$(function() {
//    $("#search_not_teacher").live('input', function (e) {
//        throttle(search_not_teacher_f,window,e);
//    });

//    $("#search_not_student").live('input', function (e) {
//        throttle(search_not_student_f,window,e);
//    });

    //模块切换
    $(".stud-class-set .news .nav").click(function(e) {
        var $a = $(e.target);
        var $b = $a.attr("data-option");
        console.log($b);
        if($b){
            $(".stud-class-set .news .nav p").removeClass("sheet");
            $(".stud-class-set .news .nav p i").hide();
            $a.addClass("sheet");
            $a.find("i").show();
            $(".stud-class-set .news .container").children().hide();
            $(".stud-class-set .news .container").find("." + $b + "").show();
        }
    });
    //操作弹框中单选复选框的选中与否
    $(".tip li").click(function(e) {

        if($(this).find(".blue").css("display") == "none") {

            $(this).find(".grey").hide();
            $(this).find(".blue").show();

        } else {

            $(this).find(".blue").hide();
            $(this).find(".grey").show();

        }
    });
    $(".student .fa").click(function() {
        console.log(1);
    });
    //教师学生模块切换
    $(".stud-class-set .news .container .member .people .left ul li").live('click', function(e) {
		//$(".stud-class-set .news .container .member .people .left ul li").removeClass("sheet");
		//$(this).addClass("sheet");
        var $course_id = $(this).attr("data-course-id");
        if($(this).attr("data-option") == "teacher") {
            $.get(
                    '/courses/'+$course_id+'/members'
            )
        }
        if($(this).attr("data-option") == "allstudent") {
            $.get(
                '/courses/'+$course_id+'/all_student_list'
            )
        }
        if($(this).attr("data-option") == "noclass") {
            $.get(
                    '/courses/'+$course_id+'/no_group_student_list'
            )
        }

        if($(this).attr("data-option") == "hasclass") {
            var $group_id = $(this).attr("data-group-id");
            $.get(
                    '/courses/'+$course_id+'/has_group_student_list?group_id='+$group_id
            )
        }

    });

//    $(".stud-class-set .news .container .member .people .left ul li .p1 i").hover(function () {
//        $(this).parent().next().show().hover(function () { clearTimeout(window.timer); }, function () { $(this).hide(); });
//    }, function (e) {
//        var dom = $(this).parent().next();
//        window.timer = setTimeout(function () { dom.hide(); }, 200); //延时隐藏,以便鼠标移动到div上时clear掉计时器
//    });

    $(".stud-class-set .news .container .member .people .left ul li .p1 i").live({
        mouseenter:
            function()
            {
                $(this).parent().next().show().hover(function () { clearTimeout(window.timer); }, function () { $(this).hide(); });
            },
        mouseleave:
            function(e)
            {
                var dom = $(this).parent().next();
                window.timer = setTimeout(function () { dom.hide(); }, 200); //延时隐藏,以便鼠标移动到div上时clear掉计时器
            }
    });

    $("#choose_course_group_submit").live('click', function(){
        if($("#course_group_id").val() == '-1'){
            $("#choose_course_group_notice").show();
        } else{
            $("#teacher_assign_group_form").submit();
            $("#choose_course_group_notice").hide();
            hideModal();
        }
    });

    $(".join .handle").live('click', function(){
        if($("input[name='member_ids[]']:checked").length > 0){
            $("#choose_course_group_form").submit();
        }
    });

    $("input[name='member_ids[]']").live('click', function(){
        if($("input[name='member_ids[]']:checked").length == $("input[name='member_ids[]']").length){
            $("#all_member_select").attr("checked", "checked");
        } else{
            $("#all_member_select").removeAttr("checked");
        }
    });

    $("#all_member_select").live('click', function(){
        if($("#all_member_select").is(':checked')){
            $("input[name='member_ids[]']").attr("checked", "checked");
        } else {
            $("input[name='member_ids[]']").removeAttr("checked");
        }
    });

    // 课堂设置
    $("#edit_course_list").on('input', function(e){
        throttle(search_course_list, window, e);
    });
    $("#edit_course_list").on('click', function (e) {
        search_course_ajax($("#edit_course_list").val().trim());
        e.stopPropagation();
    });
    $("#edit_course_list").on('blur', function(e){
        if($("#edit_course_name").val() == ""){
            $("#edit_course_name").val($("#edit_course_list").val());
        } else{
            if($("#edit_course_name").val().indexOf(course_list_name) == 0){
                $("#edit_course_name").val($("#edit_course_name").val().replace(course_list_name, $("#edit_course_list").val()));
            } else{
                $("#edit_course_name").val($("#edit_course_list").val() + $("#edit_course_name").val());
            }
        }
        course_list_name = $("#edit_course_list").val();
        regex_course_name('edit');
    });
    //页面滚动,将题目序号部分定位
    if($("#exercise_No").length > 0 ){var divtop = $("#exercise_No").offset().top;}
    $(window).scroll(function(){
        if($("#exercise_No").length > 0 ){
            var wintop=$(window).scrollTop();
            if(wintop < divtop){
                $("#exercise_No").removeClass("exercise_No");
                $("#problem_main").css("margin-top","0px");
            }else{
                $("#exercise_No").addClass("exercise_No");
                $("#problem_main").css("margin-top","171px");
            }
        }
    })

});

var d_lastSearchCondition = '';
function search_teacher_list(e, id){
    var str = $(e.target).val().trim();
    if (str == d_lastSearchCondition) {//如果输入框没有改变或者输入框为空就返回
        return;
    }
    d_lastSearchCondition = str;
    $("input[name='tea_id']").val("");
    search_teacher_ajax(str, id);
}

function search_teacher_ajax(str, id){
    $.ajax({
        url: '/graduation_topics/search_teacher?course='+id,
        data: {search: str},
        type: 'post',
        success: function (data) {
            if(data.teachers.length > 0){
                $("#add_teacher_option").empty();
                for(var i=0; i<data.teachers.length; i++){
                    $("#add_teacher_option").append('<p data-shixun-value="'+data.teachers[i][0]+'">'+data.teachers[i][1]+'</p>');
                }
                $("#add_teacher_option").show();
            } else{
                $("#add_teacher_option").empty();
            }
        }
    });
}

function submit_task_form(id){
    var result = true;
    if($("#graduate_task_type").val().trim() == ""){
        result = false;
        $("#graduate_task_name_notice").show();
    } else{
        $("#graduate_task_name_notice").hide();
    }
    if($("#graduate_task_title_name").val().trim() == ""){
        result = false;
        $("#graduate_task_title_notice").show();
    } else{
        $("#graduate_task_title_notice").hide();
    }
    if($("#graduation_content textarea").val().trim() == ""){
        result = false;
        $("#graduate_task_content_notice").show();
    } else{
        $("#graduate_task_content_notice").hide();
    }
    if(result){
        $("#"+id).submit();
    }
}

function submit_new_form(id){
    var result = true;
    if($("input[name='tea_id']").val().trim() == ""){
        result = false;
        $("#graduate_teacher_name_notice").html('<i class="fa fa-exclamation-circle mr3 font-14"></i>请从下拉列表中选择一个指导老师').show();
    } else{
        $("#graduate_teacher_name_notice").hide();
    }
    if($("#graduate_subject_name").val().trim() == ""){
        result = false;
        $("#graduate_subject_name_notice").show();
    } else{
        $("#graduate_subject_name_notice").hide();
    }
    if($("#graduation_description textarea").val().trim() == ""){
        result = false;
        $("#graduate_contrduce_notice").show();
    } else{
        $("#graduate_contrduce_notice").hide();
    }
    if(result){
        $("#"+id).submit();
    }
}

function search_graduation_topic(url){
    $.get(
        url+'&search='+$("#graduation_topic_search").val().trim()
    );
}

