<%@page import="java.net.URLEncoder"%>
<%@page import="com.csc.library.session.InitialInquiry"%>
<%@page import="com.csc.library.session.DbInquiry"%>
<%@page import="com.csc.library.utilities.CheckNull"%>
<%@page import="com.csc.library.entry.UIManager"%>
<%@page contentType="text/html; charset=UTF-8"%>
<jsp:useBean id="APS_NEW_001" class="com.csc.library.system.Task" scope="page"/>
<%
    APS_NEW_001.setChannel(request,response);
    APS_NEW_001.checkProfile();
    UIManager screen = (UIManager) APS_NEW_001.process("SingleEntry","APS_NEW_001");
    String lang = screen.getUProfile().get("lang");
    screen.referLangOff();
    CheckNull chk = new CheckNull();
    String question = chk.chkNullString(request.getParameter("__question"),screen.getDataLabel("question"));
    String questionFormat = chk.chkNullString(request.getParameter("__question_format"),screen.getDataLabel("question_format"));
    String tmpField = chk.chkNullString(request.getParameter("tmpField"));
    String lineObjective = chk.chkNullString(request.getParameter("lineObjective"));
    String lastLineObjective = chk.chkNullString(request.getParameter("lastLineObjective"));
    String tmpQuestionid = chk.chkNullString(request.getParameter("tmpQuestionid"), screen.getDataLabel("questionid"));
    String lineMatch = chk.chkNullString(request.getParameter("lineMatch"));
    String lastLineMatch = chk.chkNullString(request.getParameter("lastLineMatch"));
    String lineSortSentence = chk.chkNullString(request.getParameter("lineSortSentence"));
    String lastLineSortSentence = chk.chkNullString(request.getParameter("lastLineSortSentence"));
    String lineQuestionnaire = chk.chkNullString(request.getParameter("lineQuestionnaire"));
    String lastLineQuestionnaire = chk.chkNullString(request.getParameter("lastLineQuestionnaire"));
    String lineQuestionnaireMulti = chk.chkNullString(request.getParameter("lineQuestionnaireMulti"));
    String lastLineQuestionnaireMulti = chk.chkNullString(request.getParameter("lastLineQuestionnaireMulti"));

