var opt1 = true;
var opt2 = true;
var opt3 = false;
var opt4 = false;
var opt5 = true;
var opt7 = true;
$(function () {
    //var browser= getBrowserInfo();
    //alert(browser);
    checkhHtml5();

    //alert(browser); 
    //var verinfo = (browser+"").replace(/[^0-9.]/ig,""); 
    //alert(verinfo);

    $(document).bind('keydown.+', function () {
        var ff = $('#next_b');
        ff.click();
    });

    $(document).bind('keydown.-', function () {
        var ff = $('#pre_b');
        ff.click();
    });

    $(document).bind('keydown./', function () {
        submitExam();
    });

    $(document).bind('keydown.1', function () {
        var qustType = $('#qustType').val();
        if (qustType == '002') {
            single('1')
        }

        if (qustType == '003') {
            if ($("input[name='multi'][value=1]").is(':checked')) {
                $("input[name='multi'][value=1]").removeAttr("checked");
            } else {
                $("input[name='multi'][value=1]").prop("checked", true);
            }
        }
    });

    $(document).bind('keydown.2', function () {
        var qustType = $('#qustType').val();
        if (qustType == '002') {
            single('2')
        }

        if (qustType == '003') {
            if ($("input[name='multi'][value=2]").is(':checked')) {
                $("input[name='multi'][value=2]").removeAttr("checked");
            } else {
                $("input[name='multi'][value=2]").prop("checked", true);
            }
        }
    });

    $(document).bind('keydown.3', function () {
        var qustType = $('#qustType').val();
        if (qustType == '002') {
            single('3')
        }

        if (qustType == '003') {
            if ($("input[name='multi'][value=3]").is(':checked')) {
                $("input[name='multi'][value=3]").removeAttr("checked");
            } else {
                $("input[name='multi'][value=3]").prop("checked", true);
            }
        }
    });

    $(document).bind('keydown.4', function () {
        var qustType = $('#qustType').val();
        if (qustType == '001') {
            judge(1)
        }

    });

    $(document).bind('keydown.5', function () {
        var qustType = $('#qustType').val();
        if (qustType == '002') {
            single('4')
        }

        if (qustType == '003') {
            if ($("input[name='multi'][value=4]").is(':checked')) {
                $("input[name='multi'][value=4]").removeAttr("checked");
            } else {
                $("input[name='multi'][value=4]").prop("checked", true);
            }
        }
    });

    $(document).bind('keydown.6', function () {
        var qustType = $('#qustType').val();
        if (qustType == '001') {
            judge(2)
        }

    });

    $(document).bind('keydown.return', function () {
        var qustType = $('#qustType').val();
        if (qustType == '003') {
            selected();
        }

    });

    my_jPlayer = $("#jquery_jplayer");

    my_jPlayer.jPlayer({
        /*ready: function () {
             $(this).jPlayer("setMedia", {
               mp3: "<%=basePath%>sound/BEEP1.mp3" // Defines the m4v url
             }); // Attempts to Auto-Play the media
           },*/
        swfPath: "<%=basePath%>js",
        //cssSelectorAncestor: "#jp_container",
        supplied: "mp3,wav",
        wmode: "window"
    });

    m_jplayer = $("#jquery_jplayer_1");
    m_jplayer.jPlayer({
        /*ready: function () {
             $(this).jPlayer("setMedia", {
               mp3: "<%=basePath%>sound/BEEP1.mp3" // Defines the m4v url
             }); // Attempts to Auto-Play the media
           },*/
        resize: function (e) {
            if (e.jPlayer.status.cssClass != 'jp-video-full') {
                $('#videoWindows').window("close");
            }
        },
        ended: function () {
            setTimeout("closeVideo()", 5000)
        },
        swfPath: "<%=basePath%>js",
        cssSelectorAncestor: "#jp_container_1",
        size: {
            width: "640px",
            height: "360px",
            cssClass: "jp-video-360p"
        },
        supplied: "m4v",
        smoothPlayBar: true,
        wmode: "window"

    });

    $('#videoWindows').window({
        onClose: function () {
            //关闭广播
            m_jplayer.jPlayer("stop");
        }
    })


    $('#content').panel({
        onLoad: function () {
            if (opt1) {
                $('#result').css('display', '');
            } else {
                $('#result').css('display', 'none');
            }

            if (opt3) {
                $('#notes').css('display', '');
            } else {
                $('#notes').css('display', 'none');
            }

            if (opt4) {
                playAudio();
            }
            for (i in document.images) document.images[i].ondragstart = imgdragstart;

            ////var top = $('#showImg').offset().top;
            //var ps_height = $('#cc').layout('panel','center').height();
            //$('#imgShow').height(ps_height-top);
        }
    });


    //选择试题，刷新试题内容
    $("#questions div").bind("click", function (event) {
        event.preventDefault();
        event.stopPropagation();
        //console.info(this);
        my_jPlayer.jPlayer("stop");

        //添加选择样式
        $("#questions div").removeClass("pointboxcurrent");
        $(this).addClass("pointboxcurrent");

        var dd = $(this).attr('id');
        var isRedo = $('#isRedo').val();
        var _id = $(this).html();

        if (_id.indexOf("<span>") > 0) {
            _id = _id.substring(0, _id.indexOf("<span>"));
        }
        var token = $('#token').val();
        $('#content').panel('refresh', '/Question/GetQuestion?code=' + dd + "&token=" + token + "&id=" + _id + "&lib=" + lib + "&times=" + c + "&isRedo=" + isRedo);

        //选题区域滚动

        var container = $("#questions"),
		scrollTo = $(this);

        container.scrollTop(
		scrollTo.offset().top - container.offset().top + container.scrollTop()
		);

        // Or you can animate the scrolling: 
        //		container.animate({ 
        //		scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() 
        //		});​ 
    });

    //显示答案
    $('#opt1').bind("change", function () {
        opt1 = !opt1;

        if ($('#result').length > 0) {
            //alert(opt1);
            if (opt1) {
                $('#result').css('display', '');
            } else {
                $('#result').css('display', 'none');
            }
        }
    });
    //显示对错
    $('#opt2').bind("change", function () {
        opt2 = !opt2;
        //alert(opt2);
        if (opt2) {
            $('#yesNo').css('display', '');
        } else {
            $('#yesNo').css('display', 'none');
        }
    });
    //显示讲解
    $('#opt3').bind("change", function () {
        opt3 = !opt3;
        if (opt3) {
            $('#notes').css('display', '');
        } else {
            $('#notes').css('display', 'none');
        }

    });
    //语音讲解
    $('#opt4').bind("change", function () {
        opt4 = !opt4;
        if (!opt4) {
            my_jPlayer.jPlayer("stop");
        } else {
            playAudio();
        }
    });
    //语音提示
    $('#opt5').bind("change", function () {
        opt5 = !opt5;
        //alert(opt5);
    });

    $('#opt7').bind("change", function () {
        opt7 = !opt7;
        //alert(opt5);
    });


    formatResult(0, 0);

    if (ts > 0) {
        c = ts;
    } else {
        c = 1;
    }

    $('#questions > div:first').click();



    timedCount();

    ///examTimeCount();
});