function add_new_group(id){
    var htmlvalue = '<div class="task-popup newclass newclassHtmlvalue">' +
        '<div class="task-popup-title clearfix task-popup-bggrey">' +
        '<h3 class="fl NewClasses">新建分班</h3>'+
    '</div>' +
        '<div class="task_popup_con clearfix">' +
            '<div class="clearfix"  style="padding-top: 10px!important;margin-bottom: 10px!important;">' +
                '<label class="panel-form-label label fl newpanel-form-label color-grey">分班:&nbsp;&nbsp;&nbsp;&nbsp;</label>' +
                '<input type="text" name="group_name" id="new_group_name" placeholder="示例:分班(最佳四个字符)" maxlength="20" class="pl10 task task-height-40 panel-box-sizing fl color-grey3 new_neygroup_name">' +
                    '<div class="cl"></div>' +
                '<span class="color-red fl none" id="add_new_group_notice" style="margin-left:10.5%;">该分班已存在</span></div>' +
                '<a href="javascript:void(0);" class="task-btn task-btn-orange fr mr20 newtaskBtn" onclick="submit_new_group_form('+id+');">确定</a>' +
                '<a href="javascript:void(0);" onclick="hideModal();" class="task-btn fr mr10 newtask-mr10btn colorFFF">取消</a>' +
            '</div>' +
        '</div>';
    pop_box_new(htmlvalue, 450, 205);
}

function submit_new_group_form(id){
    var val = $.trim($("#new_group_name").val());
    if(val == ""){
        $("#add_new_group_notice").html('名称不能为空').show();
        return false;
    } else{
        $.ajax({
            url: "/courses/"+ id +"/addgroups",
            type: 'post',
            data: {group_name: val},
            success: function(data){
                if(data.result == 0){
                    $("#add_new_group_notice").html('该分班已存在').show();
                } else{
                    $("#add_new_group_notice").hide();
                    hideModal();
                    window.location.href = "/courses/"+id+"/students";
                }
            }
        });
    }
}

function update_choose_group_allow(id){
    $.ajax({
        url: "/courses/"+ id +"/choose_group_allow",
        type: 'get',
        success: function(data){

        }
    });
}

function rename_group_name(course_id, group_id){
    var htmlvalue ='<div class="task-popup newclass newclassHtmlvalue">' +
        '<div class="task-popup-title clearfix task-popup-bggrey">' +
        '<h3 class="fl NewClasses">重命名分班</h3>'+
        '</div>' +
        '<div class="task-popup-content clearfix">' +
            '<div class="clearfix" style="padding-top: 10px!important;margin-bottom: 10px!important;">' +
            '<label class="panel-form-label label fl newpanel-form-label color-grey">分班:&nbsp;&nbsp;&nbsp;&nbsp;</label>' +
            '<input type="text" name="edit_group_name" id="edit_group_name" placeholder="示例:分班(最佳四个字符)" maxlength="20" class="pl10 task task-height-40 panel-box-sizing fl color-grey3 new_neygroup_name">' +
                '<div class="cl"></div>' +
            '<span class="color-red fl none" id="edit_new_group_notice" style="margin-left:10.5%;">该分班已存在</span></div>' +
            '<a href="javascript:void(0);" class="task-btn task-btn-orange fr mr20 newtaskBtn" onclick="submit_rename_group_form('+course_id+', '+ group_id +');">确定</a>' +
            '<a href="javascript:void(0);" onclick="hideModal();" class="task-btn fr mr10 newtask-mr10btn colorFFF">取消</a>' +
            '</div>' +
        '</div>';
    pop_box_new(htmlvalue, 450, 195);
}

function submit_rename_group_form(course_id, group_id){
    var val = $.trim($("#edit_group_name").val());
    if(val == ""){
        $("#edit_new_group_notice").html('名称不能为空').show();
        return false;
    } else{
        $.ajax({
            url: "/courses/"+ course_id +"/updategroupname",
            type: 'post',
            data: {group_name: val,
                    group_id: group_id},
            success: function(data){
                if(data.result == 0){
                    $("#edit_new_group_notice").html('该分班已存在').show();
                } else{
                    $("#edit_new_group_notice").hide();
                    hideModal();
                    window.location.href = "/courses/"+course_id+"/students?group_id="+group_id;
                }
            }
        });
    }
}

function delete_group(course_id, group_id){
    var htmlvalue = '<div class="task-popup twohint" style="width:450px">' +
        '<div class=" task-popup-title clearfix">' +
        '提示</div>' +
        '<div class="task-popup-content">' +
            '<p class="task-popup-text-center font-16">确定要删除吗?<br/> 删除分班后,该分班的学生需要重新选择分班。' +
            '</div>' +
            '<div class="task-popup-submit02 clearfix" style="width:120px;">' +
            '<a onclick="submit_delete_group_form('+course_id+', '+ group_id +');" href="javascript:void(0);" class="task-btn task-btn-orange fr">确定</a>' +
                '<a href="javascript:void(0);" onclick="hideModal();" class="task-btn fr mr10 colorFFF">取消</a>' +
            '</div>' +
        '</div>';
    pop_box_new(htmlvalue, 450, 300);
}

function submit_delete_group_form(course_id, group_id){
    hideModal();
    $.ajax({
        url: "/courses/"+ course_id +"/deletegroup?group_id=" + group_id,
        type: 'get',
        data: {},
        success: function(data){
            window.location.href = "/courses/"+course_id+"/students";
        }
    });
}

function submit_change_manager_form(){
    if($("input[name='chooseteacher']:checked").length == 0) {
        $("#change_manager_notice").show();
    } else{
        $("#change_manager_form").submit();
        hideModal();
    }
}

//var lastteSearchCondition = '';
function search_not_teacher_f(e){
//    if($(e.target).val().trim() == "" || ($(e.target).val().trim() == lastteSearchCondition && lastteSearchCondition != ''))
//    {
//        return;
//    }
//    lastteSearchCondition = $(e.target).val().trim();
    $.ajax({
        url: '/courses/' + $("#course_search_not_teacher_id").val() + '/search_not_teachers',
        type:'post',
        data: {is_observe:true, search:$("#search_not_teacher").val().trim(), school:$("#search_not_teacher_school").val().trim()},
        success: function(data){  }
    });
}

function submit_add_teacher_form(){
    if($("input[name='membership[user_ids][]']:checked").length > 0){
        $("#add_teacher_notice").html("").hide();
        $("#add_teacher_form").submit();
        hideModal();
    }else{
        $("#add_teacher_notice").html("请至少选择一个用户").show();
    }
}

function submit_teacher_list_search(id){
    $.get(
        '/courses/'+id+'/teachers?search='+$("#all_teacher_list_search").val().trim()
    )
}

function submit_all_student_list_search(id, group_id){
    $.get(
            '/courses/'+id+'/students?group_id='+group_id+'&search='+$("#all_student_list_search").val().trim()
    )
}

function submit_no_group_student_search(id){
    $.get(
            '/courses/'+id+'/students?group_id=0&search='+$("#no_group_student_list_search").val().trim()
    )
}

function submit_has_group_student_search(id, group_id){
    $.get(
         '/courses/'+id+'/students?group_id='+group_id+'&search='+$("#has_group_student_list_search").val().trim()
    )
}

//var laststSearchCondition = '';
function search_not_student_f(e){
//    if($(e.target).val().trim() == "" || ($(e.target).val().trim() == laststSearchCondition && laststSearchCondition != ''))
//    {
//        return;
//    }
//    laststSearchCondition = $(e.target).val().trim();
    $.ajax({
        url: '/courses/' + $("#course_search_not_student_id").val() + '/search_not_students',
        type:'post',
        data: {is_observe:true, search:$("#search_not_student").val().trim(), school:$("#search_not_student_school").val().trim()},
        success: function(data){ $("input[type='checkbox']").attr("checked",false); }
    });
}

function submit_add_student_form(){
    if($("input[name='membership[user_ids][]']:checked").length > 0){
        $("#add_student_notice").html("").hide();
        $("#add_student_form").submit();
        hideModal();
    }else{
        $("#add_student_notice").html("请至少选择一个用户").show();
    }
}

function res_send_to_course(id, user_id, send_type){
    $.ajax({
        type: 'get',
        url: '/users/' + user_id + '/search_user_course',
        data:{send_id:id, send_type:send_type}
    });
}

