<%@ Page Title="" Language="C#" MasterPageFile="~/SystemSettings/SysSettingMasterPage.master" AutoEventWireup="true" CodeFile="ManageRegions.aspx.cs" Inherits="ManageRegions" %>


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <style type="text/css">
        ::-ms-clear, ::-ms-reveal {
            display: none;
        }

        .selectinput {
            width: 150px;
            margin-right: 10px;
        }

        .dialog-content table {
            border-collapse: collapse;
            width: 100%;
        }

            .dialog-content table td.label {
                width: 120px;
                text-align: right;
                padding-right: 10px;
                line-height: 30px;
                height: 24px;
                vertical-align: top;
            }

            .dialog-content table td input,
            .dialog-content table td textarea {
                border: 1px solid #a9a9a9;
                width: 200px;
                height: 18px;
                padding: 1px;
            }

                .dialog-content table td input[type="checkbox"] {
                    border: none;
                }

            .dialog-content table td textarea {
                height: 100px;
                /*max-width: 200px;*/
            }

        #dialogdatatb td {
            padding-top: 30px;
        }

        .a {
            text-decoration: none;
            color: #2140fb;
        }
    </style>

    <link href="<%=GetFileUrlWithVersion("../css/jquery.datetimepicker.css")%>" rel="stylesheet" />
    <script src="<%=GetFileUrlWithVersion("../js/jquery.datetimepicker.full.js")%>"></script>
    <script src="../Maintenance/js/inputdatactr.js"></script>

    <script type="text/javascript">        

        function regionrequest(method, param, callback, error) {
            _network.request("SystemSettings/ManageRegions.aspx", -1, method, param, callback, error || function (e) {
                showmaskbg(false, true);
                showAlert(GetTextByKey('P_SET_QUERY', 'An unknown error occurred.  Please refresh page.'), GetTextByKey('P_SET_QUERY', 'Query'));
            });
        }

        function OnAdd() {
            regionid = undefined;

            $('#dialog_name').val('');
            $('#dialog_startdate').val('');
            $('#dialog_projectenddate').val('');
            $('#dialog_enddate').val('');
            $('#dialog_notes').val('');
            $('#dialog_region .dialog-title span.title').text(GetTextByKey("P_SET_ADDREGION", "Add Region"));

            showmaskbg(true);
            $('#dialog_region')
                .css({
                    'top': (document.documentElement.clientHeight - $('#dialog_region').height()) / 3,
                    'left': (document.documentElement.clientWidth - $('#dialog_region').width()) / 2
                }).showDialogfixed();
            $('#dialog_name').focus();
        }

        var regionid;
        function OnEdit() {
            var index = grid_dt.selectedIndex;
            if (index < 0) {
                showAlert(GetTextByKey("P_SET_PLEASESELECTREGION", "Please select Region."), GetTextByKey("P_SET_EDITREGION", "Edit Region")); return;
            }
            var region = grid_dt.source[index].Values;
            if (!region) {
                regionid = undefined;
                return;
            }

            regionid = region.Id;
            $('#dialog_name').val(region.Name);
            $('#dialog_startdate').val(region.StartDate.DisplayValue);
            $('#dialog_projectenddate').val(region.ProjectedEndDate.DisplayValue);
            $('#dialog_enddate').val(region.EndDate.DisplayValue);
            $('#dialog_notes').val(region.Notes);
            $('#dialog_region .dialog-title span.title').text(GetTextByKey("P_SET_EDITREGION", "Edit Region"));
            showmaskbg(true);
            $('#dialog_region')
                .css({
                    'top': (document.documentElement.clientHeight - $('#dialog_region').height()) / 3,
                    'left': (document.documentElement.clientWidth - $('#dialog_region').width()) / 2
                }).showDialogfixed();
            $('#dialog_name').focus();
        }

        function OnDblClick(e) {
            OnEdit();
        }

        function OnDelete(region) {
            if (!region) {
                return;
            }
            var alerttitle = GetTextByKey("P_SET_DELETEREGION", "Delete Region");
            showConfirm(GetTextByKey("P_SET_DOYOUWANTTODELETETHEREGION", 'Do you want to delete the region?'), alerttitle, function () {
                regionrequest("DeleteRegion", region.Id, function (data) {
                    if (typeof (data) === "string") {
                        showAlert(data, alerttitle);
                    }
                    else
                        OnRefresh();
                }, function (err) {
                    showAlert(GetTextByKey("P_SET_FAILEDTODELETETHISREGION", 'Failed to delete this Region.'), alerttitle);
                });
            });
        }

        function OnRefresh() {
            showloading(true);

            regionrequest("GetRegions", "", function (data) {
                showloading(false);
                if (typeof (data) === "string") {
                    showAlert(data, GetTextByKey("P_SET_ERROR", 'Error'));
                    return;
                }

                if (data)
                    showRegions(data);
            }, function (err) {
                showloading(false);
            });
        }

        function showRegions(data) {
            var rows = [];
            for (var i = 0; i < data.length; i++) {
                var r = data[i];
                for (var j in r) {
                    if (j === "StartDate") {
                        r[j] = { DisplayValue: r["StartDateStr"], Value: r[j] };
                    }
                    else if (j === "ProjectedEndDate") {
                        r[j] = { DisplayValue: r["ProjectedEndDateStr"], Value: r[j] };
                    }
                    else if (j === "EndDate") {
                        r[j] = { DisplayValue: r["EndDateStr"], Value: r[j] };
                    }
                    else if (j === "IsActive") {
                        r[j] = { DisplayValue: r["IsActive"] ? "Yes" : "No", Value: r[j] };
                    }
                }
                var fr = { Values: r };
                rows.push(fr);
            }
            grid_dt.setData(rows);
        }


        var grid_dt;
        function InitGridData() {
            grid_dt = new GridView('#regionlist');
            grid_dt.lang = {
                all: GetTextByKey("P_GRID_ALL", "(All)"),
                ok: GetTextByKey("P_GRID_OK", "OK"),
                reset: GetTextByKey("P_GRID_RESET", "Reset")
            };
            var list_columns = [
                { name: 'Name', caption: GetTextByKey("P_SET_REGIONNAME", "Region Name"), valueIndex: 'Name', css: { 'width': 200, 'text-align': 'left' } },
                { name: 'StartDate', caption: GetTextByKey("P_SET_STARTDATE", "Start Date"), valueIndex: 'StartDate', css: { 'width': 120, 'text-align': 'left' } },
                { name: 'ProjectedEndDate', caption: GetTextByKey("P_SET_PROJECTEDENDDATE", "Projected End Date"), valueIndex: 'ProjectedEndDate', css: { 'width': 130, 'text-align': 'left' } },
                { name: 'EndDate', caption: GetTextByKey("P_SET_ENDDATE", "End Date"), valueIndex: 'EndDate', css: { 'width': 120, 'text-align': 'left' } },
                //{ name: 'IsActive', caption: GetTextByKey("P_SET_ACTIVE", "Active"), valueIndex: 'IsActive', css: { 'width': 80, 'text-align': 'left' } },
                { name: 'Notes', caption: GetTextByKey("P_SET_NOTES", "Notes"), valueIndex: 'Notes', css: { 'width': 280, 'text-align': 'left' } },
                { name: 'Edit', caption: "", css: { 'width': 30, 'text-align': 'center' } },
                { name: 'Delete', caption: "", css: { 'width': 30, 'text-align': 'center' } }
            ];
            var columns = [];
            // head
            for (var hd in list_columns) {
                var col = {};
                col.name = list_columns[hd].name;
                col.caption = list_columns[hd].caption;
                col.visible = true;
                col.sortable = true;
                col.width = list_columns[hd].css.width;
                col.align = list_columns[hd].css["text-align"]
                col.key = list_columns[hd].valueIndex;
                col.allowFilter = list_columns[hd].allowFilter;
                col.type = list_columns[hd].type;

                if (col.name === "Edit") {
                    col.isurl = true;
                    col.text = "\uf044";
                    col.sortable = false;
                    col.events = {
                        onclick: function () {
                            OnEdit();
                        }
                    };
                    col.classFilter = function (e) {
                        return "icon-col";
                    }
                    col.attrs = { 'title': GetTextByKey("P_SET_EDIT", 'Edit') };
                }
                else if (col.name === "Delete") {
                    col.isurl = true;
                    col.text = "\uf00d";
                    col.sortable = false;
                    col.events = {
                        onclick: function () {
                            OnDelete(this);
                        }
                    };
                    col.classFilter = function (e) {
                        return "icon-col";
                    };
                    col.attrs = { 'title': GetTextByKey("P_SET_DELETE", 'Delete') };
                }
                columns.push(col);
            }
            grid_dt.canMultiSelect = false;
            grid_dt.columns = columns;
            grid_dt.init();
            grid_dt.rowdblclick = OnEdit;
        }

        function OnDialogOK() {
            var item = {
                'Name': $.trim($('#dialog_name').val()),
                'StartDate': $.trim($('#dialog_startdate').val()),
                'ProjectedEndDate': $.trim($('#dialog_projectenddate').val()),
                'EndDate': $.trim($('#dialog_enddate').val()),
                'Notes': $.trim($('#dialog_notes').val())
            };
            var alerttitle;
            if (regionid) {
                item.Id = regionid;
                alerttitle = GetTextByKey("P_SET_EDITREGION", "Edit Region");
            } else {
                item.Id = -1;
                alerttitle = GetTextByKey("P_SET_ADDREGION", "Add Region");
            }

            if (!item.Name || item.Name.length == 0) {
                showAlert(GetTextByKey("P_SET_REGIONNAMECANNOTBEEMPTY", 'Region name cannot be empty.'), alerttitle);
                $('#dialog_name').focus();
                return;
            }

            if (item.StartDate.length > 0 && !checkDate(item.StartDate)) {
                showAlert(GetTextByKey("P_SET_STARTDATEFORMATERROR", "Start Date format error."), alerttitle);
                return;
            }

            if (item.ProjectedEndDate.length > 0 && !checkDate(item.ProjectedEndDate)) {
                showAlert(GetTextByKey("P_SET_PROJECTEDENDDATEFORMATERROR", "Projected End Date format error."), alerttitle);
                return;
            }

            if (item.EndDate.length > 0 && !checkDate(item.EndDate)) {
                showAlert(GetTextByKey("P_SET_ENDDATEFORMATERROR", "End Date format error."), alerttitle);
                return;
            }

            if (item.StartDate.length > 0) {
                var sdate = item.StartDate;
                var stdt = new Date(sdate.replace("-", "/"));
                if (item.ProjectedEndDate.length > 0) {
                    var edate = item.ProjectedEndDate;
                    var etdt = new Date(edate.replace("-", "/"));
                    if (stdt > etdt) {
                        showAlert(GetTextByKey("P_SET_PROJECTEDENDDATEFORMATERROR1", "Projected End Date must be later than Start Date."), alerttitle);
                        return;
                    }
                }
                if (item.EndDate.length > 0) {
                    var edate = item.EndDate;
                    var etdt = new Date(edate.replace("-", "/"));
                    if (stdt > etdt) {
                        showAlert(GetTextByKey("P_SET_ENDDATEFORMATERROR1", "End Date must be later than Start Date."), alerttitle);
                        return;
                    }
                }
            }

            regionrequest("SaveRegion", htmlencode(JSON.stringify(item)), function (data) {
                if (typeof (data) === "string") {
                    showAlert(data, GetTextByKey("P_SET_ERROR", 'Error'));
                    return;
                }

                showmaskbg(false);
                $('#dialog_region').hideDialog();
                OnRefresh();
            }, function (err) {
                showmaskbg(false);
            });
        }

        $(function () {
            setPageTitle(GetTextByKey("P_SET_MANAGEREGIONS", 'Manage Regions'), true);
            InitGridData();

            OnRefresh();

            $('#dialog_startdate').datetimepicker({
                timepicker: false,
                format: 'm/d/Y',
                enterLikeTab: false,
                scrollInput: false,
                onSelectDate: function (v, inp) {
                    var date = new DateFormatter().formatDate(v, 'm/d/Y 00:00:00');
                    inp.parent().data('val', [date]);
                }
            });

            $('#dialog_projectenddate').datetimepicker({
                timepicker: false,
                format: 'm/d/Y',
                enterLikeTab: false,
                scrollInput: false,
                onSelectDate: function (v, inp) {
                    var date = new DateFormatter().formatDate(v, 'm/d/Y 00:00:00');
                    inp.parent().data('val', [date]);
                }
            });

            $('#dialog_enddate').datetimepicker({
                timepicker: false,
                format: 'm/d/Y',
                enterLikeTab: false,
                scrollInput: false,
                onSelectDate: function (v, inp) {
                    var date = new DateFormatter().formatDate(v, 'm/d/Y 00:00:00');
                    inp.parent().data('val', [date]);
                }
            });

            $('#dialog_region').dialog(function () {
                showmaskbg(false);
            });

            $(window).resize(function () {
                $("#regionlist").css("height", $(window).height() - $("#regionlist").offset().top - 4);
            }).resize();

        });
    </script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div id="recordcontent" style="padding: 0px; margin: 0px;">
        <div class="page_title" data-lgid="P_SET_MANAGEREGIONS">Manage Regions</div>
        <div class="function_title">
            <span class="sbutton iconadd" onclick="OnAdd();" data-lgid="P_SET_ADD">Add</span>
            <span class="sbutton iconrefresh" onclick="OnRefresh();" data-lgid="P_SET_REFRESH">Refresh</span>
        </div>
        <div class="clear"></div>
        <div id="regionlist">
            <data-grid ref="grid" v-bind:columns="columns" v-bind:source="source" v-bind:allow-editing="true" v-on:rowdblclick="rowdblclick"
                v-bind:allow-auto-new-row="false" v-bind:total-row="totalRow" body-class="autoHeightBody">
            </data-grid>
        </div>
    </div>
    <div id="mask_bg" style="display: none;">
        <div class="loading c-spin"></div>
    </div>

    <div class="dialog" id="dialog_region" style="display: none; width: 500px;">
        <div class="dialog-title"><span class="title" data-lgid="P_SET_ADDREGION">Add Region</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <table>
                <tr>
                    <td class="label" data-lgid="P_SET_REGIONNAME_COLON">Region Name:</td>
                    <td>
                        <input type="text" id="dialog_name" maxlength="200" tabindex="1" style="width: 320px;" autocomplete="off" /></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_SET_STARTDATE_COLON">Start Date:</td>
                    <td>
                        <input type="text" id="dialog_startdate" maxlength="20" tabindex="1" style="width: 320px;" autocomplete="off" /></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_SET_PROJECTEDENDDATE_COLON">Project End Date:</td>
                    <td>
                        <input type="text" id="dialog_projectenddate" maxlength="20" tabindex="1" style="width: 320px;" autocomplete="off" /></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_SET_ENDDATE_COLON">End Date:</td>
                    <td>
                        <input type="text" id="dialog_enddate" maxlength="20" tabindex="1" style="width: 320px;" autocomplete="off" /></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_SET_NOTES_COLON">Notes:</td>
                    <td>
                        <textarea id="dialog_notes" class="inputbox" maxlength="1000" tabindex="1" style="width: 320px;"></textarea></td>
                </tr>
            </table>
        </div>
        <div class="dialog-func">
            <input type="button" value="Cancel" data-lgid="P_SET_CANCEL" class="dialog-close" tabindex="8" />
            <input type="button" onclick="OnDialogOK();" value="OK" data-lgid="P_SET_OK" tabindex="7" />
            <div class="clear"></div>
        </div>
    </div>
</asp:Content>