function closeVideo() {
    if ($('#videoWindows').parent().css('display') != 'none') {
        $('#videoWindows').window("close");
    }

}

function submitExam() {
    var fl = $('#questions > div').length;

    var f1 = $('#questions > div ').filter(".pointboxwrong").length;

    var f2 = $('#questions > div ').filter(".pointboxright").length;

    var f3 = fl - f1 - f2;
    if (f3 > 0) {
        $.messager.confirm('注意', '尚有 ' + f3 + ' 道题未做，是否交卷', function (r) {
            if (r) {
                submitBackExam();
            }
        });
    } else {
        submitBackExam();
    }
}

function submitBackExam() {
    clearInterval(_timer);
    $('#infoWindows').panel('open').panel('refresh', '/Question/SubmitExam?token=' + $('#token').val());
}

function tryReExam() {
    $.messager.confirm('注意', '本操作只会保留错误数据', function (r) {
        if (r) {
            reExam();
        }
    });
}

function reExam() {
    $('#reToken').val($('#token').val());
    $("#form1").submit();
}



//下一题
function next(code) {

    var selectItem = $('#selected').val();
    var qustType = $('#qustType').val();

    if (qustType == "003" && selectItem == 1) {
        selected();
    }
    var ff = $('#' + code + '+ div');
    if (ff.length == 0) {
        //$.messager.alert('联创交规速成系统','已经到最后一题，请点击交卷!','info');
        alert("已经到最后一题，请点击交卷!");
    } else {
        ff.click();
    }



}