//滑动打分
$.fn.peSlider = function(settings){
    //configurable options (none so far)
    var o = $.extend({},settings);
    if( !$('body').is('[role]') ){ $('body').attr('role','application'); }
    return $(this).each(function(){
        var thisLabel = $('label[for=' + $(this).attr('id') + ']').attr('id', $(this).attr('id') + '-label').attr('id');
        var thisUnits = $(this).attr('data-units') || '';
        var slider = $('<div></div>');
        if( $(this).is('input') ){
            var input = $(this);
            var thisUnits = input.attr('data-units');
            var friendlyVal = input.val() + ' ' + thisUnits;
            var sliderOptions = $.extend(o,{
                min: parseFloat(input.attr('min')),
                max: parseFloat(input.attr('max')),
                value: parseFloat(input.val())
            });
            if(parseFloat(input.val()) == -1){
                input.css("color", "#fff");
                input.next().next().html("未评分");
                input.next().next().show();
            } else{
                input.css("color", "#29bd8b");
                input.next().next().hide();
            }
            slider
                .insertBefore(input)
                .slider(sliderOptions)
                .bind('slide', function(e, ui){
                    if(ui.value == -1){
                        input.css("color", "#fff");
                        input.next().next().html("未评分");
                        input.next().next().show();
                    } else {
                        input.css("color", "#29bd8b");
                        input.next().next().hide();
                    }
                    input.val(ui.value);
                    friendlyVal = input.val() + ' ' + thisUnits;
                    slider.find('a').attr({
                        'aria-valuenow': ui.value,
                        'aria-valuetext': friendlyVal
                    });
                })
                .find('a')
                .attr({
                    'role': 'slider',
                    'aria-valuemin': input.attr('min'),
                    'aria-valuemax': input.attr('max'),
                    'aria-valuenow': input.val(),
                    'aria-valuetext': friendlyVal,
                    'aria-labelledby': thisLabel
                });
            input
                .focus(function(){
                   if(input.val() == -1){
                       input.css("color", "#29bd8b");
                       input.val("");
                   }
                })
                .keyup(function(){
                    var inVal = parseFloat(input.val());
                    if( !isNaN(inVal) ){
                        if(inVal == -1){
                            input.css("color", "#fff");
                            input.next().next().html("未评分");
                            input.next().next().show();
                        } else {
                            input.css("color", "#29bd8b");
                            input.next().next().hide();
                        }
                        slider.slider('value', inVal);
                        input.val(slider.slider('value'));
                    }
                })
                .change(function(){
                    var inVal = parseFloat(input.val());
                    if( !isNaN(inVal) ){
                        if(inVal == -1){
                            input.css("color", "#fff");
                            input.next().next().html("未评分");
                            input.next().next().show();
                        } else {
                            input.css("color", "#29bd8b");
                            input.next().next().hide();
                        }
                        slider.slider('value', inVal);
                        input.val(slider.slider('value'));
                    }
                })
                .blur(function(){
                    var inVal = parseFloat(input.val());
                    if( isNaN(inVal) ){
                        input.val(-1);
                    }
                    if(input.val() == -1){
                        input.css("color", "#fff");
                        input.next().next().html("未评分");
                        input.next().next().show();
                    } else {
                        input.css("color", "#29bd8b");
                        input.next().next().hide();
                    }
                });
            if( !settings.step ){
                var step = Math.round( parseFloat(input.attr('max')) / slider.width());
                if(step > 1){ slider.slider('option','step',step); }
            }
        }
    });
};

$(function() {
    //匿评评分提示
    $(".student_score_info").live("mouseover", function () {
        $(this).find("div").show();
    });
    $(".student_score_info").live("mouseout", function () {
        $(this).find("div").hide();
    });
});

function regexSubject() {
    var content = $.trim($("#course_message_subject").val());
    if (content.length == 0) {
        $("#new_course_message_notice").show();
        return  false;
    }
    else {
        $("#new_course_message_notice").hide();
        return true;
    }
    return false;
}
function regexContent() {
    if(message_content_editor.isEmpty()){
        $("#new_course_message_content_notice").show();
        return  false;
    }
    else {
        $("#new_course_message_content_notice").hide();
        return true;
    }
    return false;
}

function submitCoursesBoard(){
    if(regexSubject() && regexContent()){
        message_content_editor.sync();
        $("#message-form").submit();
    }
}

function join_group(id, group_id){
    if($("#choose_member_ids").val().trim() == ""){
        $("#no_student_notice").show();
    } else{
        $("#no_student_notice").hide();
        $.ajax({
            url: '/courses/'+id+'/choose_course_group',
            type: 'post',
            data: {member_ids: $("#choose_member_ids").val(), group_id:group_id},
            remote: true,
            success: function(data){
            }
        });
        hideModal();
    }
}

function delete_students(id, group_id){
    if($("#choose_member_ids").val().trim() == ""){
        $("#no_student_notice").show();
    } else{
        $("#no_student_notice").hide();
        var htmlvalue = '<div class="task-popup" style="width:480px;"><div class="task-popup-title clearfix">提示</div>'+
            '<div class="task-popup-content"><p class="task-popup-text-center font-16">确定要删除这些学生吗?</p></div><div class="task-popup-submit clearfix"><a href="javascript:void(0);" onclick="hideModal();" class="task-btn fl colorFFF">取消</a>'+
            '<a href="javascript:void(0)" class="task-btn task-btn-orange fr pop_close" id="confirm-button">确定</a></div></div>';
        pop_box_new(htmlvalue, 480, 140);
        $("#confirm-button").on('click',function(){
            hideModal();
            $.ajax({
                url: '/courses/'+id+'/delete_course_students',
                type: 'post',
                data: {member_ids: $("#choose_member_ids").val(), group_id:group_id},
                remote: true,
                success: function(data){
                }
            });
        });
        return;
    }
}

function hidepart(item){
    var part=$(item).attr("part");
    if(part=="1"){
        $(item).attr("part","0");
        $(item).parents("p").siblings(".orther_part").hide();
        $(item).html("展开文本回答");
    }else{
        $(item).attr("part","1");
        $(item).parents("p").siblings(".orther_part").show();
        $(item).html("隐藏文本回答");
    }
}

function show_poll_edit_setting(){
    $("#show_poll_setting").hide();
    $("#edit_poll_setting").show();
    $("#poll_setting_submit_block").show();
}

$(function(){
    $("input[name='poll_publish_time']").datetimepicker({
        allowBlank:true,
        lang:'ch',
        format:'Y-m-d H:i',
        validateOnBlur:false,
        onSelectDate:function() {
            if($.trim($("input[name='poll_end_time']").val()) == ""){
                var date = new Date(Date.parse($("input[name='poll_publish_time']").val().replace(/-/g, "/")));
                $("input[name='poll_end_time']").val(formate_time(new Date(date.setMonth(date.getMonth()+1))));
            }
        },
        onSelectTime:function() {
            if($.trim($("input[name='poll_end_time']").val()) == ""){
                var date = new Date(Date.parse($("input[name='poll_publish_time']").val().replace(/-/g, "/")));
                $("input[name='poll_end_time']").val(formate_time(new Date(date.setMonth(date.getMonth()+1))));
            }
        }
    });

    $("input[name='poll_end_time']").datetimepicker({
        allowBlank:true,
        lang:'ch',
        format:'Y-m-d H:i',
        validateOnBlur:false
    });

    $("input[name='poll_publish_time_group[]']").each(function(i, obj){
        $(obj).datetimepicker({
            allowBlank:true,
            lang:'ch',
            format:'Y-m-d H:i',
            validateOnBlur:false,
            onSelectDate:function() {
                if($.trim($($("input[name='poll_end_time_group[]']")[i]).val()) == ""){
                    var date = new Date(Date.parse($(obj).val().replace(/-/g, "/")));
                    $($("input[name='poll_end_time_group[]']")[i]).val(formate_time(new Date(date.setMonth(date.getMonth()+1))));
                }
            },
            onSelectTime:function() {
                if($.trim($($("input[name='poll_end_time_group[]']")[i]).val()) == ""){
                    var date = new Date(Date.parse($(obj).val().replace(/-/g, "/")));
                    $($("input[name='poll_end_time_group[]']")[i]).val(formate_time(new Date(date.setMonth(date.getMonth()+1))));
                }
            }
        });
    });

    $("input[name='poll_end_time_group[]']").each(function(i, obj){
        $(obj).datetimepicker({
            allowBlank:true,
            lang:'ch',
            format:'Y-m-d H:i',
            validateOnBlur:false
        });
    });

    $("input[name='exercise_publish_time']").datetimepicker({
        allowBlank:true,
        lang:'ch',
        format:'Y-m-d H:i',
        validateOnBlur:false,
        onSelectDate:function() {
            if($.trim($("input[name='exercise_end_time']").val()) == ""){
                var date = new Date(Date.parse($("input[name='exercise_publish_time']").val().replace(/-/g, "/")));
                $("input[name='exercise_end_time']").val(formate_time(new Date(date.setMonth(date.getMonth()+1))));
            }
        },
        onSelectTime:function() {
            if($.trim($("input[name='exercise_end_time']").val()) == ""){
                var date = new Date(Date.parse($("input[name='exercise_publish_time']").val().replace(/-/g, "/")));
                $("input[name='exercise_end_time']").val(formate_time(new Date(date.setMonth(date.getMonth()+1))));
            }
        }
    });

    $("input[name='exercise_end_time']").datetimepicker({
        allowBlank:true,
        lang:'ch',
        format:'Y-m-d H:i',
        validateOnBlur:false
    });

    $("input[name='exercise_publish_time_group[]']").each(function(i, obj){
        $(obj).datetimepicker({
            allowBlank:true,
            lang:'ch',
            format:'Y-m-d H:i',
            validateOnBlur:false,
            onSelectDate:function() {
                if($.trim($($("input[name='exercise_end_time_group[]']")[i]).val()) == ""){
                    var date = new Date(Date.parse($(obj).val().replace(/-/g, "/")));
                    $($("input[name='exercise_end_time_group[]']")[i]).val(formate_time(new Date(date.setMonth(date.getMonth()+1))));
                }
            },
            onSelectTime:function() {
                if($.trim($($("input[name='exercise_end_time_group[]']")[i]).val()) == ""){
                    var date = new Date(Date.parse($(obj).val().replace(/-/g, "/")));
                    $($("input[name='exercise_end_time_group[]']")[i]).val(formate_time(new Date(date.setMonth(date.getMonth()+1))));
                }
            }
        });
    });

    $("input[name='exercise_end_time_group[]']").each(function(i, obj){
        $(obj).datetimepicker({
            allowBlank:true,
            lang:'ch',
            format:'Y-m-d H:i',
            validateOnBlur:false
        });
    });

    $("#unified_setting").live('click', function(){
        if($(this).is(':checked')){
            $("#unified_setting_group").show();
            $("#un_unified_setting_group").hide();
        } else {
            $("#unified_setting_group").hide();
            $("#un_unified_setting_group").show();
        }
    });
});