%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- Bootstrap -->
        <link href="../JS/QueryBuilder/bootstrap-3.3.5/css/bootstrap.css" rel="stylesheet">

        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="../JS/html5shiv.min.js"></script>
          <script src="../JS/respond.min.js"></script>
        <![endif]-->
        <link href="../CSS/TISCO.css" rel="stylesheet" type="text/css">
        <script src='../JS/SCREEN.js'></script>
        <script src="../JS/HOTKEY.js"></script>
        <script src="../JS/ICONSMENU.js"></script>
        <script src="../JS/VIEWCALENDAR.js"></script>
        <script src="../JS/SWAPLANG_FREEDOM.js"></script>
        <script src="../JS/HOTKEY.js"></script>
        <script src="../JS/exam/CKEDITOR/ckeditor.js"></script>
        <script src="../JS/exam/CKEDITOR/sample.js"></script>
        <script src="../JS/exam/CKEDITOR/extend_plugin.js"></script>
        <script src="../JS/jquery-1.11.3.min.js"></script>
        <script src="../JS/bootstrap.min.js"></script>
        <!--<script src="../VIDEO4ALL/video4all.js"></script>-->
        <!--<script src="../AUDIOJS/audio.min.js"></script>-->
        <script>setLangSwapLang("<%=lang%>");</script>
        <script>setLang('<%=lang%>');</script>
        <script>getTitleName();</script>

        <style>
            img[height="20"] {
                padding: 0px;
            }

            /*.audiojs .play {
                background: url("../AUDIOJS/player-graphics.gif") -8px -1px no-repeat;
            }

            .audiojs .pause {
                background: url("../AUDIOJS/player-graphics.gif") -8px -91px no-repeat;
            }*/

            .detailHeader {
                text-align: center;
                background-color: #3B7CBD;
                color: #FFFFFF;
            }

            .table > tbody > tr > td {
                padding: 3px;
                border: 1px solid #CBC5C5;
            }
            .table-preview > tbody > tr > td {
                background-color: #ffffff;
                color: #000000;
            }
            
            .plus, .del {
                cursor: pointer;
                padding: 10px;
            }

        </style>
    </head>
    <body>
        <div id="toolTipLayer" style="position:absolute; visibility: hidden"></div>
        <script>initToolTips();</script>
        <form name="cscform" method="post" role="form" action="APS_NEW_001.jsp">
            <!----------BEGIN CSC INITIAL ZONE ------------------------>
            <%=screen.InitialVariable()%>
            <!----------END CSC INITIAL ZONE -------------------------->
            <input type="hidden" name="__screen" value="APS_NEW_001">
            <input type="hidden" name="__help" value="">
            <input type="hidden" name="__fixCon" value="">
            <input type="hidden" name="__cmd" value="">
            <input type="hidden" name="__language" value='<%=lang%>'>
            <input type="hidden" name="__companyid" value="<%=screen.getUProfile().get("companyid")%>">
            <input type="hidden" name="__notNull" value="<%=screen.getRequire()%>">
            <input type="hidden" name="__user" value="<%=screen.getUProfile().getUserId()%>">
            <input type="hidden" name="__referPage" value="">
            <input type="hidden" name="__calendar" >
            <input type="hidden" name="__notdelall" value="false">
            <input type="hidden" name="__clean" value="1">
            <div class="container">
                <script>document.write(Icons(""));</script>
                <br>
                <table style="border-spacing: 0;border-collapse: 0;width: 100%;">
                    <tr>
                        <td class="header" colspan="2"><script>swLang('APS_NEW_001');</script>&nbsp;</td>
                    </tr>
                    <tr>
                        <td class="blankspace" colspan="2"></td>
                    </tr>
                    <tr>
                        <td class="text-right"><strong><script>swLang('QUESTIONID');</script></strong>&nbsp;</td>
                        <td class="text-left"><%=screen.getInput("questionid")%></td>
                    </tr>
                    <tr>
                        <td class="text-right"><script>swLang('QUESTION');</script>&nbsp;&nbsp;</td>
                        <td class="text-left">
                            <textarea name="editor" id="editor" rows="10" cols="80"></textarea>
                            <script>
                                var editor = CKEDITOR.replace('editor', {
                                    customConfig: '../CKEDITOR/config_for_new_aps.js',
                                    width: 700,
                                    height: 200,
                                    language: 'en'
                                });
                            </script>
                        </td>
                    </tr>
                    <tr>
                        <td class="text-right"><script>swLang('TITLE_TYPE');</script>&nbsp;</td>
                        <td class="text-left"><%=screen.getInput("title_type") %></td>
                    </tr>
                    <tr style="display: none;">
                        <td class="text-right"><script>swLang('QUERY_TYPE');</script>&nbsp;</td>
                        <td id="comment" class="columnobject1">
                            <%=screen.getInput("query_type")%>
                        </td>
                    </tr>
                    <tr>
                        <td class="text-right"><script>swLang('ACTIVE_STATUS');</script>&nbsp;</td>
                        <td class="text-left"><%=screen.getInput("active_status") %></td>
                    </tr>
                    <tr>
                        <td class="text-right"><script>swLang('SCORE');</script>&nbsp;</td>
                        <td class="text-left"><%=screen.getInput("score") %></td>
                    </tr>
                    <tr>
                        <td colspan="2">&nbsp;</td>
                    </tr>
                    <tr>
                        <td colspan="2"><table id="tb" class="table" style="width: 98%;margin: 0 auto;"></table></td>
                    </tr>
                    <tr>
                        <td colspan="2" class="text-center" style="padding-top: 10px; padding-bottom: 10px;">
                            <button type="button" id="selectAll" class="btn btn-primary btn-sm">
                                <span class="glyphicon glyphicon-asterisk"></span> Select All
                            </button>
                            <button type="button" id="deselectAll" class="btn btn-primary btn-sm">
                                <span class="glyphicon glyphicon-ban-circle"></span> Deselect All
                            </button>
                            <button type="button" id="add" class="btn btn-primary btn-sm">
                                <span class="glyphicon glyphicon-plus"></span> Add
                            </button>
                            <button type="button" id="del" class="btn btn-primary btn-sm">
                                <span class="glyphicon glyphicon-trash"></span> Delete
                            </button>
                            <button type="button" id="openDialog" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal">
                                <span class="glyphicon glyphicon-play"></span> Preview
                            </button>

                            <!-- Modal -->
                            <div class="modal fade" id="myModal" role="dialog">
                                <div class="modal-dialog modal-lg">
                                    <!-- Modal content-->
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                                            <h2 style="font-size: 20px;" class="modal-title" style="color: #000000;">Preview</h2>
                                        </div>
                                        <div class="modal-body text-left"></div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td class="blankspace" colspan="2"></td>
                    </tr>
                    <tr>
                        <td class="bottom" colspan="2"></td>
                    </tr>
                </table>
                <%
                    StringBuilder tmpFieldDb = new StringBuilder();
                    String lineObjectiveDb = "";
                    String lastLineObjectiveDb = "";
                    String lineMatchDb = "";
                    String lastLineMatchDb = "";
                    String lineSortSentenceDb = "";
                    String lastLineSortSentenceDb = "";
                    String lineQuestionnaireDb = "";
                    String lastLineQuestionnaireDb = "";
                    String lineQuestionnaireMultiDb = "";
                    String lastLineQuestionnaireMultiDb = "";
                    try {
                        DbInquiry dbi = new InitialInquiry(screen.getUProfile()).getDbInquiry("mquestion_detail");
                        dbi.setColumn("*");
                        dbi.clearOldCondition();
                        dbi.setFilter("questionid='" + screen.getDataLabel("questionid") + "'");
                        dbi.refresh();
                        String titleType = screen.getDataLabel("title_type");
                        String queryType = screen.getDataLabel("query_type");
                        while (dbi.next()) {
                            String line = dbi.getString("question_detailid");
                            if (titleType.equals("0")) { // ปรนัย
                                tmpFieldDb.append("question_detail" + line + "=" + URLEncoder.encode(dbi.getString("question_detail"), "UTF-8") + "&");
                                tmpFieldDb.append("question_detail_format" + line + "=" + URLEncoder.encode(dbi.getString("question_detail_format"), "UTF-8") + "&");
                                tmpFieldDb.append("result_objective" + line + "=" + dbi.getString("result_objective") + "&");
                                lineObjectiveDb += line + ",";
                                lastLineObjectiveDb = line;
                            } else if (titleType.equals("1")) { // อัตนัย
                                tmpFieldDb.append("result_subjective=" + dbi.getString("result_subjective") + "&");
                            } else if (titleType.equals("2")) { // จับคู่
                                tmpFieldDb.append("question_detail" + line + "=" + URLEncoder.encode(dbi.getString("question_detail"), "UTF-8") + "&");
                                tmpFieldDb.append("question_detail_format" + line + "=" + URLEncoder.encode(dbi.getString("question_detail_format"), "UTF-8") + "&");
                                tmpFieldDb.append("answer_match_detail" + line + "=" + URLEncoder.encode(dbi.getString("answer_match_detail_format"), "UTF-8") + "&");
                                tmpFieldDb.append("answer_match_detail_format" + line + "=" + URLEncoder.encode(dbi.getString("answer_match_detail_format"), "UTF-8") + "&");
                                lineMatchDb += line + ",";
                                lastLineMatchDb = line;
                            } else if (titleType.equals("3")) { // เรียงประโยค
                                tmpFieldDb.append("result_sort_sentence" + line + "=" + URLEncoder.encode(dbi.getString("result_sort_sentence"), "UTF-8") + "&");
                                lineSortSentenceDb += line + ",";
                                lastLineSortSentenceDb = line;
                            } else if (titleType.equals("4")) { // แบบสอบถาม
                                if (queryType.equals("0")) { // เลือกคำตอบได้ข้อเดียว
                                    tmpFieldDb.append("questionnaire_detail" + line + "=" + URLEncoder.encode(dbi.getString("question_detail"), "UTF-8") + "&");
                                    tmpFieldDb.append("questionnaire_detail_format" + line + "=" + URLEncoder.encode(dbi.getString("question_detail_format"), "UTF-8") + "&");
                                    lineQuestionnaireDb += line + ",";
                                    lastLineQuestionnaireDb = line;
                                } else if (queryType.equals("1")) {
                                    tmpFieldDb.append("questionnaire_multi_detail" + line + "=" + URLEncoder.encode(dbi.getString("question_detail"), "UTF-8") + "&");
                                    tmpFieldDb.append("questionnaire_multi_detail_format" + line + "=" + URLEncoder.encode(dbi.getString("question_detail_format"), "UTF-8") + "&");
                                    lineQuestionnaireMultiDb += line + ",";
                                    lastLineQuestionnaireMultiDb = line;
                                }
                            }
                        }
                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                    boolean stautsChgQuestionid = false;

                    String questionid = screen.getDataLabel("questionid");
                    //---------- ปรนัย ----------
                    if (!lineObjectiveDb.equals("")) {
                      lineObjectiveDb = lineObjectiveDb.substring(0, lineObjectiveDb.length() - 1);
                    }

                    if (lineObjective.equals("") || !tmpQuestionid.equals(questionid)) {
                        lineObjective = lineObjectiveDb;
                        stautsChgQuestionid = true;
                    }

                    if (lastLineObjective.equals("") || !tmpQuestionid.equals(questionid)) {
                        lastLineObjective = lastLineObjectiveDb;
                        stautsChgQuestionid = true;
                    }
                     
                    //---------- จับคู่ ----------
                    if (!lineMatchDb.equals("")) {
                      lineMatchDb = lineMatchDb.substring(0, lineMatchDb.length() - 1);
                    }

                    if (lineMatch.equals("") || !tmpQuestionid.equals(questionid)) {
                        lineMatch = lineMatchDb;
                        stautsChgQuestionid = true;
                    }

                    if (lastLineMatch.equals("") || !tmpQuestionid.equals(questionid)) {
                        lastLineMatch = lastLineMatchDb;
                        stautsChgQuestionid = true;
                    }
                    
                    //---------- เรียงประโยค ----------
                    if (!lineSortSentenceDb.equals("")) {
                      lineSortSentenceDb = lineSortSentenceDb.substring(0, lineSortSentenceDb.length() - 1);
                    }

                    if (lineSortSentence.equals("") || !tmpQuestionid.equals(questionid)) {
                        lineSortSentence = lineSortSentenceDb;
                        stautsChgQuestionid = true;
                    }

                    if (lastLineSortSentence.equals("") || !tmpQuestionid.equals(questionid)) {
                        lastLineSortSentence = lastLineSortSentenceDb;
                        stautsChgQuestionid = true;
                    }

                    //---------- แบบสอบถาม ตอบได้ข้อเดียว ----------
                    if (!lineQuestionnaireDb.equals("")) {
                      lineQuestionnaireDb = lineQuestionnaireDb.substring(0, lineQuestionnaireDb.length() - 1);
                    }

                    if (lineQuestionnaire.equals("") || !tmpQuestionid.equals(questionid)) {
                        lineQuestionnaire = lineQuestionnaireDb;
                        stautsChgQuestionid = true;
                    }

                    if (lastLineQuestionnaire.equals("") || !tmpQuestionid.equals(questionid)) {
                        lastLineQuestionnaire = lastLineQuestionnaireDb;
                        stautsChgQuestionid = true;
                    }
                    // ---------- แบบสอบถาม ตอบได้หลายข้อ ----------
                    if (!lineQuestionnaireMultiDb.equals("")) {
                      lineQuestionnaireMultiDb = lineQuestionnaireMultiDb.substring(0, lineQuestionnaireMultiDb.length() - 1);
                    }

                    if (lineQuestionnaireMulti.equals("") || !tmpQuestionid.equals(questionid)) {
                        lineQuestionnaireMulti = lineQuestionnaireMultiDb;
                        stautsChgQuestionid = true;
                    }

                    if (lastLineQuestionnaire.equals("") || !tmpQuestionid.equals(questionid)) {
                        lastLineQuestionnaireMulti = lastLineQuestionnaireMultiDb;
                        stautsChgQuestionid = true;
                    }

                    if (tmpField.equals("") || !tmpQuestionid.equals(questionid)) {
                        tmpField = tmpFieldDb.toString();
                        stautsChgQuestionid = true;
                    }
                    if (stautsChgQuestionid) {
                      tmpQuestionid = questionid;
                      question = screen.getDataLabel("question");
                      questionFormat = screen.getDataLabel("question_format");
                    }
                %>

                <textarea style="display: none;" id="showResult" rows="7" cols="50"></textarea>
                <textarea style="display: none;" id="__question" name="__question"><%=question %></textarea>
                <textarea style="display: none;" id="__question_format" name="__question_format"><%=questionFormat %></textarea>
                <input type="hidden" id="lineObjective" name="lineObjective" value="<%=lineObjective%>">
                <input type="hidden" id="lastLineObjective" name="lastLineObjective" value="<%=lastLineObjective%>">
                <textarea id="tmpField" name="tmpField" style="display: none"><%=tmpField %></textarea>
                <input type="hidden" id="statusTrueFalse" name="statusTrueFalse" value="<%=chk.chkNullString(request.getParameter("statusTrueFalse"))%>">
                <input type="hidden" id="lastLineMatch" name="lastLineMatch" value="<%=chk.chkNullString(request.getParameter("lastLineMatch"))%>">
                <input type="hidden" id="lineMatch" name="lineMatch" value="<%=lineMatch%>">
                <input type="hidden" id="lastLineSortSentence" name="lastLineSortSentence" value="<%=chk.chkNullString(request.getParameter("lastLineSortSentence"))%>">
                <input type="hidden" id="lineSortSentence" name="lineSortSentence" value="<%=lineSortSentence%>">
                <input type="hidden" id="lineQuestionnaire" name="lineQuestionnaire" value="<%=lineQuestionnaire%>">
                <input type="hidden" id="lastLineQuestionnaire" name="lastLineQuestionnaire" value="<%=lastLineQuestionnaire%>">
                <input type="hidden" id="lineQuestionnaireMulti" name="lineQuestionnaireMulti" value="<%=lineQuestionnaireMulti%>">
                <input type="hidden" id="lastLineQuestionnaireMulti" name="lastLineQuestionnaireMulti" value="<%=lastLineQuestionnaireMulti%>">
                <input type="hidden" id="tmpQuestionid" name="tmpQuestionid" value="<%=tmpQuestionid%>">


                <!----------BEGIN CSC ENDING ZONE ------------------------>
                <%=screen.endJSP()%>
                <!----------END CSC ENDING ZONE -------------------------->
            </div>
        </form>

        <script>

            /*audiojs.events.ready(function () {
                var as = audiojs.createAll();
            });*/
            
            var field = {};
            function GoSave() {
                var question_format = editor.element["$"].nextSibling.childNodes[1].childNodes[1].childNodes[1].contentDocument.childNodes[1].childNodes[1].innerHTML;
                question_format = setReplaceGoSave(question_format);
                $('#__question_format').val(question_format);
                var $data = removeLineBreak(editor.getData());
                $data = chkFloatLeft($data);
                $data = chkFloatRight($data);
                $('#__question').val($data);

                // ---------- save ปรนัย ----------
                if ($("input[name='__title_type']:checked").val() === '0') {
                    var lineObjective = "";
                    var chkBlankValue = false;
                    $("textarea[name^='detail']").each(function () {
                        var $line = $(this).attr('name').slice(6);
                        lineObjective += $line + ',';

                        var $question_detail = removeLineBreak(CKEDITOR.instances[$(this).attr('name')].getData());
                        if ($question_detail === '') {
                            chkBlankValue = true;
                        }
                        $question_detail = chkFloatLeft($question_detail);
                        $question_detail = chkFloatRight($question_detail);
                        $('#question_detail' + $line).val($question_detail);
                        $('#question_detail_format' + $line).val(setReplaceGoSave(CKEDITOR.instances[$(this).attr('name')].element["$"].nextSibling.childNodes[1].childNodes[1].childNodes[1].contentDocument.childNodes[1].childNodes[1].innerHTML));

                    });

                    if ($("textarea[name^='detail']").length === 0) {
                        lineObjective = '';
                    }

                    if (lineObjective !== '') {
                        lineObjective = lineObjective.substring(0, lineObjective.length - 1);
                        $('#lineObjective').val(lineObjective);
                        if (chkStatusTrueFalse()) {
                            if (!chkBlankValue) {
                                $("#tmpField").val($("form").serialize());
                                confirmSave();
                            } else {
                                alert(getSwapLang('PLEASE_SELECT_DETAIL'));
                            }
                        }
                    } else {
                        alert(getSwapLang('PLEASE_SELECT_DETAIL'));
                    }

                // ---------- save อัตนัย ----------
                } else if ($("input[name='__title_type']:checked").val() === '1') {
                    /*var $result_subjective = $('#result_subjective');
                    if ($result_subjective.val() !== '') {
                        $("#tmpField").val($("form").serialize());
                        confirmSave();
                    } else {
                        alert(getSwapLang('PLEASE_ANSWER'));
                        $result_subjective.focus();
                    }*/
                    confirmSave();
                // ---------- save จับคู่ ----------
                } else if ($("input[name='__title_type']:checked").val() === '2') {
                    var lineMatch = "";
                    var chkBlankAnswer = false;
                    $("textarea[name^='question_detail_format']").each(function () {
                        var $line = $(this).attr('name').slice(22);
                        lineMatch += $line + ',';
                        var $question_detail = removeLineBreak(CKEDITOR.instances['question' + $line].getData());
                        $question_detail = chkFloatLeft($question_detail);
                        $question_detail = chkFloatRight($question_detail);
                        $('#question_detail' + $line).val($question_detail);
                        $('#question_detail_format' + $line).val(setReplaceGoSave(CKEDITOR.instances['question' + $line].element["$"].nextSibling.childNodes[1].childNodes[1].childNodes[1].contentDocument.childNodes[1].childNodes[1].innerHTML));
                        
                        var $answer_match_detail = removeLineBreak(CKEDITOR.instances['answer' + $line].getData());
                        if ($answer_match_detail === '') {
                            chkBlankAnswer = true;
                        }
                        $answer_match_detail = chkFloatLeft($answer_match_detail);
                        $answer_match_detail = chkFloatRight($answer_match_detail);
                        $('#answer_match_detail' + $line).val($answer_match_detail);
                        $('#answer_match_detail_format' + $line).val(setReplaceGoSave(CKEDITOR.instances['answer' + $line].element["$"].nextSibling.childNodes[1].childNodes[1].childNodes[1].contentDocument.childNodes[1].childNodes[1].innerHTML));
                    });

                    if ($("textarea[name^='question']").length === 0) {
                        lineMatch = '';
                    }

                    if (lineMatch !== '') {
                        if (!chkBlankAnswer) {
                            lineMatch = lineMatch.substring(0, lineMatch.length - 1);
                            $('#lineMatch').val(lineMatch);
                            $("#tmpField").val($("form").serialize());
                            confirmSave();
                        } else {
                            alert(getSwapLang('PLEASE_ANSWER'));
                        }
                    } else {
                        alert(getSwapLang('PLEASE_QUESTION_ANSWER'));
                    }

                    
                // ---------- save เรียงประโยค ----------
                } else if ($("input[name='__title_type']:checked").val() === '3') {
                    var lineSortSentence = "";
                    $("input[id^='result_sort_sentence']").each(function () {
                        var $line = $(this).attr('name').slice(20);
                        lineSortSentence += $line + ',';
                    });

                    if ($("input[id^='result_sort_sentence']").length === 0) {
                        lineSortSentence = '';
                    }

                    if (lineSortSentence !== '') {
                        if (!chkBlankValueMatch()) {
                            lineSortSentence = lineSortSentence.substring(0, lineSortSentence.length - 1);
                            $('#lineSortSentence').val(lineSortSentence);
                            $("#tmpField").val($("form").serialize());
                            confirmSave();
                        } else {
                            alert(getSwapLang('PLEASE_ANSWER'));
                        }
                    } else {
                        alert(getSwapLang('PLEASE_ANSWER'));
                    }

                    
                // ---------- save แบบสอบถาม ----------
                } else if ($("input[name='__title_type']:checked").val() === '4') {
                    var lineQuestionnaire = "";
                    var chkBlankValue = false;
                    if ($("input[name='__query_type']:checked").val() === '0') { // ตอบได้ข้อเดียว
                        $("textarea[name^='detail']").each(function () {
                            var $line = $(this).attr('name').slice(6);
                            lineQuestionnaire += $line + ',';

                            var $questionnaire_detail = removeLineBreak(CKEDITOR.instances[$(this).attr('name')].getData());
                            if ($questionnaire_detail === '') {
                                chkBlankValue = true;
                            }
                            $questionnaire_detail = chkFloatLeft($questionnaire_detail);
                            $questionnaire_detail = chkFloatRight($questionnaire_detail);
                            $('#questionnaire_detail' + $line).val($questionnaire_detail);
                            $('#questionnaire_detail_format' + $line).val(setReplaceGoSave(CKEDITOR.instances[$(this).attr('name')].element["$"].nextSibling.childNodes[1].childNodes[1].childNodes[1].contentDocument.childNodes[1].childNodes[1].innerHTML));
                        });

                        if ($("textarea[name^='detail']").length === 0) {
                            lineQuestionnaire = '';
                        }

                        if (lineQuestionnaire !== '') {
                            if (!chkBlankValue) {
                                lineQuestionnaire = lineQuestionnaire.substring(0, lineQuestionnaire.length - 1);
                                $('#lineQuestionnaire').val(lineQuestionnaire);
                                $("#tmpField").val($("form").serialize());
                                confirmSave();
                            } else {
                                alert(getSwapLang('PLEASE_SELECT_DETAIL'));
                            }
                        } else {
                            alert(getSwapLang('PLEASE_SELECT_DETAIL'));
                        }

                        
                    } else if ($("input[name='__query_type']:checked").val() === '1') { // ตอบได้หลายข้อ
                        var lineQuestionnaireMulti = "";
                        var chkBlankValue = false;
                        $("textarea[name^='detail']").each(function () {
                            var $line = $(this).attr('name').slice(6);
                            lineQuestionnaireMulti += $line + ',';

                            var $questionnaire_multi_detail = removeLineBreak(CKEDITOR.instances[$(this).attr('name')].getData());
                            if ($questionnaire_multi_detail === '') {
                                chkBlankValue = true;
                            }
                            $questionnaire_multi_detail = chkFloatLeft($questionnaire_multi_detail);
                            $questionnaire_multi_detail = chkFloatRight($questionnaire_multi_detail);
                            $('#questionnaire_multi_detail' + $line).val($questionnaire_multi_detail);
                            $('#questionnaire_multi_detail_format' + $line).val(setReplaceGoSave(CKEDITOR.instances[$(this).attr('name')].element["$"].nextSibling.childNodes[1].childNodes[1].childNodes[1].contentDocument.childNodes[1].childNodes[1].innerHTML));
                        });

                        if ($("textarea[name^='detail']").length === 0) {
                            lineQuestionnaireMulti = '';
                        }

                        if (lineQuestionnaireMulti !== '') {
                            if (!chkBlankValue) {
                                lineQuestionnaireMulti = lineQuestionnaireMulti.substring(0, lineQuestionnaireMulti.length - 1);
                                $('#lineQuestionnaireMulti').val(lineQuestionnaireMulti);
                                $("#tmpField").val($("form").serialize());
                                confirmSave();
                            } else {
                                alert(getSwapLang('PLEASE_SELECT_DETAIL'));
                            }
                        } else {
                            alert(getSwapLang('PLEASE_SELECT_DETAIL'));
                        }

                    } else if ($("input[name='__query_type']:checked").val() === '2') { // ความคิดเห็น
                        $("#tmpField").val($("form").serialize());
                        confirmSave();
                    }
                }
            }
            
            function chkBlankValueMatch() {
                var result = false;
                $("input[id^='result_sort_sentence']").each(function() {
                   if ($(this).val() === '') {
                       result = true;
                       return false;
                   }
                });
                return result;
            }

            function chkStatusTrueFalse() {
                if ($("input[name='trueFalse']").is(":checked")) {
                    $('#statusTrueFalse').val($("input[name='trueFalse']:checked").val());
                    return true;
                } else {
                    alert(getSwapLang('PLEASE_ANSWER'));
                    $("input[name='trueFalse']").prop('checked', true);
                    return false;
                }
            }
            
            function GoUpdate() {
                update();
            }

            function GoDelete() {
                edelete();
            }

            function GoSearch() {
                search();
            }

            function updateRecord() {
                with (document.cscform) {
                    bCon = confirm(MyCode[3]);
                    if (bCon === true) {
                        __confirm.value = "s";
                        __cmd.value = "save";
                        submit();
                    }
                }
            }

            function GoClean() {
                with (document.cscform) {
                    if (((typeof __cmd) !== "undefined") && ((typeof __confirm) !== "undefined")) {
                        __cmd.value = "save";
                        __confirm.value = "c";
                        if ((typeof window.parent.leftFrame) !== "undefined") {
                            with (window.parent.leftFrame.document.cscform) {
                                __sysisedit.value = "";
                            }
                        }
                        $('#__question').val('');
                        $('#__question_format').val('');
                        $('#tmpField').val('');
                        $('#lineObjective').val('');
                        $('#lastLineObjective').val('');
                        $('#lineMatch').val('');
                        $('#lastLineMatch').val('');
                        $('#lineSortSentence').val('');
                        $('#lastLineSortSentence').val('');
                        $('#lineQuestionnaire').val('');
                        $('#lastLineQuestionnaire').val('');
                        $('#lineQuestionnaireMulti').val('');
                        $('#lastLineQuestionnaireMulti').val('');
                        submit();
                    }
                }
            }


            // ---------- Preview ----------
            $('#openDialog').click(function () {
                var $detail = '';
                var $question = removeLineBreak(editor.getData());
                if ($("input[name='__title_type']:checked").val() === '0') { // ปรนัย
                    $("textarea[name^='detail']").each(function () {
                        var $data = removeLineBreak(CKEDITOR.instances[$(this).attr('name')].getData());
                        $data = chkFloatLeft($data);
                        $data = chkFloatRight($data);
                        var $msgFirst = $data.slice(0, $data.indexOf('>') + 1);
                        var $msgLast = $data.slice($data.indexOf('>') + 1);
                        $detail += $msgFirst + '<input type="radio" name="pre_question">&nbsp;' + $msgLast;
                    });
                } else if ($("input[name='__title_type']:checked").val() === '1') { // อัตนัย
                    $detail = '<textarea cols="140" rows="5"></textarea>';
                } else if ($("input[name='__title_type']:checked").val() === '2') { // จับคู่
                    var fieldQuestionDetail = {};
                    var fieldAnswerMatchDetail = {};
                    var size = 0;
                    $("textarea[name^='question_detail_format']").each(function (i) {
                        size = i + 1;
                        var $line = $(this).attr('name').slice(22);
                        var $question_detail = removeLineBreak(CKEDITOR.instances['question' + $line].getData());
                        $question_detail = chkFloatLeft($question_detail);
                        $question_detail = chkFloatRight($question_detail);
                        fieldQuestionDetail[size] = $question_detail;

                        var $answer_match_detail = removeLineBreak(CKEDITOR.instances['answer' + $line].getData());
                        $answer_match_detail = chkFloatLeft($answer_match_detail);
                        $answer_match_detail = chkFloatRight($answer_match_detail);
                        fieldAnswerMatchDetail[size] = $answer_match_detail; 
                        
                    });
                    var tmpRandom = '';
                    $detail = '<table class="table-preview" style="width: 100%;border-style: none;">';
                    var $option = '';
                    for (var i = 1; i <= size; i++ ) {
                        $option += '<option value="' + i + '">' + i+ '</option>';
                    }
                    var $line = 1;
                    for(var x in fieldQuestionDetail){
                        var valueQuestionDetail = fieldQuestionDetail[x];
                        var valueAnswerMatchDetail = '';
                        var random = parseInt(Math.random() * size + 1);
                        var statusFound = true;
                        while (statusFound) {
                            if (tmpRandom.indexOf(',' + random + ',') === -1 || tmpRandom === '') {
                                statusFound = false;
                                tmpRandom += ',' + random + ',';
                                valueAnswerMatchDetail = fieldAnswerMatchDetail[random];
                                var $msgQuestionFirst = valueQuestionDetail.slice(0, valueQuestionDetail.indexOf('>') + 1);
                                var $msgQustionLast = valueQuestionDetail.slice(valueQuestionDetail.indexOf('>') + 1);
                                
                                var $msgAnswerFirst = valueAnswerMatchDetail.slice(0, valueAnswerMatchDetail.indexOf('>') + 1);
                                var $msgAnswerLast = valueAnswerMatchDetail.slice(valueAnswerMatchDetail.indexOf('>') + 1);
                                
                                if (valueQuestionDetail === '') {
                                    $detail += '<tr><td width="40%">&nbsp;</td><td>' + $msgAnswerFirst + $line + '.' + $msgAnswerLast + '</td></tr>';
                                } else {
                                   $detail += '<tr><td width="40%">' + $msgQuestionFirst + '<select>' + $option + '</select>' + $msgQustionLast + '</td><td>' + $msgAnswerFirst + $line + '.&nbsp;&nbsp;' + $msgAnswerLast + '</td></tr>'; 
                                }
                                
                                
                                $line++;
                            } else {
                                random = parseInt(Math.random() * size + 1);
                            }  
                        }
                    }
                    $detail += '</table>';
                } else if ($("input[name='__title_type']:checked").val() === '3') { // เรียงประโยค
                    var fieldSortSentence = {};
                    var size = 0;
                    $("input[id^='result_sort_sentence']").each(function(i) {
                        size = i + 1;
                        fieldSortSentence[size] = $(this).val();
                    });
                    
                    $detail += '<br><div id="result" style="height: 25px;border-bottom: 1px solid #000000;"></div><br>';
                    var question = '';
                    var tmpRandom = '';
                    var random = parseInt(Math.random() * size + 1);
                    for(var x in fieldSortSentence){
                        var statusFound = true;
                        while (statusFound) {
                            if (tmpRandom.indexOf(',' + random + ',') === -1 || tmpRandom === '') {
                                statusFound = false;
                                tmpRandom += ',' + random + ',';
                                question += '<span class="plus">' + fieldSortSentence[random] + '</span>';
                            } else {
                                random = parseInt(Math.random() * size + 1);
                            }
                        }
                    }
                    $detail += '<div id="question">' + question + '</div>';
                } else if ($("input[name='__title_type']:checked").val() === '4') { // แบบสอบถาม
                    if ($("input[name='__query_type']:checked").val() === '0') { // ตอบได้ข้อเดียว
                        $("textarea[name^='detail']").each(function () {
                            var $data = removeLineBreak(CKEDITOR.instances[$(this).attr('name')].getData());
                            $data = chkFloatLeft($data);
                            $data = chkFloatRight($data);
                            var $msgFirst = $data.slice(0, $data.indexOf('>') + 1);
                            var $msgLast = $data.slice($data.indexOf('>') + 1);
                            $detail += $msgFirst + '<input type="radio" name="pre_question">&nbsp;' + $msgLast;
                        });
                    } else if ($("input[name='__query_type']:checked").val() === '1') { // ตอบได้หลายข้อ
                        $("textarea[name^='detail']").each(function () {
                            var $data = removeLineBreak(CKEDITOR.instances[$(this).attr('name')].getData());
                            $data = chkFloatLeft($data);
                            $data = chkFloatRight($data);
                            var $msgFirst = $data.slice(0, $data.indexOf('>') + 1);
                            var $msgLast = $data.slice($data.indexOf('>') + 1);
                            $detail += $msgFirst + '<input type="checkbox" name="pre_question">&nbsp;' + $msgLast;
                        });
                    } else if ($("input[name='__query_type']:checked").val() === '2') { // ความคิดเห็น
                        $detail = '<textarea cols="140" rows="5"></textarea>';
                    }
                }

                $detail = setReplacePreview($detail);
                $('.modal-body').html('<strong style="color: #000000;font-size: 150%;">' + getSwapLang('QUESTION') + '</strong><br><br><span style="color: #000000;"><strong>' + $question + "</strong>" + $detail + '</span>');
                plus();
            });

            function removeLineBreak(msg) {
                return msg.replace(/(\r\n|\n|\r)/gm, '');
            }

            function setReplacePreview(msg) {
                msg = msg.replace(/\&#3618;&#160;/g, '&nbsp;');
                msg = msg.replace(/\&#3618;/g, '&nbsp;');
                msg = msg.replace(/\<p> <\/p>/g, '');
                return msg;
            }

            function setReplaceGoSave(msg) {
                msg = msg.replace(/\<br>/g, '&nbsp;');
                msg = msg.replace(/\<p> <\/p>/g, '');
                msg = msg.replace(/\<p>&#3618;&#160;<\/p>/g, '');
                msg = msg.replace('"true"></p>','"true">&nbsp;</p>');
                return msg;
            }

            function chkFloatLeft(answer) {
                var $first = '';
                var $last = '';
                while (answer.indexOf('float:left') > -1) {
                    $first = answer.substring(0, answer.indexOf('style=\"float:left\"'));
                    if ($first.indexOf('<p><img') > -1) {
                        $first = $first.replace('<p><img', '<p style="text-align: left;"><img');
                    } else if ($first.indexOf('<p style="text-align: center"><img') > -1) {
                        $first = $first.replace('<p style="text-align: center"><img', '<p style="text-align: left;"><img');
                    }
                    $last = answer.slice(answer.indexOf('style=\"float:left\"'));
                    $last = $last.replace('style=\"float:left\"', '');
                    answer = $first + $last;
                }
                return answer;
            }

            function chkFloatRight(answer) {
                var $first = '';
                var $last = '';
                while (answer.indexOf('float:right') > -1) {
                    $first = answer.substring(0, answer.indexOf('style=\"float:right\"'));
                    if ($first.indexOf('<p><img') > -1) {
                        $first = $first.replace('<p><img', '<p style="text-align: right;"><img');
                    } else if ($first.indexOf('<p style="text-align: center"><img') > -1) {
                        $first = $first.replace('<p style="text-align: center"><img', '<p style="text-align: right;"><img');
                    }
                    $last = answer.slice(answer.indexOf('style=\"float:right\"'));
                    $last = $last.replace('style=\"float:right\"', '');
                    answer = $first + $last;
                }
                return answer;
            }

            function linkHelp(help, input) {
                with (document.cscform) {
                    obj = eval("document.cscform." + input);
                    var param = "PRU084_NEW_APS.jsp?__helpName=" + help + "&__fieldSearch=" + input + "&__pageCall=" + __screen.value + "&__fixCon=" + __fixCon.value + "&tdeq=1";
                    if (obj.value === "") {
                        param = "PRU084_NEW_APS.jsp?__helpName=" + help + "&__fieldSearch=" + input + "&__pageCall=" + __screen.value + "&__fixCon=" + __fixCon.value + "&tdeq=1";
                    }
                    win = window.open(param, "Help", "left=300,top=150,width=700,height=400,resizable=yes,scrollbars=yes,toolbar=no,status=yes");
                    if (window.focus) {
                        win.focus();
                    }
                }
            }

            function chkInteger(e) {
                var keyCode = getKeyCode(e);
                if (((keyCode < 48) || (keyCode > 57)) && keyCode !== 46) {
                    cancelEvents(e);
                }
            }

            $(function () { // Start jquery
                if ($("#tmpField").val() !== "" && $("#tmpField").val() !== undefined) {
                    var sp = $("#tmpField").val().split("&");
                    for (var a = 0; a < sp.length - 1; a++) {
                        var sp2 = sp[a].split("=");
                        field[decodeURIComponent(sp2[0].replace(/\+/g, " "))] = decodeURIComponent(sp2[1].replace(/\+/g, " "));  //sp2[0] == key  sp2[1] == value
                    }
                }

                var $detail_format = $('#__question_format').val();
                if ($detail_format !== '') {
                    editor.setData($detail_format);
                }

                $("input[name='__title_type']").removeAttr('onmouseover').css('cursor', 'pointer').parent().css('font-weight', 'normal');
                $("input[name='__active_status']").removeAttr('onmouseover').css('cursor', 'pointer').parent().css('font-weight', 'normal');
                $("input[name='__query_type']").removeAttr('onmouseover').css('cursor', 'pointer').parent().css('font-weight', 'normal');

                // ---------- gen data ปรนัย ----------
                if ($("input[name='__title_type']:checked").val() === '0') {
                    appendHeaderObjective();
                    if ($("input[name='select']").length === 0) {
                        var $lineObjective = $('#lineObjective').val();
                        if ($lineObjective !== '' && $lineObjective !== undefined) {
                            var sp = $lineObjective.split(',');
                            for (var i = 0; i < sp.length; i++) {
                                genObjective(sp[i]);
                            }
                        } else {
                            for (var i = 1; i <= 4; i++) {
                                genObjective(i);
                            }
                        }
                    }
                // ---------- gen data อัตนัย ----------
                } else if ($("input[name='__title_type']:checked").val() === '1') {
                    genSubjective();
                // ---------- gen data จับคู่ ----------
                } else if ($("input[name='__title_type']:checked").val() === '2') {
                    genMatch();
                // ---------- gen data เรียงประโยค ----------
                } else if ($("input[name='__title_type']:checked").val() === '3') {
                    genSortSentence();
                // ---------- gen data แบบสอบถาม ----------
                } else if ($("input[name='__title_type']:checked").val() === '4') {
                    hideScore();
                    showTypeQuery();
                    if ($("input[name='__query_type']:checked").val() === '0') { // ตอบได้ข้อเดียว
                        genQuestionnaire();
                    } else if ($("input[name='__query_type']:checked").val() === '1') { // ตอบได้หลายข้อ
                        genQuestionnaireMulti();
                    } else if ($("input[name='__query_type']:checked").val() === '2') { // ความคิดเห็น
                        
                    }
                }

                $('#add').click(function () {
                    if ($("input[name='__title_type']:checked").val() === '0') { // ปรนัย
                        genObjective(parseInt($('#lastLineObjective').val()) + 1);
                    } else if ($("input[name='__title_type']:checked").val() === '2') { // จับคู่
                        addMatch(parseInt($('#lastLineMatch').val()) + 1);
                    } else if ($("input[name='__title_type']:checked").val() === '3') { // เรียงประโยค
                        addSortSentence(parseInt($('#lastLineSortSentence').val()) + 1);
                    } else if ($("input[name='__title_type']:checked").val() === '4') { // แบบสอบถาม
                        if ($("input[name='__query_type']:checked").val() === '0') {
                            addQuestionnaire(parseInt($('#lastLineQuestionnaire').val()) + 1); // ตอบได้ข้อเดียว
                        } else if ($("input[name='__query_type']:checked").val() === '1') {
                            addQuestionnaireMulti(parseInt($('#lastLineQuestionnaireMulti').val()) + 1); // ตอบได้หลายข้อ
                        }
                    }
                });

                $('#selectAll').click(function () {
                    $("input[name='select']").prop('checked', true);
                });

                $('#deselectAll').click(function () {
                    $("input[name='select']").prop('checked', false);
                });

                $('#del').click(function () {
                    // ---------- ลบ ปรนัย ---------- || // ---------- ลบ จับคู่ ----------
                    if ($("input[name='__title_type']:checked").val() === '0' || $("input[name='__title_type']:checked").val() === '2' || $("input[name='__title_type']:checked").val() === '3' || ($("input[name='__title_type']:checked").val() === '4' && $("input[name='__query_type']:checked").val() === '0') || ($("input[name='__title_type']:checked").val() === '4' && $("input[name='__query_type']:checked").val() === '1')) {
                        $("input[name='select']:checked").each(function () {
                            $(this).closest('tr').remove();
                        });
                    }
                });

                // ---------- title_title change ----------
                $("input[name='__title_type']").change(function () {
                    // ---------- ปรนัย ----------
                    if ($(this).val() === '0') {
                        delObjective();
                        removeTrOnchange();
                        appendHeaderObjective();
                        showButton();
                        showScore();
                        hideTypeQuery();
                        for (var i = 1; i <= 4; i++) {
                            genObjective(i);
                        }
                    // ---------- อัตนัย ----------
                    } else if ($(this).val() === '1') {
                        delObjective();
                        removeTrOnchange();
                        genSubjective();
                        showScore();
                        hideTypeQuery();
                    // ---------- จับคู่ ----------
                    } else if ($(this).val() === '2') {
                        delObjective();
                        removeTrOnchange();
                        genMatch();
                        showButton();
                        showScore();
                        hideTypeQuery();
                    // ---------- เรียงประโยค ----------
                    } else if ($(this).val() === '3') {
                        removeTrOnchange();            
                        genSortSentence();
                        showScore();
                        hideTypeQuery();
                    // ---------- แบบสอบถาม ----------
                    } else if ($(this).val() === '4') {
                        removeTrOnchange();            
                        hideScore();
                        showTypeQuery();
                        var $query_type = $("input[name='__query_type']:checked").val();
                        if ($query_type === '0') {
                           genQuestionnaire(); 
                        } else if ($query_type === '1'){
                            genQuestionnaireMulti();
                        } else if ($query_type === '2'){
                            
                        } 
                    }
                });
                
                $("input[name='__query_type']").change(function() {
                    // ---------- แบบสอบถาม ----------
                    removeTrOnchange();            
                    hideScore();
                    showTypeQuery();
                    if ($(this).val() === '0') { // ตอบได้ข้อเดียว
                       genQuestionnaire();
                    } else if ($(this).val() === '1') { // ตอบได้หลายข้อ
                       genQuestionnaireMulti();
                    } else if ($(this).val() === '2') { // ความคิดเห็น
                       
                    }
                });

            }); // end jquery
            
            function showButton() {
                $('#selectAll').show();
                $('#deselectAll').show();
                $('#del').show();
                $('#add').show();
            }
            
            function genObjective(i) {
                $('#tb').append($('<tr/>')
                    .append($('<td class="text-center" style="vertical-align: middle;"/>')
                        .append(
                            $('<input/>', {
                                type: 'checkbox',
                                name: 'select'
                            }),
                            $('<textarea/>', {
                                name: 'question_detail' + i,
                                id: 'question_detail' + i,
                                style: 'display:none'
                            }),
                            $('<textarea/>', {
                                name: 'question_detail_format' + i,
                                id: 'question_detail_format' + i,
                                style: 'display:none'
                            })
                        ),
                        $('<td class="text-center" style="vertical-align: middle;"/>').append(
                            $('<input/>', {
                                type: 'radio',
                                name: 'trueFalse',
                                value: i
                            })
                        ),
                        $('<td class="text-center"/>').append(
                            $('<textarea/>', {
                                name: 'detail' + i,
                                rows: 5,
                                cols: 50
                            })
                        )
                    )
                );
                CKEDITOR.replace('detail' + i, {
                    customConfig: '../CKEDITOR/config_for_new_aps.js',
                    width: 770,
                    height: 80,
                    language: 'en'
                });
                
                $('#lastLineObjective').val(i);
                CKEDITOR.instances['detail' + i].setData(field['question_detail_format' + i]);
                $('#question_detail' + i).val(field['question_detail' + i]);
                $('#question_detail_format' + i).val(field['question_detail_format' + i]);
                var $statusTrueFalse = $('#statusTrueFalse').val();
                if (typeof (field['result_objective' + i]) !== 'undefined') {
                    $statusTrueFalse = field['result_objective' + i];
                    if ($statusTrueFalse === '1') {
                        $("input[name='trueFalse'][value=" + i + "]").prop('checked', true);
                    }
                } else {
                    if ($("input[name='trueFalse'][value=" + i + "]").attr('value') === $statusTrueFalse) {
                        $("input[name='trueFalse'][value=" + i + "]").prop('checked', true);
                    }
                }
            }

            function genSubjective() {
                $('#selectAll').hide();
                $('#deselectAll').hide();
                $('#del').hide();
                $('#add').hide();
                $('#tb').append(
                    $('<tr/>').append(
                        $('<td class="detailHeader text-center" style="width: 150px;vertical-align: middle;"/>').append(
                            getSwapLang('ANSWER')
                        )
                    ),
                    $('<tr/>').append(
                        $('<td class="text-center"/>').append(
                            $('<textarea>', {
                                id: 'result_subjective',
                                name: 'result_subjective',
                                rows: 6,
                                cols: 110
                            })    
                        )
                    )
                );
                if (typeof (field['result_subjective']) !== 'undefined') {
                    $('#result_subjective').val(field['result_subjective']);
                }
            }
            
            function genMatch() {
                $('#tb').append(
                    $('<tr/>').append(
                        $('<td class="detailHeader"/>').append(getSwapLang('SELECT')),
                        $('<td class="detailHeader"/>').append(getSwapLang('QUESTION')),
                        $('<td class="detailHeader"/>').append(getSwapLang('ANSWER'))
                    )
                );
                var $lineMatch = $('#lineMatch').val();
                if ($lineMatch !== '' && $lineMatch !== undefined) {
                    var sp = $lineMatch.split(',');
                    for (var i = 0; i < sp.length; i++) {
                        addMatch(sp[i]);
                        CKEDITOR.instances['question' + sp[i]].setData(field['question_detail_format' + sp[i]]);
                        $('#question_detail' + sp[i]).val(field['question_detail' + sp[i]]);
                        $('#question_detail_format' + sp[i]).val(field['question_detail_format' + sp[i]]);
                        
                        CKEDITOR.instances['answer' + sp[i]].setData(field['answer_match_detail_format' + sp[i]]);
                        $('#answer_match_detail' + sp[i]).val(field['answer_match_detail' + sp[i]]);
                        $('#answer_match_detail_format' + sp[i]).val(field['answer_match_detail_format' + sp[i]]);  
                    }
                } else {
                    for (var i = 1; i <= 4; i ++) {
                        addMatch(i);
                    }
                }
            }
            
            function addMatch(i) {
                $('#tb').append(
                    $('<tr/>').append(
                        $('<td class="text-center" style="vertical-align: middle;"/>').append(
                            $('<input/>', {
                                type: 'checkbox',
                                name: 'select'
                            }),
                            $('<textarea/>', {
                                name: 'question_detail' + i,
                                id: 'question_detail' + i,
                                style: 'display:none'
                            }),
                            $('<textarea/>', {
                                name: 'question_detail_format' + i,
                                id: 'question_detail_format' + i,
                                style: 'display:none'
                            }),
                            $('<textarea/>', {
                                name: 'answer_match_detail' + i,
                                id: 'answer_match_detail' + i,
                                style: 'display:none'
                            }),
                            $('<textarea/>', {
                                name: 'answer_match_detail_format' + i,
                                id: 'answer_match_detail_format' + i,
                                style: 'display:none'
                            })
                        ),
                        $('<td class="text-center"/>').append(
                            $('<textarea/>', {
                                id: 'question' + i,
                                name: 'question' + i,
                                rows: 5,
                                cols: 50
                            })
                        ),
                        $('<td class="text-center"/>').append(
                            $('<textarea/>', {
                                id: 'answer' + i,
                                name: 'answer' + i,
                                rows: 5,
                                cols: 50
                            })
                        )
                    )   
                );
                CKEDITOR.replace('question' + i, {
                    customConfig: '../CKEDITOR/config_for_new_aps.js',
                    width: 430,
                    height: 80,
                    language: 'en'
                });
                CKEDITOR.replace('answer' + i, {
                    customConfig: '../CKEDITOR/config_for_new_aps.js',
                    width: 430,
                    height: 80,
                    language: 'en'
                });
                $('#lastLineMatch').val(i);
            }
            
            function genSortSentence() {
                $('#tb').append(
                    $('<tr/>').append(
                        $('<td class="detailHeader text-center" style="vertical-align: middle;"/>').append(
                            getSwapLang('SELECT')
                        ),
                        $('<td class="detailHeader text-center" />').append(
                            getSwapLang('ANSWER') 
                        )
                    )
                );
                var $lineSortSentence = $('#lineSortSentence').val();
                if ($lineSortSentence !== '' && $lineSortSentence !== undefined) {
                    var sp = $lineSortSentence.split(',');
                    for (var i = 0; i < sp.length; i++) {
                        addSortSentence(sp[i]);
                        if (typeof(field['result_sort_sentence' + sp[i]]) !== 'undefined') {
                            $('#result_sort_sentence' + sp[i]).val(field['result_sort_sentence' + sp[i]]);
                        }
                    }
                } else {
                    for (var i = 1; i <= 5; i ++) {
                        addSortSentence(i);
                    }
                }
            }
            
            function addSortSentence(i) {
                $('#tb').append(
                    $('<tr/>').append(
                        $('<td class="text-center" />').append(
                            $('<input/>', {
                                type: 'checkbox',
                                name: 'select'
                            })
                        ),
                        $('<td class="text-center" />').append('<input type="text" id="result_sort_sentence' + i + '" name="result_sort_sentence' + i + '" size="80">')
                    )     
                );
                $('#lastLineSortSentence').val(i);
            }
            
            function genQuestionnaire() {
                hideScore();
                if ($("input[name='__query_type']:checked").val() === '0') {
                    appendHeaderQuestionnaire();
                    if ($("input[name='select']").length === 0) {
                        var $lineQuestionnaire = $('#lineQuestionnaire').val();
                        if ($lineQuestionnaire !== '' && $lineQuestionnaire !== undefined) {
                            var sp = $lineQuestionnaire.split(',');
                            for (var i = 0; i < sp.length; i++) {
                                addQuestionnaire(sp[i]);
                            }
                        } else {
                            for (var i = 1; i <= 2; i++) {
                                addQuestionnaire(i);
                            }
                        }
                    }        
                }
            }
            
            function addQuestionnaire(i) {
                $('#tb').append($('<tr/>')
                    .append($('<td class="text-center" style="vertical-align: middle;"/>')
                        .append(
                            $('<input/>', {
                                type: 'checkbox',
                                name: 'select'
                            }),
                            $('<textarea/>', {
                                name: 'questionnaire_detail' + i,
                                id: 'questionnaire_detail' + i,
                                style: 'display:none'
                            }),
                            $('<textarea/>', {
                                name: 'questionnaire_detail_format' + i,
                                id: 'questionnaire_detail_format' + i,
                                style: 'display:none'
                            })
                        ),
                        $('<td class="text-center"/>').append(
                            $('<textarea/>', {
                                name: 'detail' + i,
                                rows: 5,
                                cols: 50
                            })
                        )
                    )
                );
                CKEDITOR.replace('detail' + i, {
                    customConfig: '../CKEDITOR/config_for_new_aps.js',
                    width: 830,
                    height: 80,
                    language: 'en'
                });
                
                $('#lastLineQuestionnaire').val(i);
                CKEDITOR.instances['detail' + i].setData(field['questionnaire_detail_format' + i]);
                $('#questionnaire_detail' + i).val(field['questionnaire_detail' + i]);
                $('#questionnaire_detail_format' + i).val(field['questionnaire_detail_format' + i]);
            }
            
            function genQuestionnaireMulti() {
                hideScore();
                if ($("input[name='__query_type']:checked").val() === '1') {
                    appendHeaderQuestionnaire();
                    var $lineQuestionnaireMulti = $('#lineQuestionnaireMulti').val();
                    if ($lineQuestionnaireMulti !== '' && $lineQuestionnaireMulti !== undefined) {
                        var sp = $lineQuestionnaireMulti.split(',');
                        for (var i = 0; i < sp.length; i++) {
                            addQuestionnaireMulti(sp[i]);
                        }
                    } else {
                        for (var i = 1; i <= 2; i++) {
                            addQuestionnaireMulti(i);
                        }
                    }        
                }
            }
            
            function addQuestionnaireMulti(i) {
                $('#tb').append($('<tr/>')
                    .append($('<td class="text-center" style="vertical-align: middle;"/>')
                        .append(
                            $('<input/>', {
                                type: 'checkbox',
                                name: 'select'
                            }),
                            $('<textarea/>', {
                                name: 'questionnaire_multi_detail' + i,
                                id: 'questionnaire_multi_detail' + i,
                                style: 'display:none'
                            }),
                            $('<textarea/>', {
                                name: 'questionnaire_multi_detail_format' + i,
                                id: 'questionnaire_multi_detail_format' + i,
                                style: 'display:none'
                            })
                        ),
                        $('<td class="text-center"/>').append(
                            $('<textarea/>', {
                                name: 'detail' + i,
                                rows: 5,
                                cols: 50
                            })
                        )
                    )
                );
                CKEDITOR.replace('detail' + i, {
                    customConfig: '../CKEDITOR/config_for_new_aps.js',
                    width: 830,
                    height: 80,
                    language: 'en'
                });
                
                $('#lastLineQuestionnaireMulti').val(i);
                CKEDITOR.instances['detail' + i].setData(field['questionnaire_multi_detail_format' + i]);
                $('#questionnaire_multi_detail' + i).val(field['questionnaire_multi_detail' + i]);
                $('#questionnaire_multi_detail_format' + i).val(field['questionnaire_multi_detail_format' + i]);
                
            }
            
            function appendHeaderQuestionnaire() {
                $('#tb').append(
                    $('<tr/>').append(
                        $('<td class="detailHeader"/>').append(getSwapLang('SELECT')),
                        $('<td class="detailHeader"/>').append(getSwapLang('DETAIL'))
                    )
                );
            }
            
            function hideScore() {
                $("input[name='__score']").closest('tr').hide();
            }
            
            function showScore() {
                $("input[name='__score']").closest('tr').show();
            }

            function  removeTrOnchange() {
                $('#tb > tbody > tr').remove();
            }

            function appendHeaderObjective() {
                $('#tb')
                    .append($('<tr/>')
                        .append(
                            $('<td class="detailHeader"/>').append(getSwapLang('SELECT')),
                            $('<td class="detailHeader"/>').append(getSwapLang('ANSWER_TRUE')),
                            $('<td class="detailHeader"/>').append(getSwapLang('DETAIL'))
                        )
                    );
            }

            function delObjective() {
                $("textarea[name^='question_detail_format']").each(function () {
                    $(this).closest('tr').remove();
                });
            }
            
            function del() {
                $('.del').click(function() {
                    $(this).attr('class','plus');
                    $('#question').html($.trim($('#question').html()) + $(this).context.outerHTML);
                    $(this).remove();
                    plus();
                });
            }

            function plus() {
                $('.plus').click(function() {
                    $(this).attr('class','del');
                    $('#result').html($.trim($('#result').html()) + $(this).context.outerHTML);
                    $(this).remove();
                    del();
                });
            }
            
            function hideTypeQuery() {
                $('#comment').closest('tr').hide();
            }
            
            function showTypeQuery() {
              $('#comment').closest('tr').show();  
            }

        </script>
    </body>
</html>
<%screen.referLangOff();%>