<%@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_002" class="com.csc.library.system.Task" scope="page"/>
<%
    APS_NEW_002.setChannel(request,response);
    APS_NEW_002.checkProfile();
    UIManager screen = (UIManager) APS_NEW_002.process("SingleEntry","APS_NEW_002");
    String lang = screen.getUProfile().get("lang");
    screen.referLangOff();
    CheckNull chk = new CheckNull();
    String tmpLine = chk.chkNullString(request.getParameter("tmpLine"));
    String tmpField = chk.chkNullString(request.getParameter("tmpField"));
    String tmpSubGroupid = chk.chkNullString(request.getParameter("tmpSubGroupid"), screen.getDataLabel("sub_groupid"));
%>
<!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;
                vertical-align: middle;
            }
            .table-preview > tbody > tr > td {
                background-color: #ffffff;
                color: #000000;
            }
            
            .plus, .del {
                cursor: pointer;
                padding: 10px;
            }
            
            p {
                margin: 0px;
            }

        </style>
    </head>
    <body>
        <div id="toolTipLayer" style="position:absolute; visibility: hidden"></div>
        <script>initToolTips();</script>
        <form id="cscform" name="cscform" method="post" role="form" action="APS_NEW_002.jsp">
            <!----------BEGIN CSC INITIAL ZONE ------------------------>
            <%=screen.InitialVariable()%>
            <!----------END CSC INITIAL ZONE -------------------------->
            <input type="hidden" name="__screen" value="APS_NEW_002">
            <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_002');</script>&nbsp;</td>
                    </tr>
                    <tr>
                        <td class="blankspace" colspan="2"></td>
                    </tr>
                    <tr>
                        <td class="text-right"><strong><script>swLang('SUB_GROUPID');</script></strong>&nbsp;</td>
                        <td class="text-left"><%=screen.getInput("sub_groupid")%></td>
                    </tr>
                    <tr>
                        <td class="text-right"><script>swLang('SUB_GROUP_NAME');</script>&nbsp;&nbsp;</td>
                        <td class="text-left"><%=screen.getInput("sub_group_name")%></td>
                    </tr>
                    <tr>
                        <td class="text-right"><script>swLang('TITLE_TYPE');</script>&nbsp;&nbsp;</td>
                        <td class="text-left"><%=screen.getInput("title_type")%></td>
                    </tr>
                    <tr>
                        <td class="text-right"><script>swLang('TOTAL_SCORE');</script>&nbsp;&nbsp;</td>
                        <td class="text-left">
                            <span id="tmpScore"><%=screen.getDataLabel("total_score")%></span>
                            <input type="hidden" id="__total_score" name="__total_score" value="<%=screen.getDataLabel("total_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;">
                                <tr>
                                    <td class="detailHeader"><script>swLang('SELECT');</script></td>
                                    <td class="detailHeader"><script>swLang('QUESTIONID');</script></td>
                                    <td class="detailHeader"><script>swLang('DETAIL');</script></td>
                                    <td class="detailHeader"><script>swLang('SCORE');</script></td>
                                </tr>
                            </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 tmpLineDb = "";
                    
                    try {
                        DbInquiry dbi = new InitialInquiry(screen.getUProfile()).getDbInquiry("msub_group_detail");
                        dbi.setColumn("*");
                        dbi.clearOldCondition();
                        dbi.setFilter("sub_groupid = '" + screen.getDataLabel("sub_groupid") + "'");
                        dbi.refresh();
                        while (dbi.next()) {
                            String line = dbi.getString("sub_group_detailid");
                            tmpLineDb += line + ",";
                            tmpFieldDb.append("questionid_" + line + "=" + line + "&");
                            try {
                                DbInquiry mq = new InitialInquiry(screen.getUProfile()).getDbInquiry("mquestion");
                                mq.setColumn("*");
                                mq.clearOldCondition();
                                mq.setFilter("questionid = '" + line + "'");
                                mq.refresh();
                                if (mq.next()) {
                                    tmpFieldDb.append("question_detail_" + line + "=" + URLEncoder.encode(mq.getString("question"), "UTF-8") + "&");
                                    tmpFieldDb.append("score_" + line + "=" + mq.getString("score") + "&");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    String subGroupid = screen.getDataLabel("sub_groupid");
                    boolean stautsChgQuestionid = false;
                    
                    if (!tmpLineDb.equals("")) {
                    	tmpLineDb = tmpLineDb.substring(0, tmpLineDb.length() - 1);
                    }
                    if (tmpLine.equals("") || !tmpSubGroupid.equals(subGroupid)) {
                    	tmpLine = tmpLineDb;
                        stautsChgQuestionid = true;
                    }
                    if (tmpField.equals("")  || !tmpSubGroupid.equals(subGroupid)) {
                    	tmpField = tmpFieldDb.toString();
                    }

                    if (stautsChgQuestionid) {
                        tmpSubGroupid = subGroupid;
                    }
                    
                %>
                <input type="hidden" id="tmpLine" name="tmpLine" value="<%=tmpLine%>">
                <textarea id="tmpField" name="tmpField" style="display: none"><%=tmpField %></textarea>
                <textarea id="tmpPreview" name="tmpPreview" style="display: none"></textarea>
                <input type="hidden" id="tmpSubGroupid" name="tmpSubGroupid" value="<%=tmpSubGroupid%>">

                <!----------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 tmpLine = '';
                $('#tb > tbody > tr').find("input[name^='questionid_']").each(function() {
                   var $line = $(this).val();
                   tmpLine += $line + ',';
                });
                if (tmpLine !== '') {
                    setTotalScore();
                    tmpLine = tmpLine.substring(0,tmpLine.length - 1);
                    $('#tmpLine').val(tmpLine);
                    $("#tmpField").val($("form").serialize());
                    confirmSave();
                } else {
                    alert(getSwapLang('PLEASE_SELECT_QUESTIONID'));
                }  
            }
            
            function setTotalScore() {
                var score = 0;
                $("input[id^='score_']").each(function() {
                    score += parseFloat($(this).val());
                });
                $('#__total_score').val(score);
                $('#tmpScore').text(score.toFixed(2));
            }

            function GoUpdate() {
                update();
            }

            function GoDelete() {
                edelete();
            }

            function GoSearch() {
                search();
            }
            
            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 = "";
                            }
                        }
                        $('#tmpLine').val('');
                        $('#tmpField').val('');
                        submit();
                    }
                }
            }
            
            function getPreview(callback) {
                var questionid = [];
                $("input[name^='questionid_']").each(function() {
                    questionid.push($(this).val());
                });
                
                $.post("APS_NEW_002_PREVIEW.jsp",
                {
                    questionid: questionid.join()
                },
                function(data, status){
                    if(status === "success"){
                        $('#tmpPreview').html($.trim(data));
                        callback();
                    }
                });
            }

            // ---------- Preview ----------
            $('#openDialog').click(function () {
                getPreview(function() {
                    var $detail = '<strong style="color: #000000;font-size: 130%;">' + $("input[name='__sub_group_name']").val() + '</strong><br>';
                    $detail += $('#tmpPreview').val();
                    $detail = setReplacePreview($detail);
                    $('.modal-body').html('<span style="color: #000000;">' + $detail + '</span>');
                    plus();
                });
            });

            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 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 addQuestionid(questionid) {
                $('#tb').append(
                    $('<tr/>').append(
                        $('<td class="text-center"/>').append(
                            $('<p/>').append(
                                $('<input/>', {
                                    type: 'checkbox',
                                    name: 'select'
                                })
                            )
                        ),
                        $('<td class="text-center questionid"/>').append(
                            '<p>' + questionid + '</p>' +
                            '<input type="hidden" id="questionid_' + questionid + '" name="questionid_' + questionid + '" value="' + questionid + '">'
                        ),
                        $('<td class="text-center"/>').append(
                            field['question_detail_' + questionid] +
                            '<textarea style="display: none;" id="question_detail_' + questionid + '" name="question_detail_' + questionid + '">' + field['question_detail_' + questionid] + '</textarea>'
                        ),
                        $('<td class="text-center"/>').append(
                            field['score_' + questionid] +
                            '<input type="hidden" id="score_' + questionid + '" name="score_' + questionid + '" value="' + field['score_' + questionid] + '">'
                        )
                    )    
                );
            }

            $(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
                    }
                }
                
                if ($('#tmpLine').val() !== '') {
                    var sp = $('#tmpLine').val().split(',');
                    for (var i = 0; i < sp.length; i++) {
                        addQuestionid(sp[i]);
                    }
                }

                $('#add').click(function () {
                    window.open("APS_NEW_002_ADD.jsp?title_type=" + $("input[name='__title_type']:checked").val(), "_blank", "toolbar=yes, scrollbars=yes, resizable=yes, top=100, left=300, width=800, height=500");
                });

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

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

                $('#del').click(function () {
                    $("input[name='select']:checked").closest('tr').remove();
                    setTotalScore();
                });
                
                /*var previous = '';
                $("input[name='__title_type']").on('focus',function() {
                    previous = $("input[name='__title_type']:checked").val();
                });*/
                $("input[name='__title_type']").change(function() {
                    //if (confirm('555')) {
                        $('#tb > tbody > tr').not('tr:eq(0)').remove(); 
                    /*} else {
                        $("input[name='__title_type'][value=" + previous + "]").prop('checked',true);
                    }*/
                });

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

            function del() {
                $('.del').click(function() {
                    $(this).attr('class','plus');
                    var $line = $(this).parent().attr('id').slice(6);
                    $('#question' + $line).html($.trim($('#question' + $line).html()) + $(this).context.outerHTML);
                    $(this).remove();
                    plus();
                });
            }

            function plus() {
                $('.plus').click(function() {
                    $(this).attr('class','del');
                    var $line = $(this).parent().attr('id').slice(8);
                    $('#result' + $line).html($.trim($('#result' + $line).html()) + $(this).context.outerHTML);
                    $(this).remove();
                    del();
                });
            }
            
        </script>
    </body>
</html>
<%screen.referLangOff();%>