function show_ex_edit_setting(){
    $("#show_exercise_setting").hide();
    $("#edit_exercise_setting").show();
    $("#exam_setting_submit_block").show();
}

function hide_poll_edit_setting() {
    $("#show_poll_setting").show();
    $("#edit_poll_setting").hide();
    $("#poll_setting_submit_block").hide();
}

function hide_ex_edit_setting() {
    $("#show_exercise_setting").show();
    $("#edit_exercise_setting").hide();
    $("#exam_setting_submit_block").hide();
}

function poll_setting_form_submit(){
    var myDate = new Date();
    var result = true;
    var max_end_time = "";
    if($("#unified_setting").length == 0 || $("#unified_setting").is(':checked')){
        if($("input[name='poll_publish_time']").prop("disabled")==false && $.trim($("input[name='poll_publish_time']").val()) != ""){
            var publish_time = Date.parse($("input[name='poll_publish_time']").val());
            if(publish_time < myDate){
                $("input[name='poll_publish_time']").next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>发布时间应晚于当前时间").show();
                $("input[name='poll_publish_time']").addClass("bor-red");
                result = false;
            } else{
                $("input[name='poll_publish_time']").next('span').hide();
                $("input[name='poll_publish_time']").removeClass("bor-red");
            }
            if($.trim($("input[name='poll_end_time']").val()) == ""){
                $("input[name='poll_publish_time']").next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>截止时间不能为空").show();
                $("input[name='poll_end_time']").addClass("bor-red");
                result = false;
            }
        }
        if($("input[name='poll_end_time']").prop("disabled")==false && $.trim($("input[name='poll_end_time']").val()) != ""){
            if($.trim($("input[name='poll_publish_time']").val()) == ""){
                $("#poll_publish_time").val(formate_time(myDate));
            }
            var publish_time = Date.parse($("input[name='poll_publish_time']").val());
            var end_time = Date.parse($("input[name='poll_end_time']").val());
            if(end_time <= publish_time){
                $("input[name='poll_end_time']").next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>截止时间应晚于发布时间").show();
                $("input[name='poll_end_time']").addClass("bor-red");
                result = false;
            }
            else{
                $("input[name='poll_end_time']").next('span').hide();
                $("input[name='poll_end_time']").removeClass("bor-red");
            }
        }
        max_end_time = $.trim($("input[name='poll_end_time']").val()) == "" ? "" : Date.parse($.trim($("input[name='poll_end_time']").val()));
    } else {
        $("input[name='poll_publish_time_group[]']").each(function(i, obj) {
            var end_time_obj = $($("input[name='poll_end_time_group[]']")[i]);
            if($(obj).prop("disabled")==false && $.trim($(obj).val()) != ""){
                var publish_time = Date.parse($(obj).val());
                if(publish_time < myDate){
                    $(obj).next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>发布时间应晚于当前时间").show();
                    $(obj).addClass("bor-red");
                    result = false;
                    if(scroll){
                        $(document).scrollTop(parseInt($(obj).offset().top)-150);
                        scroll=false;//已经定位后、后续报错部分就不用定位了
                    }
                } else{
                    $(obj).next('span').hide();
                    $(obj).removeClass("bor-red");
                }
                if($.trim(end_time_obj.val()) == ""){
                    end_time_obj.next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>截止时间不能为空").show();
                    end_time_obj.addClass("bor-red");
                    result = false;
                    if(scroll){
                        $(document).scrollTop(parseInt(end_time_obj.offset().top)-150);
                        scroll=false;//已经定位后、后续报错部分就不用定位了
                    }
                }
            }
            if(end_time_obj.prop("disabled")==false && $.trim(end_time_obj.val()) != ""){
                if($.trim($(obj).val()) == ""){
                    $(obj).val(formate_time(myDate));
                }
                var publish_time = Date.parse($(obj).val());
                var end_time = Date.parse(end_time_obj.val());
                if(end_time <= publish_time){
                    end_time_obj.next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>截止时间应晚于发布时间").show();
                    end_time_obj.addClass("bor-red");
                    result = false;
                    if(scroll){
                        $(document).scrollTop(parseInt(end_time_obj.offset().top)-150);
                        scroll=false;//已经定位后、后续报错部分就不用定位了
                    }
                } else{
                    end_time_obj.next('span').hide();
                    end_time_obj.removeClass("bor-red");
                }
            }
        });

        $("input[name='poll_end_time_group[]']").each(function(i, obj){
            if($(obj).val() > max_end_time){
                max_end_time = $(obj).val();
            }
        });
        max_end_time = max_end_time == "" ? max_end_time : Date.parse(max_end_time);
    }

    if(result){
        if(max_end_time == ""){
            var current_time = formate_time_s(new Date());
            var date =  new Date(new Date().setTime(Math.ceil(new Date().getTime()/3600000.0)*3600000));
            var aMonthSince = new Date(date.setMonth(date.getMonth()+1));
            var end_time = formate_time_s(aMonthSince);
            var htmlvalue = '<div class="task-popup" style="width:360px;"><div class="task-popup-title clearfix task-popup-bggrey"><h3 class="fl color-grey3">立即发布</h3><a href="javascript:void(0);" class="pop_close"><i class="fa fa-times-circle font-18 link-color-grey fr mt5"></i></a></div>'+
                '<div class="task-popup-content"><div class="alert alert-orange mb15">发布设置均可修改,<a href="javascript:void(0);" onclick="$(document).scrollTop(0); hideModal();" class="color-orange04" style="text-decoration: underline;">点击修改</a><br/>此设置将对所有的分班生效</div>'+
                '<p class="color-grey">发布时间:<span class="ml10">'+current_time+'</span></p><p class="color-grey">截止时间:<span class="ml10">'+end_time+'</span></p>'+
                '<div class="cl"></div><div class="fr"><a href="javascript:void(0);" class="task-btn task-btn-orange fr" onclick="$(\'#poll_setting_form\').submit();hideModal();">确定</a><a href="javascript:void(0)" class="task-btn fr pop_close mr10" onclick="hideModal();">取消</a></div>'
                +'<div class="cl"></div></div></div>';
            pop_box_new(htmlvalue, 360, 270);
        } else{
            $("#poll_setting_form").submit();
        }
    }
}