//上一题
function proe(code) {
    var fl = $('#questions > div');
    var first = $('#questions > div:first');
    if (first.attr('id') == code) {
        alert("已经是第一题");
        return;
    }
    var first;
    $.each(fl, function (i, n) {
        if (n.id != code) {
            first = $(n);
        } else {

            first.click();
            return;
        }

    });

}

//判断题
function judge(re) {
    var result = $('#anwser').val();
    var arr = ['', '√', '×'];
    var out = "";
    takeAnwser(arr[re]);
    if (re == result) {
        //alert("对");
        takeCSSRight();
        takeRight()
        //		$('#chose').attr("src",basePath+"/image/chs_"+re+".png");
        //		$('#chose').height(32);
        //		$('#chose').width(32);
        out = '<img src="/image/chs_' + re + '.png"  style="height: 32px; width: 32px;margin-top: 10px;">';
        $('#choses').html("<div style='margin-top: 15px;float: left;'>" + "您的答案:</div>" + out);
        if (opt2) {
            $('#yesNo').html("<img  src='/image/yes-v3.png' style='width: 32px;height: 32px;margin-top: 10px;'/>");
        }
        putResult(1, re, result);
    } else {
        //alert("错");
        takeCSSWrong();
        takeError();
        //setTimeout(playAudio,1000);
        //		$('#chose').attr("src",basePath+"/image/chs_"+re+".png");
        //		$('#chose').height(32);
        //		$('#chose').width(32);
        out = '<img src="/image/chs_' + re + '.png"  style="height: 32px; width: 32px;margin-top: 10px;">';
        $('#choses').html("<div style='margin-top: 15px;float: left;'>" + "您的答案:</div>" + out);
        if (opt2) {
            $('#yesNo').html("<img  src='/image/red-x.png' style='width: 32px;height: 32px;margin-top: 10px;'/>");
        }

        putResult(2, re, result);
    }
    if (opt1) {
        $('#result').html("<div style='margin-top: 15px;float: left;'>" + "正确答案:</div>" + "<img  src='/image/chs_" + result + ".png' style='width: 32px;height: 32px;margin-top: 10px;'/>");
    }
}

function single(re) {
    var arr = ['', 'A', 'B', 'C', 'D'];
    var result = $('#anwser').val();
    var out = "";

    takeAnwser(arr[re]);
    if (re == result) {
        //alert("对");
        takeRight()
        takeCSSRight();
        //		$('#chose').attr("src",basePath+"/image/b_"+arr[re]+".png");
        //		$('#chose').height(32);
        //		$('#chose').width(32);
        out = '<img src="/image/b_' + arr[re] + '.png"  style="height: 32px; width: 32px;margin-top: 10px;">';
        $('#choses').html("<div style='margin-top: 15px;float: left;'>" + "您的答案:</div>" + out);
        if (opt2) {
            $('#yesNo').html("<img  src='/image/yes-v3.png' style='width: 32px;height: 32px;margin-top: 10px;'/>");
        }
        putResult(1, re, result);
    } else {
        takeError()
        takeCSSWrong();
        //$('#chose').attr("src",basePath+"/image/b_"+arr[re]+".png");
        //$('#chose').height(32);
        //$('#chose').width(32);
        out = '<img src="/image/b_' + arr[re] + '.png"  style="height: 32px; width: 32px;margin-top: 10px;">';
        $('#choses').html("<div style='margin-top: 15px;float: left;'>" + "您的答案:</div>" + out);
        if (opt2) {
            $('#yesNo').html("<img  src='/image/red-x.png' style='width: 32px;height: 32px;margin-top: 10px;'/>");
        }


        putResult(2, re, result);
    }
    if (opt1) {
        $('#result').html("<div style='margin-top: 15px;float: left;'>" + "正确答案:</div>" + "<img  src='/image/b_" + arr[result] + ".png' style='width: 32px;height: 32px;margin-top: 10px;'/>");
    }

}

