<%@ Page Language="C#" AutoEventWireup="true" CodeFile="List.aspx.cs" Inherits="Mail_List" meta:resourcekey="Page" %>
<%@ Register src="../Common/TopNavbar.ascx" tagname="TopNavbar" tagprefix="tabs" %>

<!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/bootstrap/css/animate.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/bootstrap-notify.min.js"></script>
</head>
<body>
    <style>
        .table-fixed
        {
            table-layout:fixed;
        }
        .col-cbox
        {
            width:32px;
        }
        .mailfrom-wrap
        {
            word-break: break-all;
            white-space: normal;
        }
        .col-subject
        {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
        .col-absbody
        {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;            
            opacity: 0.6;
            font-size: small;
        }
        /* 요약 본문을 여러 줄로 표시할 때
        .col-absbody
        {
            overflow: hidden;
            white-space: wrap;
            text-overflow: clip;            
            opacity: 0.6;
            font-size: small;
        }*/
        input[type="checkbox"] {
            width: 20px;
            height: 20px;
        }
    </style>
    <script type="text/javascript">
        if (!!window.performance && window.performance.navigation.type == 2) {
            window.location.reload();
        }
	</script>
    <script type="text/javascript">
        $(document).ready(function () {
            // 플래그 클릭 시 플래그 선택 모달 대화상자를 띄운다.
            $("[data-flag-id]").click(function (event) {
                var flagValue = $(this).data("flag-value");
                $("input[name=msgflag][value=" + flagValue + "]").prop("checked", true);
                $("#msgflagId").val($(this).data("flag-id"));
                $("#msgFlagModal").modal();
                event.stopPropagation();
            });

            // 플래그 선택 모달 대화상자에서 확인 버튼 클릭
            $("#msgflagOKButton").click(function () {
                // 모달 대화상자를 닫는다.
                $("#msgFlagModal").modal("hide");
                var flagMsgId = $("#msgflagId").val();
                var flagValue = $("input[name=msgflag]:checked").val();
                // 플래그 변경 ajax 호출
                $.ajax({
                    type: "POST",
                    url: "CallAjax.aspx/SetMsgFlag",
                    data: JSON.stringify({
                        msgId: flagMsgId,
                        flagValue: flagValue
                    }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        // 플래그 이미지 업데이트
                        var flagTag = $("[data-flag-id=" + flagMsgId + "]");
                        flagTag.data("flag-value", flagValue);
                        if (flagValue >= 0 && flagValue <= 6) {
                            var flagColors = ["#CECEC6", "#D3401B", "#638CD6", "#F4DE84", "#94C673", "#F78431", "#B563D6"];
                            flagTag.removeClass("fa-flag fa-check");
                            flagTag.addClass("fa-solid fa-flag mc-likeLink");
                            flagTag.css("color", flagColors[flagValue]);
                        } else {
                            flagTag.removeClass("fa-flag fa-check");
                            flagTag.addClass("fa-solid fa-check mc-likeLink");
                            flagTag.css("color", "#524A52");
                        }
                    },
                    failure: function (response) {
                        Dialog.alert('<asp:Literal runat="server" Text="<%$ Resources:, Msg01%>" />'); // 플래그 변경 작업을 실패했습니다.
                    }
                });
            });

            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%>);
        });

        function SelectAllCheckboxes() {
            var table = $get("<%=MsgGridView.ClientID %>");
            var cell = table.rows[0].cells[0];
            var status = false;
            var index = -1;

            for (var i = 0; i < cell.childNodes.length; i++) {
                var el = cell.childNodes[i];
                if (el.nodeName == 'INPUT' && el.type == 'checkbox') {
                    status = el.checked;
                    index = i;
                }
            }

            for (i = 1; i < table.rows.length; i++) {
                var cell = table.rows[i].cells[0];
                el = cell.childNodes[index];
                if (el != undefined) el.checked = status;
            }

            return false;
        }

        function GetSelectedCount() {
            var count = 0;
            var table = $get("<%=MsgGridView.ClientID %>");
            for (var i = 0; i < table.rows.length; i++) {
                var cell = table.rows[i].cells[0];
                for (var j = 0; j < cell.childNodes.length; j++) {
                    var el = cell.childNodes[j];
                    if (el.nodeName == 'INPUT' && el.type == 'checkbox' && el.checked) {
                        count++;
                    }
                }
            }
            return count;
        }

        function GetSelectedItems() {
            var items = [];
            var table = $get("<%=MsgGridView.ClientID %>");
            for (var i = 0; i < table.rows.length; i++) {
                var cell = table.rows[i].cells[0];
                var checked = false;
                for (var j = 0; j < cell.childNodes.length; j++) {
                    var el = cell.childNodes[j];
                    if (el.nodeName == 'INPUT' && el.type == 'checkbox' && el.checked) {
                        checked = true;    
                    } else if (el.nodeName == 'INPUT' && el.type == 'hidden' && checked) {
                        items.push(el.value);
                    }
                }
            }
            return items;
        }

        function ConfirmDelete() {
            var items = GetSelectedItems();
            if (items.length > 0) {
                var folderType = "<%=_folderType%>";
                $.ajax({
                    type: "POST",
                    url: "CallAjax.aspx/DeleteMessages",
                    data: JSON.stringify({
                        folderType: folderType,
                        msgIDs: items                        
                    }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var msg = (folderType == "mcTrash" || folderType == "mcSpam") ?
                            '<asp:Literal runat="server" Text="<%$ Resources:Mail, Msg01%>" />' : '<asp:Literal runat="server" Text="<%$ Resources:Mail, Msg02%>" />';
                        mc7_notify(msg, "success");
                        window.setTimeout(function () {
                            __doPostBack("RefreshButton", "");
                        }, 2000);
                    },
                    failure: function (response) {
                    }
                });
            } else {
                Dialog.alert('<asp:Literal runat="server" Text="<%$ Resources:, Msg03%>" />'); // 삭제할 메일을 선택하십시오.
            }
        }

        function ConfirmMove() {
            var count = GetSelectedCount();
            if (count <= 0) {
                Dialog.alert('<asp:Literal runat="server" Text="<%$ Resources:, Msg04%>" />'); // 이동할 메일을 선택하십시오.
            } else {
                __doPostBack("MoveToButton", "");
            }
        }

        function ViewMessage(msgId, folderId, pageIndex, searchCategoty, searchKeyword) {
            location.href = "View.aspx?msg=" + msgId + "&folder=" + folderId + "&page=" + pageIndex + "&searchCategoty=" + searchCategoty + "&searchKeyword=" + encodeURIComponent(searchKeyword);
        }

        function EditMessage(msgId, folderId, pageIndex, searchCategoty, searchKeyword) {
            location.href = "NewTM.aspx?action=edit&msg=" + msgId + "&folder=" + folderId + "&page=" + pageIndex;
        }

        function Refresh() {
            location.href = "List.aspx?folder=<%=_folderId.ToString()%>&init=true";
        }

        function OpenFolders() {
            location.href = "Folders2.aspx?select=<%=_folderId.ToString()%>";
        }

        function WriteNewMail() {
            location.href = "NewTM.aspx?action=new&folder=<%=_folderId.ToString()%>";
        }

        function SearchOnEnter(event) {
            if (event.keyCode == 13) {
                __doPostBack("SearchButton", "");
                return false;
            }
            return true;
        }
    </script> 
        
    <form id="form1" runat="server">
        <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/notify.js" />
                </Scripts>
            </CompositeScript>
        </asp:ScriptManager>

        <tabs:TopNavbar ID="TopMenu1" runat="server" />

        <div class="container-fluid topNavbarRegion">
            <div class="row" id="toolBar" data-spy="affix">
                <div class="col-xs-12" style="padding-top:2px;padding-bottom:2px;">
                    <button type="button" id="refreshToolButton" class="btn btn-primary" onclick="Refresh()"><span class="fa-solid fa-rotate-right"></span></button>
                    <button type="button" id="folderToolButton" class="btn btn-primary" onclick="OpenFolders()"><span class="fa-solid fa-folder-open"></span></button>
                    <button type="button" id="writeToolButton" class="btn btn-primary" onclick="WriteNewMail()"><span class="fa-solid fa-pen"></span></button>
                    <button type="button" id="deleteToolButton" class="btn btn-primary" onclick="ConfirmDelete()"><span class="fa-solid fa-trash-can"></span></button>
                    <button type="button" id="moveToolButton" class="btn btn-primary" onclick="ConfirmMove()"><span class="fa-regular fa-copy"></span></button>
                    <button type="button" id="searchCollapseButton" class="btn btn-primary" data-toggle="collapse" data-target="#searchPanel"><span class="fa-solid fa-magnifying-glass"></span></button>
                </div>
            </div>
        </div>
       
        <div class="container-fluid" style="padding-top:40px">
            <div id="searchPanel" runat="server" class="collapse">
                <div class="row">
                    <div class="col-xs-9">
                        <asp:DropDownList ID="CategoryList" runat="server" CssClass="form-control" meta:resourcekey="CategoryList">
                            <asp:ListItem Text="제목" Value="subject" Selected="True" meta:resourcekey="CategoryListItem1"></asp:ListItem>
                            <asp:ListItem Text="본문" Value="body" meta:resourcekey="CategoryListItem2"></asp:ListItem>
                            <asp:ListItem Text="보낸사람" Value="sender" meta:resourcekey="CategoryListItem3"></asp:ListItem>
                            <asp:ListItem Text="받는사람" Value="receiver" meta:resourcekey="CategoryListItem4"></asp:ListItem>
                            <asp:ListItem Text="전체" Value="all" meta:resourcekey="CategoryListItem5"></asp:ListItem>
                        </asp:DropDownList>
                    </div>
                    <div class="col-xs-3">
                        <button type="button" id="searchButton" class="btn btn-default" onclick="__doPostBack('SearchButton', '')"><span class="fa-solid fa-magnifying-glass"></span></button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-9">
                        <asp:TextBox ID="KeywordTextBox" runat="server" CssClass="form-control" AutoPostBack="false" onkeydown="return SearchOnEnter(event);" />
                    </div>
                    <div class="col-xs-3">
                        <button type="button" id="searchCancelButton" class="btn btn-default" onclick="__doPostBack('SearchCancelButton', '')"><span class="fa-solid fa-xmark"></span></button>
                    </div>
                </div>
            </div>

            <asp:GridView ID="MsgGridView" runat="server" Width="100%" CssClass="table table-hover table-fixed" AutoGenerateColumns="false" 
                AllowPaging="true" PageSize="20" AllowSorting="true" GridLines="None" ShowHeaderWhenEmpty="true" ShowHeader="true" 
                DataSourceID="MsgDataSource" EnableViewState="true" DataKeyNames="ID"
                OnPreRender="MsgGridView_PreRender">
                <EmptyDataTemplate>
                    <div>
                        <asp:Localize ID="Localize1" runat="server" meta:resourcekey="Localize1">메일이 존재하지 않습니다.</asp:Localize>
                    </div>
                </EmptyDataTemplate> 
                <Columns>
                    <asp:TemplateField>
                        <HeaderStyle CssClass="col-cbox text-left" />                               
                        <ItemStyle CssClass="text-left" />
                        <HeaderTemplate>
                            <input id="chkAll" onclick="SelectAllCheckboxes();" runat="server" type="checkbox" />
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:CheckBox ID="SelectCheckBox" runat="server" />
                            <asp:HiddenField ID="SelectItemId" runat="server" Value='<%#Eval("ID")%>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <HeaderStyle Font-Size="Larger" />
                        <ItemTemplate>
                            <div class="row" onclick="<%# GetClickEventFunction((Guid)Eval("ID"))%>">
                                <div class="col-xs-12">
                                    <div class="row">
                                        <div class="col-xs-9 mailfrom-wrap">
                                            <%# GetActionFlagImage((bool)Eval("New"), (int)Eval("ActionFlag"))%>  
                                            <%# GetFromOrTo((string)Eval("FromName"), (string)Eval("FromAddress"), (string)Eval("SentTo"), (bool)Eval("New"))%>                               
                                        </div>
                                        <div class="col-xs-3 text-right">
                                            <small><%# GetFormattedRecvTime((DateTime)Eval("RecvTime"))%></small>
                                        </div> 
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-10 col-subject">
                                            <%# GetSubject((string)Eval("Subject"), (bool)Eval("New"), (string)Eval("FolderName"), (int)Eval("ActionFlag"))%>                                    
                                        </div> 
                                        <div class="col-xs-2 text-right">
                                            <%# GetAttachmentImage((int)Eval("AttachCount"))%> 
                                            <%# GetFlag((int)Eval("Flag"), (Guid)Eval("ID"))%>
                                        </div> 
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-12 col-absbody">
                                            <%#: Eval("Summary") %>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns> 
                <PagerSettings PageButtonCount="5" Mode="NumericFirstLast" />
                <PagerStyle CssClass="mc-gridpager"/>
            </asp:GridView>
        </div>

        <div style="display:none">
            <asp:LinkButton ID="RefreshButton" runat="server" OnClick="RefreshButton_Click" Text="" />
            <asp:LinkButton ID="DeleteButton" runat="server" OnClick="DeleteButton_Click" Text="" />
            <asp:LinkButton ID="SearchButton" runat="server" OnClick="SearchButton_Click" Text="" />
            <asp:LinkButton ID="SearchCancelButton" runat="server" OnClick="SearchCancelButton_Click" Text="" />
            <asp:LinkButton ID="MoveToButton" runat="server" OnClick="MoveToButton_Click" Text="" />            
        </div>

        <asp:ObjectDataSource ID="MsgDataSource" runat="server" TypeName="MsgDataSource"
            SelectMethod="GetMessages" SelectCountMethod="TotalNumberOfProducts" SortParameterName="sortExpression"
            EnablePaging="true" onselected="MsgDataSource_Selected">
            <SelectParameters>
                <asp:QueryStringParameter Name="folder" Type="String" QueryStringField="folder" />
                <asp:Parameter Name="isNew" Type="Boolean" DefaultValue="false" ConvertEmptyStringToNull="true" />
                <asp:Parameter Name="storePN" Type="Boolean" DefaultValue="true" ConvertEmptyStringToNull="true" />
            </SelectParameters>
        </asp:ObjectDataSource>
                
        <asp:ObjectDataSource ID="SearchedMsgDataSource" runat="server" TypeName="SearchedMsgDataSource"
            SelectMethod="GetMessages" SelectCountMethod="TotalNumberOfProducts" SortParameterName="sortExpression"
            EnablePaging="true" onselected="SearchedMsgDataSource_Selected">
            <SelectParameters>
                <asp:QueryStringParameter Name="folder" Type="String" QueryStringField="folder" />
                <asp:Parameter Name="keyword" Type="String" ConvertEmptyStringToNull="true" />
                <asp:Parameter Name="field" Type="String" ConvertEmptyStringToNull="true" />
                <asp:Parameter Name="isNew" Type="Boolean" DefaultValue="false" ConvertEmptyStringToNull="true" />
                <asp:Parameter Name="storePN" Type="Boolean" DefaultValue="true" ConvertEmptyStringToNull="true" />
            </SelectParameters>
        </asp:ObjectDataSource>
    </form>

    <div class="modal fade" id="msgFlagModal" 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="Localize2" runat="server" meta:resourcekey="Localize2">플래그 지정</asp:Localize></h4>
                </div>
                <div class="modal-body">
                    <form role="form">
                        <div class="radio">
                            <label><input type="radio" name="msgflag" value="0"><span class='fa-solid fa-flag' style="color:#CECEC6"></span> <asp:Literal ID="Literal1" runat="server" Text="<%$ Resources:Mail, Flag8%>" /></label>
                        </div>
                        <div class="radio">
                            <label><input type="radio" name="msgflag" value="1"><span class='fa-solid fa-flag' style="color:#D3401B"></span> <asp:Literal ID="Literal2" runat="server" Text="<%$ Resources:Mail, Flag1%>" /></label>
                        </div>
                        <div class="radio">
                            <label><input type="radio" name="msgflag" value="2"><span class='fa-solid fa-flag' style="color:#638CD6"></span> <asp:Literal ID="Literal3" runat="server" Text="<%$ Resources:Mail, Flag2%>" /></label>
                        </div>
                        <div class="radio">
                            <label><input type="radio" name="msgflag" value="3"><span class='fa-solid fa-flag' style="color:#F4DE84"></span> <asp:Literal ID="Literal4" runat="server" Text="<%$ Resources:Mail, Flag3%>" /></label>
                        </div>
                        <div class="radio">
                            <label><input type="radio" name="msgflag" value="4"><span class='fa-solid fa-flag' style="color:#94C673"></span> <asp:Literal ID="Literal5" runat="server" Text="<%$ Resources:Mail, Flag4%>" /></label>
                        </div>
                        <div class="radio">
                            <label><input type="radio" name="msgflag" value="5"><span class='fa-solid fa-flag' style="color:#F78431"></span> <asp:Literal ID="Literal6" runat="server" Text="<%$ Resources:Mail, Flag5%>" /></label>
                        </div>
                        <div class="radio">
                            <label><input type="radio" name="msgflag" value="6"><span class='fa-solid fa-flag' style="color:#B563D6"></span> <asp:Literal ID="Literal7" runat="server" Text="<%$ Resources:Mail, Flag6%>" /></label>
                        </div>
                        <div class="radio">
                            <label><input type="radio" name="msgflag" value="99"><span class='fa-solid fa-check' style="color:#524A52"></span> <asp:Literal ID="Literal8" runat="server" Text="<%$ Resources:Mail, Flag7%>" /></label>
                        </div>
                        <button type="button" class="btn btn-success btn-block" id="msgflagOKButton"><asp:Localize ID="Localize3" runat="server" meta:resourcekey="Localize3">확인</asp:Localize></button>
                        <input type="hidden" id="msgflagId" />
                    </form>
                </div>                    
            </div>
        </div>
    </div>
    
</body>
</html>