function ex_setting_form_submit(){
    var myDate = new Date();
    var result = true;
    var max_end_time = "";
    if($("#unified_setting").length == 0 || $("#unified_setting").is(':checked')){
        if($("input[name='exercise_publish_time']").prop("disabled")==false && $.trim($("input[name='exercise_publish_time']").val()) != ""){
            var publish_time = Date.parse($("input[name='exercise_publish_time']").val());
            if(publish_time < myDate){
                $("input[name='exercise_publish_time']").next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>发布时间应晚于当前时间").show();
                $("input[name='exercise_publish_time']").addClass("bor-red");
                result = false;
            } else{
                $("input[name='exercise_publish_time']").next('span').hide();
                $("input[name='exercise_publish_time']").removeClass("bor-red");
            }
            if($.trim($("input[name='exercise_end_time']").val()) == ""){
                $("input[name='exercise_publish_time']").next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>截止时间不能为空").show();
                $("input[name='exercise_end_time']").addClass("bor-red");
                result = false;
            }
        }
        if($("input[name='exercise_end_time']").prop("disabled")==false && $.trim($("input[name='exercise_end_time']").val()) != ""){
            if($.trim($("input[name='exercise_publish_time']").val()) == ""){
                $("#exercise_publish_time").val(formate_time(myDate));
            }
            var publish_time = Date.parse($("input[name='exercise_publish_time']").val());
            var end_time = Date.parse($("input[name='exercise_end_time']").val());
            if(end_time <= publish_time){
                $("input[name='exercise_end_time']").next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>截止时间应晚于发布时间").show();
                $("input[name='exercise_end_time']").addClass("bor-red");
                result = false;
            }
            else{
                $("input[name='exercise_end_time']").next('span').hide();
                $("input[name='exercise_end_time']").removeClass("bor-red");
            }
        }
        max_end_time = $.trim($("input[name='exercise_end_time']").val()) == "" ? "" : Date.parse($.trim($("input[name='exercise_end_time']").val()));

    } else {
        $("input[name='exercise_publish_time_group[]']").each(function(i, obj){
            var end_time_obj = $($("input[name='exercise_end_time_group[]']")[i]);
            if($(obj).prop("disabled")==false && $.trim($(obj).val()) != ""){
                var publish_time = Date.parse($(obj).val());
                if(publish_time < myDate){
                    $(obj).next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>发布时间应晚于当前时间").show();
                    $(obj).addClass("bor-red");
                    result = false;
                    if(scroll){
                        $(document).scrollTop(parseInt(end_time_obj.offset().top)-150);
                        scroll=false;//已经定位后、后续报错部分就不用定位了
                    }
                } else{
                    $(obj).next('span').hide();
                    $(obj).removeClass("bor-red");
                }

                if($.trim(end_time_obj.val()) == ""){
                    end_time_obj.next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>截止时间不能为空").show();
                    result = false;
                    if(scroll){
                        $(document).scrollTop(parseInt(end_time_obj.offset().top)-150);
                        scroll=false;//已经定位后、后续报错部分就不用定位了
                    }
                } else{
                    end_time_obj.next('span').hide();
                    end_time_obj.removeClass("bor-red");
                }
            }

            if(end_time_obj.prop("disabled")==false && $.trim(end_time_obj.val()) != ""){
                if($.trim($(obj).val()) == ""){
                    $(obj).val(formate_time(myDate));
                }
                var publish_time = Date.parse($(obj).val());
                var end_time = Date.parse(end_time_obj.val());
                if(end_time <= publish_time){
                    end_time_obj.next('span').html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>截止时间应晚于发布时间").show();
                    result = false;
                    end_time_obj.addClass("bor-red");
                    if(scroll){
                        $(document).scrollTop(parseInt(end_time_obj.offset().top)-150);
                        scroll=false;
                    }
                } else{
                    end_time_obj.next('span').hide();
                    end_time_obj.removeClass("bor-red");
                }
            }
        });

        $("input[name='exercise_end_time_group[]']").each(function(i, obj){
            if($(obj).val() > max_end_time){
                max_end_time = $(obj).val();
            }
        });
        max_end_time = max_end_time == "" ? max_end_time : Date.parse(max_end_time);
    }

    if($("#exercise_setting_time").val().trim() != ""){
        var time = $("#exercise_setting_time").val().trim();
        var regex = /^[1-9]\d*$/;
        if(!regex.test(time)){
            result = false;
            $("#exercise_time_notice").html("<i class='fa fa-exclamation-circle mr5 color-orange'></i>请输入正整数").show();
            $("input[name='time']").addClass("bor-red");
        }else{
            $("#exercise_time_notice").hide();
            $("input[name='time']").removeClass("bor-red");
        }
    }
    if(result){
        if(max_end_time == ""){
            var current_time = formate_time_s(new Date());
            var date =  new Date(new Date().setTime(Math.ceil(new Date().getTime()/3600000.0)*3600000));
            var aMonthSince = new Date(date.setMonth(date.getMonth()+1));
            var end_time = formate_time_s(aMonthSince);
            var htmlvalue = '<div class="task-popup" style="width:360px;"><div class="task-popup-title clearfix task-popup-bggrey"><h3 class="fl color-grey3">立即发布</h3><a href="javascript:void(0);" class="pop_close"><i class="fa fa-times-circle font-18 link-color-grey fr mt5"></i></a></div>'+
                '<div class="task-popup-content"><div class="alert alert-orange mb15">发布设置均可修改,<a href="javascript:void(0);" onclick="$(document).scrollTop(0); hideModal();" class="color-orange04" style="text-decoration: underline;">点击修改</a><br/>此设置将对所有的分班生效</div>'+
                '<p class="color-grey">发布时间:<span class="ml10">'+current_time+'</span></p><p class="color-grey">截止时间:<span class="ml10">'+end_time+'</span></p>'+
                '<div class="cl"></div><div class="fr"><a href="javascript:void(0);" class="task-btn task-btn-orange fr" onclick="$(\'#exercise_setting_form\').submit();hideModal();">确定</a><a href="javascript:void(0)" class="task-btn fr pop_close mr10" onclick="hideModal();">取消</a></div>'
                +'<div class="cl"></div></div></div>';
            pop_box_new(htmlvalue, 360, 270);
        } else{
            $("#exercise_setting_form").submit();
        }
    }
}

//添加标题时确定按钮
function add_poll_question_new(doc)
{
    var result = true;
    new_quetion_title_editor.sync();
    var title = $.trim($("#poll_questions_title").val());
    if(title.length == 0){
        notice_box("标题不能为空");
        result = false;
    }
    if(doc.parent().parent().parent().find("input[name='min_choices']").length > 0 && doc.parent().parent().parent().find("input[name='max_choices']").length > 0){
        var min_choices = doc.parent().parent().parent().find("input[name='min_choices']");
        var max_choices = doc.parent().parent().parent().find("input[name='max_choices']");
        var test_str = /^[0-9]*$/;
        if(!test_str.test(min_choices.val()) || !test_str.test(max_choices.val()) || parseInt(min_choices.val()) > parseInt(max_choices.val()) || parseInt(min_choices.val()) > parseInt(min_choices.attr("max")) || parseInt(max_choices.val()) > (max_choices.attr("max"))){
            notice_box("可选项设置有误");
            result = false;
        }
    }

    var textareas = doc.parent().parent().parent().find("textarea.candiate_answer");
    if(textareas.length > 0){
        for(var i=0; i < textareas.length; i ++){
            if($(textareas[i]).val().trim() == ""){
                notice_box("选项不能为空");
                doc.one('click', function(){
                    add_poll_question_new($(this));
                });
                result = false;
                return false;
            }
        }
    }
    if(result){
        doc.parent().parent().parent().parent().submit();
    } else{
        doc.one('click', function(){
            add_poll_question_new($(this));
        });
    }
}