function takeAnwser(as) {
    var code = $('#code').val();
    $('#' + code + ' > span').html(as);
}

function takeCSSRight() {
    var code = $('#code').val();
    $('#' + code).removeClass();
    $('#' + code).toggleClass("pointbox pointboxright");
    if ($('#' + code).attr("isW") == 1) {
        $('#' + code).toggleClass("divcss5");
    }
}

function takeCSSWrong() {
    var code = $('#code').val();
    $('#' + code).removeClass();
    $('#' + code).attr("isW", 1);
    $('#' + code).toggleClass("pointbox pointboxwrong");
}

//正确语音提示
function takeRight() {
    if (opt5) {
        my_jPlayer.jPlayer("setMedia", {
            mp3: "/Content/sound/right.wav"
        });

        my_jPlayer.jPlayer("play");
    }

}

//错误语音提示
function takeError() {
    if (opt5) {
        my_jPlayer.jPlayer("setMedia", {
            mp3: "/Content/sound/wrong.wav"
        });

        my_jPlayer.jPlayer("play");
    }
    if (opt7) {
        setTimeout(playAudio, 1000);
    }

}

function playAudio() {
    //var ff = $('#audio').val();
    if (opt4 || opt7) {
        audioPlay();
    }

}

function audioPlay() {
    my_jPlayer.jPlayer("setMedia", {
        mp3: $('#audio').val()
    });

    my_jPlayer.jPlayer("play");
}

function videoPlay() {
    var video = $('#vedio').val();
    var result = /\.[^\.]+/.exec(video);
    //alert(video.length);
    if (video.length > 0) {
        if (result == ".gif") {
            $('#showVideo').attr('src', video); //basePath + "res/gif/" +
            $('#gifDlg').dialog("open");
        } else if (result == ".mp4") {
            m_jplayer.jPlayer("setMedia", {
                title: "按ESC退出全屏",
                m4v: video //basePath + "res/mp4/" + 
            });

            m_jplayer.jPlayer({
                fullScreen: true
            });
            m_jplayer.jPlayer("play");
            $('#videoWindows').window('open');
        } else {
            $.messager.alert('提示', "没有媒体文件！", 'error');
        }
    } else {
        $.messager.alert('提示', "没有媒体文件！", 'error');
    }


}


//后台写入结果
function putResult(result, doAnswer, answer) {
    // var choose = $('#selected').val();
    $.ajax({
        url: '/Question/PutResult',
        data: {
            'code': $('#code').val(),
            'token': $('#token').val(),
            'times': c,
            'isAB': isAB,
            'result': result,
            'doAnswer': doAnswer,
            'answer': answer,
            'orderlist': $('#orderlist').val()
        },
        cache: false,
        dataType: "json",
        success: function (data) {
           /// debugger;
           // console.log(data) ;
            if (data != null || data != undefined) {
                formatResult(data.Success, data.score);
                //  lib = data.lib;
                firstOk = data.Success;

                var radio_value = '';
                if ($("input[name=opt6]").is(':checked')) {
                    radio_value = $("input[name=opt6]:checked").val();
                }
                if (radio_value == 2) {
                    var ff = $('#next_b');
                    ff.click();
                } else if (radio_value == 3 && data.result == 1) {
                    var ff = $('#next_b');
                    ff.click();
                }
            }
        }
    });
}


