<%@ Page Language="C#" AutoEventWireup="true" CodeFile="New.aspx.cs" Inherits="Mail_New" ValidateRequest="false" meta:resourcekey="Page" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <link rel="stylesheet" href="../libs/bootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" href="../libs/bootstrapValidator.min.css" />
    <link rel="stylesheet" href="../libs/fontawesome/css/all.min.css" />
    <script type="text/javascript" src="../libs/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="../libs/bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="../libs/bootstrapValidator.min.js"></script>
</head>
<body>
    <style>
        .mailAddrRemove
        {
            color: #FF9151;
        }
    </style>
    <script type="text/javascript">
        var submitType = "";
        var senderNameActb = null;

        $(function () {
            Dialog.setMessage('<asp:Literal runat="server" Text="<%$ Resources:Dialog, Title%>" />', '<asp:Literal runat="server" Text="<%$ Resources:Dialog, OK%>" />', '<asp:Literal runat="server" Text="<%$ Resources:Dialog, Cancel%>" />');
            Dialog.setUseBrowserConfirm(<%=AppSetting.UseBrowserConfirm%>);
            toRcpts = new Recipients();
            ccRcpts = new Recipients();
            bccRcpts = new Recipients();

            $("#form1").bootstrapValidator()
                .on('success.form.bv', function (e) {
                    // 폼 서브미션 금지하고 __doPostBack 호출
                    e.preventDefault();
                    if (toRcpts.Length() == 0) {
                        $("#toRcptWarning").collapse("show");
                        var $form = $(e.target);
                        $form.bootstrapValidator("disableSubmitButtons", false);
                        return;
                    }
                    var postBack = "";
                    if (submitType == "send") {
                        // 메일을 발송하시겠습니까?
                        Dialog.confirm({
                            content: '<asp:Literal runat="server" Text="<%$ Resources:, Msg01%>" />',
                            ok: function () {
                                $("#ToRcptsHidden").val(Recipients.ToJsonString(toRcpts));
                                $("#CcRcptsHidden").val(Recipients.ToJsonString(ccRcpts));
                                $("#BccRcptsHidden").val(Recipients.ToJsonString(bccRcpts));
                                __doPostBack("SendButton", "");
                            },
                            cancel: function () {
                                // confirm 취소 시 서브밋 버튼 활성화
                                var $form = $(e.target);
                                $form.bootstrapValidator("disableSubmitButtons", false);
                            }
                        });
                    } else if (submitType == "save") {
                        // 임시 보관함에 저장하시겠습니까?
                        Dialog.confirm({
                            content: '<asp:Literal runat="server" Text="<%$ Resources:, Msg02%>" />',
                            ok: function () {
                                $("#ToRcptsHidden").val(Recipients.ToJsonString(toRcpts));
                                $("#CcRcptsHidden").val(Recipients.ToJsonString(ccRcpts));
                                $("#BccRcptsHidden").val(Recipients.ToJsonString(bccRcpts));
                                __doPostBack("SaveButton", "");
                            },
                            cancel: function () {
                                // confirm 취소 시 서브밋 버튼 활성화
                                var $form = $(e.target);
                                $form.bootstrapValidator("disableSubmitButtons", false);
                            }
                        });
                    }
                });

            $.ajax({
                type: "POST",
                url: "GetRecipients.aspx/GetAutoCmplRecipientList4Actb",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var autoCmplArray = response.d;
                    actb($("#mailAddrText").get(0), autoCmplArray, undefined, true);
                },
                failure: function (response) {
                    Dialog.alert('<asp:Literal runat="server" Text="<%$ Resources:, Msg03%>" />');     // 자동 완성 데이터 로딩 작업을 실패했습니다.
                }
            });

            InitRecipients();
            //senderNameActb = new actb($("#SenderNameTextBox").get(0), autoCmplSenderArray);
        });

        function Send() {
            submitType = "send";
        }

        function Save() {
            submitType = "save";
        }

        function AddFiles(e) {
            var url = "SelectFile.aspx?key=<%=_uploadKey%>";
            window.open(url, "AttachFileWindow");
            e.stopPropagation();
        }

        function OnCompletedUpload() {
            __doPostBack("AddAttachFileButton", "");
        }

        function RemoveFile(index) {
            $("#<%=RemoveAttachFileIndex.ClientID %>").val(index);
            __doPostBack("RemoveAttachFileButton", "");
        }

        function GotoBack() {
            // 편집한 내용은 저장되지 않습니다.\n메일 편집을 종료하시겠습니까?
            Dialog.confirm({
                content: '<asp:Literal runat="server" Text="<%$ Resources:, Msg04%>" />',
                ok: function () {
                    history.back();
                }
            });
        }

        function ShowMessage(msg) {
            Dialog.alert(msg);
        }

        /*
            Contact, Orgz Dialog 관련 함수 
        */
        var toRcpts = null;
        var ccRcpts = null;
        var bccRcpts = null;

        function InitRecipients() {
            <%=_initRecipientsScript %>;
            ShowRcptListView($("#toListView"), toRcpts);
            ShowRcptListView($("#ccListView"), ccRcpts);
            ShowRcptListView($("#bccListView"), bccRcpts);
            if (ccRcpts.Length() > 0 || bccRcpts.Length() > 0) $("#ExpandRecipients").collapse("toggle");

            $("#rcptSelectModal").on("shown.bs.modal", function () {
                $("#mailAddrText").focus();
            });

            if ("<%=AppSetting.SupportBcc%>" == "False") {
                $("#bccRegion").hide();
            }
        }        
        
        // 주소록/조직도 등에서 메일 쓰기 시 수신자 지정을 위해 사용
        function CallReturnToRecipients(displayName, value, type) {
            // 1: Email, 2: Contact, 3: Orgz 
            if (type == 1)
                toRcpts.AddMailAddress(displayName, value);
            else if (type == 2)
                toRcpts.AddMailGroup(displayName, value);
            else if (type == 3) 
                toRcpts.AddOrgz(displayName, value);
        } 
        
        var rcptType = "";      // + 버튼 클릭 시 받는이/참조/숨은참조를 구분하기 위한 변수

        // 받는이/참조/숨은참조 추가 버튼 클릭
        function OpenMailAddressDialog(rType) {
            rcptType = rType;
            OpenRcptSelectModal();
        }

        // 수신자 입력 모달창 띄우기
        function OpenRcptSelectModal() {
            $("#toRcptWarning").collapse("hide");
            $("#rcptSelectModal").modal();
            $("#mailAddrText").val("");
        }

        // 수신자 입력 모달창에서 메일 주소 입력 후 확인 버튼 클릭 시 호출: 모달을 닫고 입력한 수신자를 UI에 출력한다.
        function AddMailAddress() {
            $("#rcptSelectModal").modal("hide");
            var mailAddr = $("#mailAddrText").val();
            switch (rcptType) {
                case "to":
                    toRcpts.AddMailAddressEx(mailAddr);
                    ShowRcptListView($("#toListView"), toRcpts);
                    break;
                case "cc":
                    ccRcpts.AddMailAddressEx(mailAddr);
                    ShowRcptListView($("#ccListView"), ccRcpts);
                    break;
                case "bcc":
                    bccRcpts.AddMailAddressEx(mailAddr);
                    ShowRcptListView($("#bccListView"), bccRcpts);
                    break;
            }
        }

        // 주소록 버튼 클릭
        function OpenContact() {
            var url = "../Contact/SelectRcpt.aspx?RcptType=" + rcptType;
            window.open(url, "SelectRcpt");
        }

        // 조직도 버튼 클릭
        function OpenOrgz() {
            var url = "../Contact/SelectOrgz.aspx?RcptType=" + rcptType;
            window.open(url, "SelectOrgz");
        }

        // SelectRcpt.aspx, SelectOrgz.aspx에서 데이터를 반환하기 위해 호출
        function ReturnToRecipients(param) {
            var rcpts = Recipients.FromJsonString(param);
            toRcpts.AddRecipients(rcpts);
            $("#rcptSelectModal").modal("hide");
            ShowRcptListView($("#toListView"), toRcpts);
        }
       
        function ReturnCcRecipients(param) {
            var rcpts = Recipients.FromJsonString(param);
            ccRcpts.AddRecipients(rcpts);
            $("#rcptSelectModal").modal("hide");
            ShowRcptListView($("#ccListView"), ccRcpts);
        } 
       
        function ReturnBccRecipients(param) {
            var rcpts = Recipients.FromJsonString(param);
            bccRcpts.AddRecipients(rcpts);
            $("#rcptSelectModal").modal("hide");
            ShowRcptListView($("#bccListView"), bccRcpts);
        }

        // Recipients 오브젝트에 저장되어 있는 수신자 목록을 UI에 출력한다.
        function ShowRcptListView(target, rcptList) {
            var clsName = target.attr("id") + "_remove";
            target.empty();
            for (var i = 0; i < rcptList.recipients.length; i++) {
                var rcpt = rcptList.recipients[i];
                var name = "";
                switch (rcpt.type) {
                    case RcptMailAddr: name = rcpt.name; break;
                    case RcptMailGroup: name = "@[" + rcpt.name + "]"; break;
                    case RcptOrgz: name = "#[" + rcpt.name + "]"; break;
                }
                var tag = "<span class='label label-info'>" + HtmlEncode(name) + " <span class='fa-solid fa-xmark " + clsName +  " mailAddrRemove' data-value='" + i + "'></span></span> ";
                target.append(tag);
            }
            $("." + clsName).click(function () {
                var index = $(this).data("value");
                rcptList.RemoveByIndex(index);
                ShowRcptListView(target, rcptList);
            });
        }

        function IgnoreEnterKey(event) {
            if (event.keyCode == 13) return false;
            return true;
        }

        function HtmlEncode(value) {
            return $('<div/>').text(value).html();
        }

        (function ($, undefined) {
            $.fn.getCursorPosition = function () {
                var el = $(this).get(0);
                var pos = 0;
                if ('selectionStart' in el) {
                    pos = el.selectionStart;
                } else if ('selection' in document) {
                    el.focus();
                    var Sel = document.selection.createRange();
                    var SelLength = document.selection.createRange().text.length;
                    Sel.moveStart('character', -el.value.length);
                    pos = Sel.text.length - SelLength;
                }
                return pos;
            }
        })(jQuery);

        function AddSignature(id) {
            $.ajax({
                type: "POST",
                url: "CallAjax.aspx/GetSignatureEx",
                data: JSON.stringify({ id: id }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var content = $('#MsgTextBox').val();
                    var position = $("#MsgTextBox").getCursorPosition()
                    var newContent = content.substr(0, position) + response.d + content.substr(position);
                    $('#MsgTextBox').val(newContent);
                },
                failure: function (response) {
                    Dialog.alert('<asp:Literal runat="server" Text="<%$ Resources:, Msg06%>" />'); // 서명 데이터 로딩 작업을 실패했습니다.
                }
            });
        }
    </script>

    <form id="form1" runat="server"
        data-bv-feedbackicons-valid="glyphicon glyphicon-ok" 
        data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
        data-bv-feedbackicons-validating="glyphicon glyphicon-refresh">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <CompositeScript>
                <Scripts>
                    <asp:ScriptReference Path="~/libs/tabs/common.js" />
                    <asp:ScriptReference Path="~/libs/tabs/dialog.js" />
                    <asp:ScriptReference Path="~/libs/tabs/Recipients.js" />
                    <asp:ScriptReference Path="~/libs/tabs/actb.js" />
                    <asp:ScriptReference Path="~/libs/tabs/actb_common.js" />
                </Scripts>
            </CompositeScript>
        </asp:ScriptManager>

        <div class="container-fluid">
            <div class="row" id="toolBar" data-spy="affix">
                <div class="col-xs-12" style="padding-top:2px;padding-bottom:2px;">
                    <button type="submit" id="sendToolButton" class="btn btn-primary" onclick="Send()" ><span class="fa-solid fa-paper-plane"></span> <asp:Localize ID="Localize1" runat="server" meta:resourcekey="L01">보내기</asp:Localize></button>
                    <button type="submit" id="saveToolButton" class="btn btn-primary" onclick="Save()"><span class="fa-solid fa-download"></span> <asp:Localize ID="Localize2" runat="server" meta:resourcekey="L02">임시저장</asp:Localize></button>
                    <span>&nbsp;</span>
                    <button type="button" id="Button2" class="btn btn-primary" onclick="GotoBack();"><span class="fa-solid fa-xmark"></span></button>
                </div>
            </div>
        </div>

        <div class="container-fluid" style="padding-top:40px">            
            <div class="form-group">
                <div class="row">
                    <div class="col-xs-10">
                        <label for="addToButton"><asp:Localize ID="Localize3" runat="server" meta:resourcekey="L03">받는이</asp:Localize>:</label>
                        <span id="toListView" style="font-size:larger"></span>
                        <button type="button" id="addToButton" class="btn btn-default" onclick="OpenMailAddressDialog('to')"><span class="fa-solid fa-plus"></span></button>
                        <span id="toRcptWarning" class="text-danger collapse small"><asp:Localize ID="Localize4" runat="server" meta:resourcekey="L04">수신자를 지정 바랍니다.</asp:Localize></span>
                    </div>
                    <div class="col-xs-2 text-right">
                        <span id="expandRcptUI" class="fa-solid fa-chevron-down mc-likeLink" data-toggle="collapse" data-target="#ExpandRecipients"></span>
                    </div>
                </div>
            </div>
            <div id="ExpandRecipients" class="collapse">
                <div class="form-group">
                    <label for="addCcButton"><asp:Localize ID="Localize5" runat="server" meta:resourcekey="L05">참조</asp:Localize>:</label>
                    <span id="ccListView" style="font-size:larger"></span>
                    <button type="button" id="addCcButton" class="btn btn-default" onclick="OpenMailAddressDialog('cc')"><span class="fa-solid fa-plus"></span></button>
                </div>
                <div class="form-group" id="bccRegion">
                    <label for="addBccButton"><asp:Localize ID="Localize6" runat="server" meta:resourcekey="L06">숨은 참조</asp:Localize>:</label>
                    <span id="bccListView" style="font-size:larger"></span>
                    <button type="button" id="addBccButton" class="btn btn-default" onclick="OpenMailAddressDialog('bcc')"><span class="fa-solid fa-plus"></span></button>
                </div>
                <div class="form-group <%=_cssSenderName%>">
                    <label for="SenderNameComboBox"><asp:Localize ID="Localize7" runat="server" meta:resourcekey="L07">보내는 이름</asp:Localize>:</label>
                    <asp:DropDownList ID="SenderNameComboBox" runat="server" CssClass="form-control">
                    </asp:DropDownList>
                </div>
                <div class="form-group <%=_cssSenderAddr%>">
                    <label for="SenderAddrComboBox"><asp:Localize ID="Localize8" runat="server" meta:resourcekey="L08">보내는 메일 주소</asp:Localize>:</label>
                    <asp:DropDownList ID="SenderAddrComboBox" runat="server" CssClass="form-control">
                    </asp:DropDownList>
                </div>
            </div>
            <div class="form-group">
                <label for="SubjectTextBox"><asp:Localize ID="Localize9" runat="server" meta:resourcekey="L09">제목</asp:Localize>:</label>
                <input type="text" runat="server" id="SubjectTextBox" name="SubjectTextBox" class="form-control" placeholder="<%$ Resources:, Ph01%>" autocomplete="off"
                    required data-bv-notempty-message="<%$ Resources:, Msg05%>" />
            </div>
            <asp:UpdatePanel ID="attachPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
                <ContentTemplate>
                    <div class="row" style="padding-bottom:0.5em">
                        <div class="col-xs-12" data-toggle="collapse" data-target="#attachList">
                            <strong><asp:Localize ID="Localize10" runat="server" meta:resourcekey="L10">첨부 파일</asp:Localize>:</strong> 
                            <asp:Label ID="AttachSummaryLabel" runat="server"></asp:Label>
                            <button type="button" id="addAttachButton" class="btn btn-default" onclick="AddFiles(event)"><span class="fa-solid fa-plus"></span></button>
                        </div>
                    </div>
                    <ul id="attachList" runat="server" class="list-group collapse">
                        <asp:Literal ID="AttachListTag" runat="server" />
                    </ul>
                </ContentTemplate>
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="AddAttachFileButton" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="RemoveAttachFileButton" EventName="Click" />
                </Triggers>
            </asp:UpdatePanel>
            <div class="form-group">
                <label for="MsgTextBox"><asp:Localize ID="Localize11" runat="server" meta:resourcekey="L11">본문</asp:Localize>:</label>
                <textarea class="form-control" rows="10" id="MsgTextBox" runat="server"></textarea>
            </div>
            <div class="form-group">
                <div class="dropdown">
                    <button type="button" id="replyToolButton" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
                        <asp:Localize ID="Localize17" runat="server" meta:resourcekey="L17">서명 추가</asp:Localize> <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu">
                        <asp:Repeater ID="SigRepeater" runat="server" DataSourceID="FolderDataSource">
                            <ItemTemplate>
                                <li><a href="#" onclick="AddSignature('<%# Eval("ID") %>');return false;"><%# Eval("Name") %></a></li>
                            </ItemTemplate>
                        </asp:Repeater>
                    </ul>
                </div>
            </div>
            <div>
                <asp:PlaceHolder ID="MsgBodyHolder" runat="server" EnableViewState="false"></asp:PlaceHolder>
            </div>
        </div>

        <asp:ObjectDataSource ID="FolderDataSource" runat="server" TypeName="MailSigDataSource" SelectMethod="GetSignatures" >
        </asp:ObjectDataSource>

        <div style="display:">            
            <asp:LinkButton ID="SendButton" runat="server" OnClick="SendButton_Click" /> 
            <asp:LinkButton ID="SaveButton" runat="server" OnClick="SaveButton_Click" /> 
            <asp:LinkButton ID="AddAttachFileButton" runat="server" OnClick="AddAttachFileButton_Click" /> 
            <asp:LinkButton ID="RemoveAttachFileButton" runat="server" OnClick="RemoveAttachFileButton_Click" />
            <asp:HiddenField ID="RemoveAttachFileIndex" runat="server" />
            <!-- Recipients HiddenField -->
            <asp:HiddenField ID="ToRcptsHidden" runat="server" /> 
            <asp:HiddenField ID="CcRcptsHidden" runat="server" />
            <asp:HiddenField ID="BccRcptsHidden" runat="server" /> 
        </div>
    </form>

    <div class="modal fade" id="rcptSelectModal" role="dialog">
        <div class="modal-dialog">    
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header" style="">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4><asp:Localize ID="Localize12" runat="server" meta:resourcekey="L12">수신자 선택</asp:Localize></h4>
                </div>
                <div class="modal-body">
                    <form role="form">
                        <div class="form-group">
                            <label for="email"><asp:Localize ID="Localize13" runat="server" meta:resourcekey="L13">메일 주소</asp:Localize>:</label>
                            <input type="text" runat="server" id="mailAddrText" name="mailAddrText" class="form-control" placeholder="<%$ Resources:, Ph02%>" autocomplete="off" onkeydown="return IgnoreEnterKey(event);" />
                        </div>
                        <div class="form-group">
                            <button type="button" id="addContactButton" class="btn btn-default" onclick="OpenContact();"><asp:Localize ID="Localize14" runat="server" meta:resourcekey="L14">주소록</asp:Localize></button>
                        </div>
                        <div class="form-group">
                            <button type="button" id="addOrgzButton" class="btn btn-default" onclick="OpenOrgz();"><asp:Localize ID="Localize15" runat="server" meta:resourcekey="L15">조직도</asp:Localize></button>
                        </div>
                        <div>&nbsp;</div>
                        <button type="button" class="btn btn-success btn-block" id="msgflagOKButton" onclick="AddMailAddress()"><asp:Localize ID="Localize16" runat="server" meta:resourcekey="L16">확인</asp:Localize></button>
                    </form>
                </div>                    
            </div>
        </div>
    </div>
</body>
</html>