function add_ex_question(doc,quest_type)
{
    var result = true;
    new_quetion_title_editor.sync();
    var title = $.trim($("#poll_questions_title").val());
    var score = $.trim($("#question_score").val());
    var standard_ans = $.trim($("#exercise_choice_" + quest_type).val());

    if (quest_type == 5) {
        var name = $.trim($("#poll_questions_name").val());
        if(name===""){
            notice_box("题目标题不能为空");
            result = false;
        }
    }

    if(title.length == 0){
        if(quest_type != 5){
            notice_box("题目标题不能为空");
        } else {
            notice_box("题目要求不能为空");
        }
        result = false;
    } else if(quest_type != 5){
        if(score.length == 0){
            notice_box("分数不能为空");
            result = false;
        } else{
            if(!/^[1-9][0-9]*$/.test(score)) {
                notice_box("分数必须是非零开头的数字");
                result = false;
            }else if(quest_type == 1 && standard_ans.length == 0) {
                notice_box("标准答案不能为空");
                result = false;
            }else if(quest_type == 2 && standard_ans.length < 2) {
                notice_box("标准答案至少有两个选项");
                result = false;
            } else if(quest_type == 1 || quest_type == 2){
                var textareas = doc.parent().parent().parent().find("textarea.candiate_answer");
                for(var i=0; i < textareas.length; i ++){
                    if($(textareas[i]).val().trim() == ""){
                        notice_box("选项不能为空");
                        doc.one('click', function(){
                            add_ex_question($(this),quest_type);
                        });
                        return false;
                    }
                }
            }
        }
        if (quest_type == 3) {
            var textareas = doc.parent().parent().parent().find("textarea.candiate_answer");
            if (textareas.length > 0) {
                for (i = 0; i < textareas.length; i++) {
                    if ($.trim($(textareas[i]).val()) == "") {
                        notice_box("参考答案不能为空");
                        doc.one('click', function(){
                            add_ex_question($(this),quest_type);
                        });
                        return false;
                    }
                }
            } else {
                notice_box("参考答案不能为空");
                result = false;
            }
        }
    } else if(quest_type == 5){
        var scores = $("input[name='question_score[]']");
        for(var i=0; i < scores.length; i++){
            if($(scores[i]).val().trim() == ""){
                notice_box("关卡分数不能为空");
                doc.one('click', function(){
                    add_ex_question($(this),quest_type);
                });
                return false;
            } else if(!/^[0-9]*$/.test($(scores[i]).val().trim())) {
                notice_box("分数必须是数字");
                doc.one('click', function(){
                    add_ex_question($(this),quest_type);
                });
                return false;
            }
        }
    }
    if (result){
        $(doc).parents("form").submit();
    } else{
        doc.one('click', function(){
            add_ex_question($(doc),quest_type);
        });
    }
}

function poll_head_submit(doc){
    var title = $.trim($("#poll_name").val());
    if(title.length == 0){
        notice_box("问卷标题不能为空");
    } else {
        doc.parent().parent().submit();
    }
}

function ex_head_submit(doc){
    var title = $.trim($("#exercise_name").val());
    if(title.length == 0){
        notice_box("试卷标题不能为空");
    } else {
        doc.parent().parent().submit();
    }
}

function ex_head_cancel(){
    $("#exercise_head_edit").hide();
    $("#exercise_head_show").show();
}

function pollsCancel(){
    $("#polls_head_edit").hide();
    $("#polls_head_show").show();
}

function pollsSubmit(doc){
    var title = $.trim($("#polls_title").val());
    if(title.length == 0){
        notice_box("问卷标题不能为空");
    } else{
        doc.parent().parent().submit();
    }
}
function pollsEdit(){
    $("#polls_head_edit").show();
    $("#polls_head_show").hide();
}

function pollQuestionEdit(question_id){
    var forms = $("form.new_poll_question");
    if($.trim($("#insert_new_poll_question_"+question_id).html()) == "") {
        if(forms.length > 0){
            notice_box("请先保存正在编辑的题目再编辑。");
        } else{
            $("#show_poll_questions_"+question_id).hide();
            $("#edit_poll_questions_"+question_id).show();
            $("#poll_questions_title_"+question_id).focus();
            KindEditor.ready(function(K){
                $("div#edit_poll_questions_"+question_id).each(function(){
                    var params = {};
                    params.kindutil = K;
                    params.div_form = $(this);
                    params.form = $("form",params.div_form);
                    if(params.form==undefined || params.form.length==0){
                        return;
                    }
                    params.placeholder = "请输入题干";
                    params.textarea = $("textarea[name='question_title']",params.div_form);
                    if(params.textarea.data('init') == undefined) {
                        params.editor = init_exercise_quetison_editor(params);
                        edit_quetion_title_editor = params.editor;
                        params.textarea.data('init', 1);
                    }
                });
            });
        }
    } else{
        notice_box("请先保存正在编辑的题目再编辑。");
    }
}

// 编辑问卷题库题目
function pollBankQuestionEdit(question_id){
    var forms = $("form.new_exercise_bank_question");
    if($.trim($("#insert_new_poll_question_"+question_id).html()) == "") {
        if(forms.length > 0){
            notice_box("请先保存正在编辑的题目再编辑。");
        } else{
            $("#show_poll_questions_"+question_id).hide();
            $("#edit_poll_questions_"+question_id).show();
            $("#poll_questions_title_"+question_id).focus();
            KindEditor.ready(function(K){
                $("div#edit_poll_questions_"+question_id).each(function(){
                    var params = {};
                    params.kindutil = K;
                    params.div_form = $(this);
                    params.form = $("form",params.div_form);
                    if(params.form==undefined || params.form.length==0){
                        return;
                    }
                    params.placeholder = "请输入题干";
                    params.textarea = $("textarea[name='question_title']",params.div_form);
                    if(params.textarea.data('init') == undefined) {
                        params.editor = init_exercise_quetison_editor(params);
                        edit_quetion_title_editor = params.editor;
                        params.textarea.data('init', 1);
                    }
                });
            });
        }
    } else{
        notice_box("请先保存正在编辑的题目再编辑。");
    }
}

function exQuestionEdit(question_id, question_type, url){
    var forms = $("form.new_exercise_question");
    if($.trim($("#insert_new_poll_question_"+question_id).html()) == "") {
        if(forms.length > 0){
            notice_box("请先保存正在编辑的题目再编辑。");
        } else{
            $("#show_poll_questions_"+question_id).hide();
            $("#edit_poll_questions_"+question_id).show();
            $("#poll_questions_title_"+question_id).focus();
            KindEditor.ready(function(K){
                $("div#edit_poll_questions_"+question_id).each(function(){
                    var params = {};
                    params.kindutil = K;
                    params.div_form = $(this);
                    params.form = $("form",params.div_form);
                    if(params.form==undefined || params.form.length==0){
                        return;
                    }
                    params.placeholder = "请输入题干";
                    params.textarea = $("textarea[name='question_title']",params.div_form);
                    if(params.textarea.data('init') == undefined) {
                        params.editor = init_exercise_quetison_editor(params);
                        edit_quetion_title_editor = params.editor;
                        params.textarea.data('init', 1);
                    }
                });
            });
            if(question_type == 3){
                var choices = $("#edit_poll_questions_"+question_id).find(".single_choice");
                var choice_length = choices.length;
                for(var i=0; i<choice_length; i++){
                    create_editorMD($(choices[i]).attr("id"), "89.8%", 120, "请输入参考答案", url);
                }
            } else if(question_type == 4){
                create_editorMD("new_multi_answer_"+question_id, "89.8%", 150, "请输入参考答案", url);
            }
        }
    } else{
        notice_box("请先保存正在编辑的题目再编辑。");
    }
}

// 编辑试卷题库题目
function exBankQuestionEdit(question_id, question_type, url){
    var forms = $("form.new_exercise_bank_question");
    if($.trim($("#insert_new_poll_question_"+question_id).html()) == "") {
        if(forms.length > 0){
            notice_box("请先保存正在编辑的题目再编辑。");
        } else{
            $("#show_poll_questions_"+question_id).hide();
            $("#edit_poll_questions_"+question_id).show();
            $("#poll_questions_title_"+question_id).focus();
            KindEditor.ready(function(K){
                $("div#edit_poll_questions_"+question_id).each(function(){
                    var params = {};
                    params.kindutil = K;
                    params.div_form = $(this);
                    params.form = $("form",params.div_form);
                    if(params.form==undefined || params.form.length==0){
                        return;
                    }
                    params.placeholder = "请输入题干";
                    params.textarea = $("textarea[name='question_title']",params.div_form);
                    if(params.textarea.data('init') == undefined) {
                        params.editor = init_exercise_quetison_editor(params);
                        edit_quetion_title_editor = params.editor;
                        params.textarea.data('init', 1);
                    }
                });
            });
            if(question_type == 3){
                var choices = $("#edit_poll_questions_"+question_id).find(".single_choice");
                var choice_length = choices.length;
                for(var i=0; i<choice_length; i++){
                    create_editorMD($(choices[i]).attr("id"), "89.8%", 120, "请输入参考答案", url);
                }
            } else if(question_type == 4){
                create_editorMD("new_multi_answer_"+question_id, "89.8%", 150, "请输入参考答案", url);
            }
        }
    } else{
        notice_box("请先保存正在编辑的题目再编辑。");
    }
}