function formatResult(num) {
    var fl = $('#questions > div').length;
    $("#allQ").html(fl);

    var f1 = $('#questions > div ').filter(".pointboxwrong").length;
    $("#WQ").html(f1);

    var f2 = $('#questions > div ').filter(".pointboxright").length;
    $("#RQ").html(f2);

    var f3 = fl - f1 - f2;
    $("#UQ").html(f3);

    var score = parseInt(f2 / f1 * 100);
    //$('#firstOK').html(GetPercent(num, total));
    $('#firstOK').html(GetPercent(fl - num, fl));
    $('#score').html(score);
}

function GetPercent(num, total) {
    var _num = 0;
    var _total = 0;
    if (_first > 0 || _all > 0) {
        var _num = _first;
        var _total = _all;
        _first = 0;
        _all = 0;
    } else {
        _num = parseFloat(num);
        _total = parseFloat(total);
    }

    if (isNaN(_num) || isNaN(_total)) {
        return "-";
    }
    return _total <= 0 ? "0%" : (Math.round(_num / _total * 10000) / 100.00 + "%");
}


function multi(obj) {
    var p = $(obj).parent();
    //$(p).toggleClass("pointboxright");
    if ($("input[name='multi'][value=" + $(p).data("v") + "]").is(':checked')) {
        $("input[name='multi'][value=" + $(p).data("v") + "]").removeAttr("checked");
    } else {
        $("input[name='multi'][value=" + $(p).data("v") + "]").prop("checked", true);
    }

}

function chilckMe(me) {
    if (me.checked) {
        $(me).prop("checked", true);
    }
    else {
        $(me).removeAttr("checked");
    }
}

function sort1(obj) {
    var arr = obj;
    arr.sort(function (a, b) { return a < b ? 1 : -1 });
    return arr;
}

//http://localhost:8080/exam//image/balloon_A.png
//http://localhost:8080/exam//image/balloon_A.png


function selected() {
    $('#selected').val("2");
    var items = $("input[name='multi']:checked");
    if (items.length == 0) {
        alert("请选择答案");
        return;
    }
    var arr = ['', 'A', 'B', 'C', 'D'];
    var a = [];// 创建数组
    out = "";
    $(items).each(function () {
        a.push($(this).val());
        //out=out+'<img src="'+basePath+'/image/b_'+arr[$(this).val()]+'.png"  style="height: 32px; width: 32px;margin-top: 10px;">';
        out = out + arr[$(this).val()];
    });
    re = a.join("");

    takeAnwser(out);
    var result = $('#anwser').val();
    if (re == result) {
        takeRight()
        takeCSSRight();

        $('#choses').html("<div style='margin-top: 15px;float: left;'>" + "您的答案:" + out + "</div>");
        if (opt2) {
            $('#yesNo').html("<img  src='" + basePath + "/image/yes-v3.png' style='width: 32px;height: 32px;margin-top: 10px;'/>");
        }
        putResult(1, re, result);
    } else {
        takeError()
        takeCSSWrong();
        $('#choses').html("<div style='margin-top: 15px;float: left;'>" + "您的答案:" + out + "</div>");

        if (opt2) {
            $('#yesNo').html("<img  src='" + basePath + "/image/red-x.png' style='width: 32px;height: 32px;margin-top: 10px;'/>");
        }

        putResult(2, re, result);
    }
    if (opt1) {
        var out = ""

        b = result.split("");
        $.each(b, function (i, n) {
            //out=out+'<img src="'+basePath+'/image/b_'+arr[n]+'.png"  style="height: 32px; width: 32px;margin-top: 10px;">';
            out = out + arr[n];
        });
        $('#result').html("<div style='margin-top: 15px;float: left;'>" + "正确答案:" + out + "</div>");
    }

}