//编辑题目时确定按钮
function edit_p_question(doc,id)
{
    var result = true;
    edit_quetion_title_editor.sync();
    var title = $.trim($("#poll_questions_title_" + id).val());
    if(title.length == 0){
        noctice_box("标题不能为空");
        result = false;
    }
    if(doc.parent().parent().parent().find("input[name='min_choices']").length > 0 && doc.parent().parent().parent().find("input[name='max_choices']").length > 0){
        var min_choices = doc.parent().parent().parent().find("input[name='min_choices']");
        var max_choices = doc.parent().parent().parent().find("input[name='max_choices']");
        var test_str = /^[0-9]*$/;
        if(!test_str.test(min_choices.val()) || !test_str.test(max_choices.val()) || parseInt(min_choices.val()) > parseInt(max_choices.val()) || parseInt(min_choices.val()) > parseInt(min_choices.attr("max")) || parseInt(max_choices.val()) > (max_choices.attr("max"))){
            notice_box("可选项设置有误");
            result = false;
        }
    }
    var textareas = doc.parent().parent().parent().find("textarea.candiate_answer");
    if(textareas.length > 0){
        for(var i=0; i < textareas.length; i ++){
            if($(textareas[i]).val().trim() == ""){
                notice_box("选项不能为空");
                result = false;
                return false;
            }
        }
    }
    if(result){
        doc.parent().parent().parent().parent().submit();
    }
}

function edit_poll_question(doc,id,quest_type) {
    var result = true;
    edit_quetion_title_editor.sync();
    var title = $.trim($("#poll_questions_title_" + id).val());
    var score = $.trim($("#poll_question_score_" + id).val());
    var standard_ans = $.trim($("#exercise_choice_" + id).val());
    if (quest_type == 5) {
        var name = $.trim($("#poll_questions_name_" + id).val());
        if(name===""){
            notice_box("题目标题不能为空");
            result = false;
        }
    }
    if (title.length == 0) {
        if (quest_type != 5) {
            notice_box("题目标题不能为空");
        } else {
            notice_box("题目要求不能为空");
        }
        result = false;
    } else if (quest_type != 5) {
        if (score.length == 0) {
            notice_box("分数不能为空");
            result = false;
        } else {
            if (!/^[1-9][0-9]*$/.test(score)) {
                notice_box("分数必须是非零开头的数字");
                result = false;
            } else if (quest_type == 1 && standard_ans.length == 0) {
                notice_box("标准答案不能为空");
                result = false;
            } else if (quest_type == 2 && standard_ans.length < 2) {
                notice_box("标准答案至少有两个选项");
                result = false;
            } else if(quest_type == 1 || quest_type == 2){
                var textareas = doc.parent().parent().parent().find("textarea.candiate_answer");
                for(var i=0; i < textareas.length; i ++){
                    if($(textareas[i]).val().trim() == ""){
                        notice_box("选项不能为空");
                        return false;
                    }
                }
            }
        }
        if (quest_type == 3) {
            var div = $("#poll_answers_" + id);
            var candiate_answer = $(".candiate_answer", div);
            if (candiate_answer.length > 0) {
                for (i = 0; i < candiate_answer.length; i++) {
                    if (i < candiate_answer.length - 1 && $.trim($(candiate_answer[i]).val()) == "") {
                        continue;
                    } else if (i == (candiate_answer.length - 1) && $.trim($(candiate_answer[i]).val()) == "") {
                        notice_box("参考答案不能为空");
                        result = false;
                    } else if ($.trim($(candiate_answer[i]).val()) != "") {

                    }
                }
            } else {
                notice_box("参考答案不能为空");
                result = false;
            }
        }
    } else if (quest_type == 5) {
        var scores = $("input[name='question_score[]']");
        for (var i = 0; i < scores.length; i++) {
            if ($(scores[i]).val().trim() == "") {
                notice_box("关卡分数不能为空");
                return false;
            } else if (!/^[0-9]*$/.test($(scores[i]).val().trim())) {
                notice_box("分数必须是数字");
                return false;
            }
        }
    }
    if (result) {
        $("#update_exercise_question_"+id).submit();
    }
}

/*试卷*/
/*填空题操作*/
function addfill(item, imageUrl){
    var bt = baidu.template;
    bt.LEFT_DELIMITER = '<!';
    bt.RIGHT_DELIMITER = '!>';
    var html = bt('t:set-fillin-lists', null);
    $(item).parent().parent('.clearfix').before(html);
    $(item).parent().parent('.clearfix').prev().find('textarea').attr("name", "exercise_choice["+new Date().getTime()+"]");
    //var inputs = document.getElementsByName("exercise_choice[]");
    var inputs_spans=$(item).parents(".fillin_Temp").find("li span[name='fill_span']");
    //var inputs_spans = document.getElementsByName("fill_span");
    document.getElementsByName("test_set[input][]");
    for (var j = 0; j < inputs_spans.length; j++) {
        var countChar = convert_to_chi_num(j+1);
        $(inputs_spans[j]).html("答案 "+countChar);
    }
    $(item).parent().parent('.clearfix').prev().find('div').attr("id", "new_single_answer_"+inputs_spans.length);
    create_editorMD("new_single_answer_"+inputs_spans.length, "89.8%", 120, "请输入参考答案(可选)", imageUrl);
    //$(inputs[inputs.length - 1]).focus();
}

function convert_to_chi_num(num){
    var toChar="";
    switch(num){
        case 1:
            return toChar="一";
            break;
        case 2:
            return toChar="二";
            break;
        case 3:
            return toChar="三";
            break;
        case 4:
            return toChar="四";
            break;
        case 5:
            return toChar="五";
            break;
        case 6:
            return toChar="六";
            break;
        case 7:
            return toChar="七";
            break;
        case 8:
            return toChar="八";
            break;
        case 9:
            return toChar="九";
            break;
    }
}

function removefill(item){
    var temp=$(item).parents(".fillin_Temp");
    $(item).parents('li').remove();
    var inputs_spans=temp.find("li span[name='fill_span']");
    //var inputs_spans = document.getElementsByName("fill_span");
    for (var j = 0; j < parseInt(inputs_spans.length); j++) {
        var countChar=convert_to_chi_num(j+1);
        $(inputs_spans[j]).html("答案 "+countChar);
    }
}

/*选择题操作*/
function removeMuli(item){
    var temp=$(item).parents("li").siblings("div").find(".current-option");
    var count=0;
    var exercise_choice = $(item).parents(".multiple_Temp").find("input[name='exercise_choice']");
    var muil=$(item).parents(".multiple_Temp").find(".check-option-bg");
    var pare=$(item).parents(".multiple_Temp");
    if($(item).parents("li").find("label span").hasClass("check-option-bg")){
        count++;
    }
    $(item).parents('li').remove();
    var inputs_spans=pare.find("li span[name='option_spans']");
    //var inputs_spans = document.getElementsByName("option_spans");
    for (var j = 0; j < parseInt(inputs_spans.length); j++) {
        if(j >= 0 && j <= 26){
            $(inputs_spans[j]).html(String.fromCharCode(65 + j));
        }
    }

    temp.html("");
    if(parseInt(muil.length)-count>0){
        for(var i=0;i<parseInt(muil.length)-count;i++){
            temp.html(temp.html()+muil.eq(i).html());
        }
        exercise_choice.val(temp.html());
    }else{
        exercise_choice.val('');
        temp.html("请点击正确选项");
    }
}

function addMuli(item){
    var bt = baidu.template;
    bt.LEFT_DELIMITER = '<!';
    bt.RIGHT_DELIMITER = '!>';
    var html = bt('t:set-option-lists', null);
    $(item).parent().parent('.clearfix').before(html);
    $(item).parent().parent('.clearfix').prev().find('textarea').attr("name", "question_answer["+new Date().getTime()+"]");

    var inputs_spans=$(item).parents(".multiple_Temp").find("li span[name='option_spans']");
    //var inputs_spans = document.getElementsByName("option_spans");
    for (var j = 0; j < inputs_spans.length; j++) {
        if(j >= 0 && j <= 26){
            $(inputs_spans[j]).html(String.fromCharCode(65 + j));
        }
    }
    for (var i = 0; i < $(".candiate_answer").length; i++) {
        autoTextarea($(".candiate_answer")[i], 0, 140);
    }
}

function selectMul(item){
    var temp=$(item).parents(".multiple_Temp");
    var exercise_choice = $(temp).find("input[name='exercise_choice']");
    temp.find("li").removeClass("check-option-bg");
    $(item).toggleClass("check-option-bg");

    temp.find(".current-option").html("");
    if(temp.find(".check-option-bg").length>0){
        for(var i=0;i<temp.find(".check-option-bg").length;i++){
            temp.find(".current-option").html(temp.find(".current-option").html()+temp.find(".check-option-bg").eq(i).html());
        }
        exercise_choice.val(temp.find(".current-option").html());
    }else{
        temp.find(".current-option").html("请点击正确选项");
        exercise_choice.val('');
    }
}

function addOtherSingle(item){
    var bt = baidu.template;
    bt.LEFT_DELIMITER = '<!';
    bt.RIGHT_DELIMITER = '!>';
    var html = bt('t:set-other-option-lists', null);
    if($(item).parent().parent().parent().find('textarea[name="question_other_answer"]').length == 0){
        $(item).parent().parent('.clearfix').prev().before(html);
        var max_size = $(item).parents(".multiple_Temp").find('textarea[name="question_other_answer"]').length + $(item).parents(".multiple_Temp").find('.candiate_answer').length;
        $($(item).parents(".multiple_Temp").find("input[name='min_choices']")[0]).attr("max", max_size);
        $($(item).parents(".multiple_Temp").find("input[name='max_choices']")[0]).attr("max", max_size);
    } else{
        notice_box("只能添加一个‘其他’选项");
    }
}

/*单选题操作*/
function addSingle(item){
    var bt = baidu.template;
    bt.LEFT_DELIMITER = '<!';
    bt.RIGHT_DELIMITER = '!>';
    var html = bt('t:set-option-list', null);
    if($(item).parent().parent().parent().find('textarea[name="question_other_answer"]').length == 0){
        $(item).parent().parent('.clearfix').before(html);
        $(item).parent().parent('.clearfix').prev().find('textarea').attr("name", "question_answer["+new Date().getTime()+"]");
    } else{
        $(item).parent().parent('.clearfix').prev().before(html);
        $(item).parent().parent('.clearfix').prev().prev().find('textarea').attr("name", "question_answer["+new Date().getTime()+"]");
    }
    var inputs_spans=$(item).parents(".single_Temp").find("li span[name='option_span']");
    //var inputs_spans = document.getElementsByName("option_span");
    for (var j = 0; j < inputs_spans.length; j++) {
        if(j >= 0 && j <= 26){
            $(inputs_spans[j]).html(String.fromCharCode(65 + j));
        }
    }
    for (var i = 0; i < $(".candiate_answer").length; i++) {
        autoTextarea($(".candiate_answer")[i], 0, 140);
    }
    var max_size = $(item).parents(".multiple_Temp").find('textarea[name="question_other_answer"]').length + $(item).parents(".multiple_Temp").find('.candiate_answer').length;
    $($(item).parents(".multiple_Temp").find("input[name='min_choices']")[0]).attr("max", max_size);
    $($(item).parents(".multiple_Temp").find("input[name='max_choices']")[0]).attr("max", max_size);
}
function removeSingle(item){
    var temp=$(item).parents("li").siblings("div").find(".current-option");
    var exercise_choice = $(item).parents(".single_Temp").find("input[name='exercise_choice']");
    var singl=$(item).parents(".single_Temp").find(".check-option-bg");
    var pare=$(item).parents(".single_Temp");
    temp.html("");
    var count=0;
    if($(item).parents("li").find("label span").hasClass("check-option-bg")){
        count++;
    }
    var max_size = $(item).parents(".multiple_Temp").find('textarea[name="question_other_answer"]').length + $(item).parents(".multiple_Temp").find('.candiate_answer').length;
    $($(item).parents(".multiple_Temp").find("input[name='min_choices']")[0]).attr("max", max_size - 1);
    $($(item).parents(".multiple_Temp").find("input[name='max_choices']")[0]).attr("max", max_size - 1);
    $(item).parents('li').remove();
    var inputs_spans=pare.find("li span[name='option_span']");
    for (var j = 0; j < parseInt(inputs_spans.length); j++) {
        if(j >= 0 && j <= 26){
            $(inputs_spans[j]).html(String.fromCharCode(65 + j));
        }
    }

    if(parseInt(singl.length)-count>0){
        for(var i=0;i<parseInt(singl.length)-count;i++){
            temp.html(temp.html()+singl.eq(i).html());
        }
        exercise_choice.val(temp.html());
    }else{
        temp.html("请点击正确选项");
        exercise_choice.val('');
    }
}
function selectchoice(item){
    var temp=$(item).parents(".single_Temp");
    var exercise_choice = $(temp).find("input[name='exercise_choice']");
    $(temp).find("li span").removeClass("check-option-bg");
    $(item).toggleClass("check-option-bg");

    temp.find(".current-option").html("");
    if(temp.find(".check-option-bg").length>0){
        for(var i=0;i<temp.find(".check-option-bg").length;i++){
            temp.find(".current-option").html(temp.find(".current-option").html()+temp.find(".check-option-bg").eq(i).html());
        }
        exercise_choice.val(temp.find(".current-option").html());
    }else{
        temp.find(".current-option").html("请点击正确选项");
        exercise_choice.val('');
    }
}

function copy_course(url){
    var htmlvalue = '<div class="task-popup" style="width:550px;"><div class="task-popup-title clearfix"><h3 class="fl color-grey3">提示</h3><a href="javascript:void(0);" class="pop_close"><i class="fa fa-times-circle font-18 link-color-grey fr mt5"></i></a></div>'+
        '<div class="task-popup-content"><div class="task-popup-text-center font-16">'
        +'<div style="width: 450px;margin: 0px auto;text-align: left;"><p>复制将在后台执行</p><p>平台将为你创建一个新的同名课堂,请问是否继续?</p><p>作业、资源、试卷都将复制到新课堂</p></div>'
        + '</div></div><div class="task-popup-submit clearfix"><a href="javascript:void(0);" onclick="hideModal();" class="task-btn fl">取消</a>'+
        '<a href="'+url+'" class="task-btn task-btn-orange fr" onclick="hideModal();">确定</a></div></div>';
    pop_box_new(htmlvalue, 550, 300);
}

function new_shixun_exercise(id){
    if($("input[name='shixun_exercise']:checked").length == 0){
        $("#exercise_type_notice").show();
    } else{
        var type=$("input[name='shixun_exercise']:checked").val();
        $("#shixun_exercise_question").submit();
        hideModal();
    }
}


function scroll_70height(num){
    window.location.href="#mao"+num;
    var top=$(document).scrollTop();

    var mt=$("#problem_main").css("margin-top");
    $(document).scrollTop(parseInt(top)-230);

    /*var Notop = $("#exercise_No").offset().top;
    var Noheight = $("#exercise_No").height();
    if(parseInt(top) - 70 > parseInt(Notop) + parseInt(Noheight)){
        //当滚动后题目序号显示模块不见了就进行定位

    }*/
}

function cancel_publish(url){
    var htmlvalue = '<div class="task-popup" style="width:480px;"><div class="task-popup-title clearfix font-20">提示</div>'+
        '<div class="task-popup-content"><p class="task-popup-text-center font-16 mt15 mb15">将删除学生已提交的作品/答题<br>是否确认撤销发布</p></div><div class="task-popup-submit clearfix"><a href="javascript:void(0);" onclick="hideModal();" class="task-btn fl">取消</a>'+
        '<a href="'+ url +'" class="task-btn task-btn-orange fr" onclick="hideModal();">确定</a></div></div>';
    pop_box_new(htmlvalue, 480, 270);
}