function selected_bak() {
    var arr = ['', 'A', 'B', 'C', 'D'];
    var a = [];// 创建数组
    var items = $('#anwsers > div ').filter(".pointboxright");
    out = "";
    $(items).each(function () {
        a.unshift($(this).data("v")); // 添加到第一个位置
        out = '<img src="' + basePath + '/image/b_' + arr[$(this).data("v")] + '.jpg"  style="height: 32px; width: 32px;">' + out;
    });
    //alert(a.join("")); 
    re = a.join("");
    var result = $('#anwser').val();
    if (re == result) {
        takeRight()
        takeCSSRight();

        $('#choses').html("正确答案：" + out);
        if (opt2) {
            $('#yesNo').html("<img  src='" + basePath + "/image/yes-v3.png' style='width: 32px;height: 32px;'/>");
        }
        putResult(1);
    } else {
        takeError()
        takeCSSWrong();
        $('#choses').html("正确答案：" + out);

        if (opt2) {
            $('#yesNo').html("<img  src='" + basePath + "/image/red-x.png' style='width: 32px;height: 32px;'/>");
        }
        putResult(2);
    }
    if (opt1) {
        var out = ""
        b = result.split("");
        $.each(b, function (i, n) {
            out = out + '<img src="' + basePath + '/image/b_' + arr[n] + '.jpg"  style="height: 32px; width: 32px;">';
        });
        $('#result').html("正确答案：" + out);
    }
}

function unSelect() {
    //	var items = $('#anwsers > div ').filter(".pointboxright");
    //	$(items).each(function(){
    //		$(this).toggleClass("pointboxright");
    //		
    //	});
    var items = $("input[name='multi']:checked");

    $(items).each(function () {
        $(this).attr("checked", false);
    });
}

function timedCount() {

    hour = parseInt(c / 3600);// 小时数  
    min = parseInt(c / 60);// 分钟数  
    if (min >= 60) {
        min = min % 60
    }
    lastsecs = c % 60;


    $('#timeCount').html(hour + "时" + min + "分" + lastsecs + "秒");
    c = c + 1
    t = setTimeout("timedCount()", 1000)

}

function examTimeCount() {

    var end = new Date()
    examTime = new Date(end.valueOf() + 45 * 60 * 1000);
    timer();
}

function timer() {
    var ts = examTime - (new Date());//计算剩余的毫秒数  
    // var dd = parseInt(ts / 1000 / 60 / 60 / 24, 10);//计算剩余的天数  
    // var hh = parseInt(ts / 1000 / 60 / 60 % 24, 10);//计算剩余的小时数  
    var mm = parseInt(ts / 1000 / 60 % 60, 10);//计算剩余的分钟数  
    var ss = parseInt(ts / 1000 % 60, 10);//计算剩余的秒数  
    // dd = checkTime(dd);  
    // hh = checkTime(hh);  
    mm = checkTime(mm);
    ss = checkTime(ss);
    $('#timeCount').html(mm + "分" + ss + "秒");
    setInterval("timer()", 1000);
    CollectGarbage();
}
function checkTime(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

function getBrowserInfo() {
    var agent = navigator.userAgent.toLowerCase();

    var regStr_ie = /msie [\d.]+;/gi;
    var regStr_ff = /firefox\/[\d.]+/gi
    var regStr_chrome = /chrome\/[\d.]+/gi;
    var regStr_saf = /safari\/[\d.]+/gi;
    //IE
    if (agent.indexOf("msie") > 0) {
        return agent.match(regStr_ie);
    }

    //firefox
    if (agent.indexOf("firefox") > 0) {
        return agent.match(regStr_ff);
    }

    //Chrome
    if (agent.indexOf("chrome") > 0) {
        return agent.match(regStr_chrome);
    }

    //Safari
    if (agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0) {
        return agent.match(regStr_saf);
    }
}

function checkhHtml5() {
    if (typeof (Worker) !== "undefined") {
        //alert("支持HTML5");   
    } else {
        alert("您的浏览器不支持HTML5,请退回更换浏览器或浏览模式（安全360浏览器切换为极速模式）");
    }
}

function imgdragstart() { return false; }
