<%@ Page Title="" Language="C#" MasterPageFile="~/Maintenance/MaintenanceBase.master" AutoEventWireup="true" CodeFile="AddCustomerRecord.aspx.cs" Inherits="AddCustomerRecord" %>


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <link href="<%=Common.GenerateUrl("../css/tabcontrol.css") %>" rel="stylesheet" />
    <style type="text/css">
        ::-ms-clear, ::-ms-reveal {
            display: none;
        }

        .tab-header {
            float: left;
            padding: 2px 6px;
            cursor: pointer;
            border: 1px solid #fff;
            border-bottom: none;
        }

            .tab-header:hover {
                background: #eee;
            }

            .tab-header.selected {
                border-color: #d8d8d8;
                cursor: default;
            }

                .tab-header.selected:hover {
                    background: #fff;
                }

        .label { /*cover tab.css*/
            display: table-cell;
        }

        .login_lable {
            height: 24px;
            line-height: 24px;
            vertical-align: top;
        }

        .sbutton {
            font-weight: 200;
        }

        .msgdiv {
            border: solid 1px lightgray;
            margin-top: 5px;
            padding-left: 5px;
            padding-right: 10px;
            padding-top: 3px;
            padding-bottom: 3px;
            line-height: 24px;
            white-space: normal;
            word-break: break-word;
            overflow: hidden;
        }

        .msgtime {
            text-align: right;
        }

        .dialog, .data-column-header-filter-panel, .data-column-header-filter-bg {
            z-index: 700;
        }

        .subtitle {
            margin: 20px 40px 5px 0px;
            font-size: 16px;
            color: gray;
        }

            .subtitle span {
                margin-left: 10px;
            }

            .subtitle hr {
                background-color: #d8d8d8;
                border: none;
                height: 1px;
            }

        .dialog-content table td.label {
            width: 120px;
        }

        .dialog-content table td input[type="text"], .dialog-content table td textarea {
            width: 320px;
        }
    </style>

    <script src="<%=GetFileUrlWithVersion("../js/controls.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../js/utility.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../js/language.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../js/modulelang.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../js/assetselector.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("js/addcustomerrecord.js")%>" type="text/javascript"></script>
    <script type="text/javascript">
        var custid = "";
        var loadingCount = 0;
        var assetid = 0;
        var CRReadOnly = <%=CRReadOnly ?"true":"false"%>;
        var AllowCanOpenWO = <%=AllowCanOpenWO ?"true":"false"%>;

        function crrequest(method, param, callback, error) {
            _network.request("Maintenance/AddCustomerRecord.aspx", -1, method, param, callback, error || function (e) {
                console.log(e);
                showmaskbg(false, true);
                showAlert(GetTextByKey('P_UM_PAGEERROR', 'An unknown error occurred.  Please refresh page.'), GetTextByKey('P_UM_QUERY', 'Query'));
            });
        }

        function showcontatcmask(flag) {
            if (flag) {
                $('#contatcmask').fadeIn(100);
            } else {
                $('#contatcmask').fadeOut(100);
            }
        }

        function OnAdd() {
            $('#dialog_name').val("");
            $('#dialog_code').val("");
            $('#dialog_custaddress').val("");
            $('#dialog_notes').val("");
            $('#dialog_salespersoncode').data('spiid', '');
            $('#dialog_salespersoncode').val('');
            $('#dialog_salespersonname').val('');
            showContacts([]);
            showFollowers([]);

            setTimeout(function () {
                grid_dt && grid_dt.resize();
                grid_dtfollower && grid_dtfollower.resize();
            });
        }

        var customer;
        function getCustomerRecordInfo() {
            showLoading();
            crrequest("GetCustomerRecordInfo", custid, function (data) {
                hideLoading();
                if (typeof (data) === "string") {
                    showAlert(data, GetTextByKey("P_UM_ERROR", 'Error'));
                    return;
                }
                customer = data;

                $('#dialog_name').val(customer.Name);
                $('#dialog_code').val(customer.Code);
                $('#dialog_custaddress').val(customer.Address);
                $('#dialog_notes').val(customer.Notes);
                $('#dialog_salespersoncode').data('spiid', customer.SalespersonIID);
                $('#dialog_salespersoncode').val(customer.SalespersonCode);
                $('#dialog_salespersonname').val(customer.SalespersonName);

            }, function (err) {
                hideLoading();
            });
        }

        function OnEdit() {
            getCustomerRecordInfo();
            getContacts();
            getFollowers();

            setTimeout(function () {
                grid_dt && grid_dt.resize();
            });
        }

        function OnSave(exit) {
            var item = {
                'Name': $.trim($('#dialog_name').val()),
                'Code': $.trim($('#dialog_code').val()),
                'Address': $.trim($('#dialog_custaddress').val()),
                'Notes': $.trim($('#dialog_notes').val()),
                'SalespersonIID': $('#dialog_salespersoncode').data('spiid')
            };

            var alerttitle;
            if (custid) {
                item.ID = custid;
                alerttitle = GetTextByKey("P_CR_EDITCUSTOMER", "Edit Customer");
            } else {
                alerttitle = GetTextByKey("P_CR_ADDCUSTOMER", "Add Customer");
            }

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

            showmaskbg(true);
            param = htmlencode(JSON.stringify(item));
            crrequest("SaveCustomerRecord", param, function (data) {
                showmaskbg(false);
                if (typeof (data) === "string") {
                    showAlert(data, alerttitle);
                } else {
                    var lastcustid = custid;
                    custid = data;
                    if (assetid > 0) {
                        assignAssets([assetid], getContacts);
                        assetid = 0;
                    }
                    if (exit == 0) {
                        if (custid > 0)
                            showAlert(GetTextByKey("P_UM_SAVSUCCESSFULLY", "Saved successfully."), alerttitle);

                        if (!lastcustid)
                            init(custid);
                    }
                    else if (exit == 1)
                        OnExit(exit);
                }
            }, function (err) {
                showAlert(GetTextByKey("P_CR_FAILEDTOSAVECUSTOMER", 'Failed to save customer.'), alerttitle);
            });
        }

        function OnExit(type) {
            if (window.parent && typeof window.parent.CloseCustomerDialog == 'function')
                window.parent.CloseCustomerDialog(type);
            else
                window.parent.CloseDialog(type);
        }

        var assignmenloaded = false;
        function init(cid, aid) {
            custid = cid;
            assetid = aid || 0;
            OnAdd();

            $('#tab_header_info').click();

            $('.comments').hide();
            if (custid && custid !== '') {
                OnEdit();
                getCustomerComments();
                $('#tab_header_assignment').show();
                $('#btncomments').show();
            }
            else {
                $('#tab_header_assignment').hide();
                $('#btncomments').hide();
            }

            assignmenloaded = false;
        }

        function onassignmentclick() {
            if (!assignmenloaded) {
                assignmenloaded = true;
                getAssignData();
            }
        }

        function showLoading() {
            loadingCount++;
            $("#dialogmask").show();
        }

        function hideLoading() {
            loadingCount--;
            if (loadingCount === 0)
                $("#dialogmask").hide();
        }


        //*************************Start Comment********************************//

        function getCustomerComments() {
            $('#mask_over_bg').show();
            crrequest("GetCustomerComments", custid, function (data) {
                $('#mask_over_bg').hide();
                if (typeof (data) === "string") {
                    return;
                }
                $("#li_comments").data("loaded", true);
                $("#divcomments").empty();
                if (data && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var comment = data[i];
                        showComment(comment, i == 0)
                    }
                }
            }, function (err) {
                $('#mask_over_bg').hide();
            });
        }

        function showComment(comment, isfirst) {
            var commoentctrl = $("#divcomments");
            var div = $("<div class='msgdiv'></div>").appendTo(commoentctrl);
            if (isfirst)
                div.css("margin-top", 0);
            var divuser = $("<div class='msgtime'></div>").appendTo(div);
            divuser.append($("<div style='float:left;font-weight: bold;'></div>").text(comment.UserName));
            divuser.append($("<div style='float:right;color: #aaa;'></div>").text(comment.SubmitLocalDateStr));
            var contentctrl = $("<div style='clear:both;'></div>").appendTo(div);
            contentctrl.html(replaceHtmlText(comment.Comment));
        }

        function addCustomerComment() {
            var comment = $('#dialog_comments').val();
            if ($.trim(comment) == "") {
                showAlert(GetTextByKey("P_FR_PLEASEINPUTTHECOMMENT", "Please input the comment."), GetTextByKey("P_FR_ERROR", 'Error'));
                return;
            }

            var param = JSON.stringify([custid, false, comment]);
            param = htmlencode(param);
            $('#mask_over_bg').show();
            crrequest("SubmitComment", param, function (data) {
                $('#mask_over_bg').hide();
                if (data !== "") {
                    showAlert(data, GetTextByKey("P_FR_ERROR", 'Error'));
                    return;
                }
                $('#dialog_comments').val("");
                getCustomerComments();
            }, function (err) {
                $('#mask_over_bg').hide();
            });
        }

        function OnAddComment() {
            addCustomerComment();
        }

        function openComments() {
            if ($('.comments').is(":visible"))
                $('.comments').hide();
            else
                $('.comments').show();
        }

        function closeComments() {
            $('.comments').hide();
        }
        //*************************End Comment********************************//


        //*************************Contact********************************//
        var grid_dt;
        function InitGridData() {
            grid_dt = new GridView('#contactlist');
            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_CR_CONTACTNAME", "Contact Name"), valueIndex: 'Name', css: { 'width': 150, 'text-align': 'left' } },
                { name: 'ContactEmail', caption: GetTextByKey("P_CR_CONTACTEMAIL", "Contact Email"), valueIndex: 'Email', css: { 'width': 130, 'text-align': 'left' } },
                { name: 'ContactMobilePhone', caption: GetTextByKey("P_CR_CONTACTMOBILE", "Contact Mobile"), valueIndex: 'MobilePhoneDisplayText', css: { 'width': 140, 'text-align': 'left' } },
                { name: 'ContactPreferenceStr', caption: GetTextByKey("P_CR_CONTACTPREFERENCES", "Contact Preferences"), valueIndex: 'ContactPreferenceStr', css: { 'width': 130, 'text-align': 'left' } },
                { name: 'Active', caption: GetTextByKey("P_CR_ACTIVE", "Active"), valueIndex: 'Active', type: 3, css: { 'width': 60, 'text-align': 'center' } },
                { name: 'OptOut', caption: GetTextByKey("P_CR_OPTOUT", "Opt Out"), valueIndex: 'OptOut', type: 3, css: { 'width': 60, 'text-align': 'center' } },
                { name: 'SurveyOptOut', caption: GetTextByKey("P_CR_XXXXXX", "Survey Opt Out"), valueIndex: 'SurveyOptOut', type: 3, css: { 'width': 80, 'text-align': 'center' } },
                { name: 'CanOpenWO', caption: GetTextByKey("P_CR_XXXXXX", "Can Open WO"), valueIndex: 'CanOpenWO', type: 3, css: { 'width': 80, 'text-align': 'center' } },
                { name: 'Notes', caption: GetTextByKey("P_CR_NOTES", "Notes"), valueIndex: 'Notes', css: { 'width': 200, '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;
                if (list_columns[hd].type) {
                    col.type = list_columns[hd].type;
                }
                if (!AllowCanOpenWO && col.name === "CanOpenWO") {
                    continue;
                }
                if (CRReadOnly && (col.name === "Edit" || col.name === "Delete")) {
                    continue;
                }
                if (col.name === "Active" || col.name === "OptOut" || col.name === "SurveyOptOut" || col.name === "CanOpenWO") {
                    col.enabled = !CRReadOnly;
                    col.events = {
                        onchange: function () {
                            UpdateContact(this);
                        }
                    };
                }
                else if (col.name === "Edit") {
                    col.isurl = true;
                    col.text = "\uf044";
                    col.sortable = false;
                    col.events = {
                        onclick: function () {
                            onEditContact();
                        }
                    };
                    col.classFilter = function (e) {
                        return "icon-col";
                    }
                    col.attrs = { 'title': GetTextByKey("P_UM_EDIT", 'Edit') };
                }
                else if (col.name === "Delete") {
                    col.isurl = true;
                    col.text = "\uf00d";
                    col.sortable = false;
                    col.events = {
                        onclick: function () {
                            onDeleteContact(this);
                        }
                    };
                    col.classFilter = function (e) {
                        return "icon-col";
                    };
                    col.attrs = { 'title': GetTextByKey("P_UM_DELETE", 'Delete') };
                }
                columns.push(col);
            }
            grid_dt.canMultiSelect = false;
            grid_dt.columns = columns;
            grid_dt.init();
            if (!CRReadOnly)
                grid_dt.rowdblclick = onEditContact;
        }

        function getContacts() {
            crrequest('GetContacts', custid, function (data) {
                if (typeof (data) === "string") {
                    showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record"));
                    showcontatcmask(false);
                    return;
                }
                showContacts(data);
            }, function (err) {
            });
        }

        function showContacts(data) {
            var rows = [];
            for (var i = 0; i < data.length; i++) {
                var r = data[i];
                //for (var j in r) {
                //    if (j === "Active") {
                //        r[j] = { DisplayValue: r.Active ? "Yes" : "No", Value: r[j] };
                //    }
                //}
                var fr = { Values: r };
                rows.push(fr);
            }

            grid_dt.setData(rows);
        }

        var contactid = null;
        function onAddContact() {
            var alerttitle = GetTextByKey("P_CR_ADDCONTACT", 'Add Contact')
            if (!custid) {
                showAlert(GetTextByKey("P_CR_PLEASESAVETHECUSTOMERFIRST", 'Please save the customer first.'), alerttitle, undefined);
                return;
            }
            contactid = null;
            $('#dialog_contactname').val("");
            $('#dialog_contactpreference').val("0");
            $('#dialog_emailaddress').val("");
            $('#dialog_mobile').val("");
            $('#dialog_address').val("");
            $('#dialog_contactnotes').val("");
            $('#dialog_active').prop('checked', true);
            $('#dialog_optout').prop('checked', false);
            $('#dialog_surveyoptout').prop('checked', false);
            $('#dialog_canopenwo').prop('checked', false);

            $('#dialog_contact .dialog-title span.title').text(alerttitle);
            showmaskbg(true);
            $('#dialog_contact')
                .css({
                    'top': (document.documentElement.clientHeight - $('#dialog_contact').height()) / 3,
                    'left': (document.documentElement.clientWidth - $('#dialog_contact').width()) / 2
                }).showDialogfixed();
        }

        function onEditContact() {
            var index = grid_dt.selectedIndex;
            if (index < 0) return;

            var contact = grid_dt.source[index].Values;
            contactid = contact.Id;
            $('#dialog_contactname').val(contact.Name);
            $('#dialog_contactpreference').val(contact.ContactPreference);
            $('#dialog_emailaddress').val(contact.Email);
            $('#dialog_mobile').val(contact.MobilePhoneDisplayText);
            $('#dialog_address').val(contact.Address);
            $('#dialog_contactnotes').val(contact.Notes);
            $('#dialog_active').prop('checked', contact.Active);
            $('#dialog_optout').prop('checked', contact.OptOut);
            $('#dialog_surveyoptout').prop('checked', contact.SurveyOptOut);
            $('#dialog_canopenwo').prop('checked', contact.CanOpenWO);

            $('#dialog_contact .dialog-title span.title').text(GetTextByKey("P_CR_EDITCONTACT", 'Edit Contact'));
            showmaskbg(true);
            $('#dialog_contact')
                .css({
                    'top': (document.documentElement.clientHeight - $('#dialog_contact').height()) / 3,
                    'left': (document.documentElement.clientWidth - $('#dialog_contact').width()) / 2
                }).showDialogfixed();
        }

        function onSaveContact() {
            var item = {
                'Name': $.trim($('#dialog_contactname').val()),
                'ContactPreference': $.trim($('#dialog_contactpreference').val()),
                'Email': $.trim($('#dialog_emailaddress').val()),
                'MobilePhone': $.trim($('#dialog_mobile').val()),
                'Address': $('#dialog_address').val(),
                'Notes': $.trim($('#dialog_contactnotes').val()),
                'Active': $('#dialog_active').prop('checked'),
                'OptOut': $('#dialog_optout').prop('checked'),
                'SurveyOptOut': $('#dialog_surveyoptout').prop('checked'),
                'CanOpenWO': $('#dialog_canopenwo').prop('checked')
            };

            var alerttitle;
            if (contactid) {
                item.Id = contactid;
                alerttitle = GetTextByKey("P_CR_EDITCONTACT", "Edit Contact");
            } else {
                alerttitle = GetTextByKey("P_CR_ADDCONTACT", "Add Contact");
            }

            if (!item.Name || item.Name.length == 0) {
                showAlert(GetTextByKey("P_CR_CONTACTNAMECANNOTBEEMPTY", 'Contact Name cannot be empty.'), alerttitle, undefined, function () { $('#dialog_contactname').focus(); });
                return;
            }
            if ((!item.Email || item.Email.length == 0) && (!item.MobilePhone || item.MobilePhone.length == 0)) {
                showAlert(GetTextByKey("P_CR_EMAILANDMOBILEPHONECANNOTBOTHBEEMPTY", 'Email and Mobile Phone cannot both be empty. '), alerttitle);
                return;
            }
            if (item.Email !== "" && !isEmail(item.Email)) {
                showcontatcmask(true);
                showAlert(GetTextByKey("P_CR_EMAILISNOTAVALIDEMAILADDRESS", 'The email address is invalid.'), alerttitle, undefined, function () {
                    showcontatcmask(false);
                });
                return;
            }

            showcontatcmask(true);
            param = htmlencode(JSON.stringify([custid, JSON.stringify(item)]));
            crrequest("SaveContact", param, function (data) {
                showcontatcmask(false);
                if (typeof (data) === "string") {
                    showcontatcmask(true);
                    showAlert(data, alerttitle, undefined, function () {
                        showcontatcmask(false);
                    });
                } else {
                    $('#dialog_contact').hideDialog();
                    showmaskbg(false);
                    getContacts();
                }
            }, function (err) {
                showAlert(GetTextByKey("P_CR_FAILEDTOSAVECONTACT", 'Failed to save contact.'), alerttitle);
            });
        }

        function UpdateContact(item) {
            param = htmlencode(JSON.stringify([custid, JSON.stringify(item)]));
            crrequest("SaveContact", param, function (data) {

            }, function (err) {
            });
        }

        function onDeleteContact(c) {
            if (!c) {
                return;
            }
            showConfirm(GetTextByKey("P_CR_DOYOUWANTTODELETETHISCONTACT", 'Do you want to delete this contact?'), GetTextByKey("P_CR_DELETECONTACT", 'Delete Contact'), function () {
                crrequest('DeleteContact', c.Id, function (data) {
                    getContacts();
                }, function (err) {
                    showAlert(GetTextByKey('P_CR_FAILEDTODELETETHISCONTACT', 'Failed to delete this contact.'), GetTextByKey("P_CR_DELETECONTACT", 'Delete Contact'));
                });
            });
        }
        //*************************End Contact********************************//


        //*************************Follower********************************//

        var grid_dtfollower;
        function InitFollowerGridData() {
            grid_dtfollower = new GridView('#followerlist');
            grid_dtfollower.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_CR_CONTACTNAME", "Contact Name"), valueIndex: 'Name', css: { 'width': 150, 'text-align': 'left' } },
                { name: 'ContactEmail', caption: GetTextByKey("P_CR_CONTACTEMAIL", "Contact Email"), valueIndex: 'Email', css: { 'width': 130, 'text-align': 'left' } },
                { name: 'ContactMobilePhone', caption: GetTextByKey("P_CR_CONTACTMOBILE", "Contact Mobile"), valueIndex: 'MobilePhoneDisplayText', css: { 'width': 120, 'text-align': 'left' } },
                { name: 'ContactPreferenceStr', caption: GetTextByKey("P_CR_CONTACTPREFERENCES", "Contact Preferences"), valueIndex: 'ContactPreferenceStr', css: { 'width': 80, 'text-align': 'left' } },
                { 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;
                if (list_columns[hd].type) {
                    col.type = list_columns[hd].type;
                }
                if (CRReadOnly && (col.name === "Delete")) {
                    continue;
                }
                if (col.name == "ContactPreferenceStr") {
                    col.filter = function (item) {
                        var text = "";
                        if (item.SendEmail)
                            text = "Email";
                        if (item.SendText) {
                            if (text == "")
                                text = "Text";
                            else
                                text += ", Text";
                        }
                        return text;
                    }
                }
                else if (col.name === "Delete") {
                    col.isurl = true;
                    col.text = "\uf00d";
                    col.sortable = false;
                    col.events = {
                        onclick: function () {
                            onDeleteFollower(this);
                        }
                    };
                    col.classFilter = function (e) {
                        return "icon-col";
                    };
                    col.attrs = { 'title': GetTextByKey("P_UM_DELETE", 'Delete') };
                }

                columns.push(col);
            }
            grid_dtfollower.canMultiSelect = false;
            grid_dtfollower.columns = columns;
            grid_dtfollower.init();
        }

        function showFollowers(data) {
            var rows = [];
            for (var i = 0; i < data.length; i++) {
                var r = data[i];
                var fr = { Values: r };
                rows.push(fr);
            }

            grid_dtfollower.setData(rows);
        }

        var grid_allfollower;
        function InitAllFollowerGridData() {
            grid_allfollower = new GridView('#allfollowerlist');
            grid_allfollower.lang = {
                all: GetTextByKey("P_GRID_ALL", "(All)"),
                ok: GetTextByKey("P_GRID_OK", "OK"),
                reset: GetTextByKey("P_GRID_RESET", "Reset")
            };
            var list_columns = [
                { name: 'DisplayName', caption: GetTextByKey("P_WO_CONTACTNAME", "Contact Name"), valueIndex: 'DisplayName', css: { 'width': 240, 'text-align': 'left' } },
                { name: 'ContactTypeName', caption: GetTextByKey("P_WO_CONTACTTYPE", "Contact Type"), valueIndex: 'ContactTypeName', css: { 'width': 120, 'text-align': 'left' } },
                { name: 'Text', caption: "Text", valueIndex: 'Text', type: 3, css: { 'width': 60, 'text-align': 'center' } },
                { name: 'Email', caption: GetTextByKey("P_WO_EMAIL", "Email"), valueIndex: 'Email', type: 3, css: { 'width': 70, '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;
                if (list_columns[hd].type) {
                    col.type = list_columns[hd].type;
                }
                columns.push(col);
                if (col.name === "Text") {
                    col.enabled = function (item) {
                        return item.Mobile != null && $.trim(item.Mobile).length > 0;
                    };
                }
                if (col.name === "Email") {
                    col.enabled = function (item) {
                        return item.ID !== '';
                    };
                }
            }
            grid_allfollower.canMultiSelect = false;
            grid_allfollower.columns = columns;
            grid_allfollower.init();
        }

        function showAllFollower(data) {
            var rows = [];
            for (var i = 0; i < data.length; i++) {
                var r = data[i];
                for (var j in r) {
                    var a = r[j];
                }
                if (!r.Text)
                    r.Text = false;
                if (!r.Email)
                    r.Email = false;
                var fr = { Values: r };
                rows.push(fr);
            }

            grid_allfollower.setData(rows);
        }

        var isloadfollower = false;
        var allfollowers = [];
        function getAllFollowers() {
            crrequest('GetAllFollowers', '', function (data) {
                if (typeof (data) === "string") {
                    showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record"));
                    showmaskbg(false);
                    return;
                }
                isloadfollower = true;
                allfollowers = data;
                showAllFollower(data);
            }, function (err) {
            });
        }

        function getFollowers() {
            crrequest('GetFollowers', custid, function (data) {
                if (typeof (data) === "string") {
                    showAlert(data, GetTextByKey('P_CUSTOMERRECORD', "Customer Record"));
                    showcontatcmask(false);
                    return;
                }
                showFollowers(data);
            }, function (err) {
            });
        }

        function searchFollower(newopen) {//newopen新打开
            var filter = $('#selfollower_search').val().trim().toLowerCase();
            if (isloadfollower && allfollowers) {
                var emails = [];
                for (var i = 0; i < allfollowers.length; i++) {
                    var m = allfollowers[i];
                    if (newopen) {
                        m.Text = false;
                        m.Email = false;
                        emails.push(m);
                    }
                    else {
                        if (!m.Text && !m.Email) {
                            if (m.ID.toLowerCase().indexOf(filter) >= 0 || m.DisplayName.toLowerCase().indexOf(filter) >= 0)
                                emails.push(m);
                        }
                        else
                            emails.push(m);
                    }
                }
                showAllFollower(emails);
            }
        }

        function onAddFollower() {
            var alerttitle = GetTextByKey("P_CR_XXX", 'Add Followers')
            if (!custid) {
                showAlert(GetTextByKey("P_CR_PLEASESAVETHECUSTOMERFIRST", 'Please save the customer first.'), alerttitle, undefined);
                return;
            }

            $('#selfollower_search').val('').attr('placeholder', GetTextByKey('P_IPT_SEARCH', 'Search'));
            if (!isloadfollower)
                getAllFollowers();
            else
                searchFollower(true);

            $('#addfollowerpopupdialog .dialog-title span.title').text(alerttitle);
            showmaskbg(true);
            $('#addfollowerpopupdialog')
                .css({
                    'top': (document.documentElement.clientHeight - $('#addfollowerpopupdialog').height()) / 3,
                    'left': (document.documentElement.clientWidth - $('#addfollowerpopupdialog').width()) / 2
                }).showDialogfixed();

            setTimeout(function () {
                grid_allfollower && grid_allfollower.resize();
            });
        }

        function onSaveFollowers() {
            var followers = [];
            for (var i = 0; i < grid_allfollower.source.length; i++) {
                var ct = grid_allfollower.source[i].Values;
                if (ct.Email || ct.Text) {
                    var f = {};
                    f.Id = -1;
                    f.UserIID = ct.IID;
                    f.Name = ct.DisplayName;
                    f.Email = ct.ID;
                    f.MobilePhone = ct.Mobile;
                    f.SendEmail = ct.Email;
                    f.SendText = ct.Text;
                    followers.push(f);
                }
            }
            var param = JSON.stringify([custid, JSON.stringify(followers)]);
            param = htmlencode(param);
            crrequest("AddFollowers", param, function (data) {
                if (data !== "OK") {
                    showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
                    return;
                }
                showmaskbg(false);
                $('#addfollowerpopupdialog').hideDialog();
                getFollowers();
            }, function (err) {
                //showmaskbg(false);
            });
        }

        function onDeleteFollower(c) {
            if (!c) {
                return;
            }
            showConfirm(GetTextByKey("P_CR_XXX", 'Do you want to delete this follower?'), GetTextByKey("P_CR_XXXXXX", 'Delete Follower'), function () {
                crrequest('DeleteFollower', c.Id, function (data) {
                    getFollowers();
                }, function (err) {
                    showAlert(GetTextByKey('P_CR_XXX', 'Failed to delete this follower.'), GetTextByKey("P_CR_DELETECONTACT", 'Delete Contact'));
                });
            });
        }

        //*************************End Follower********************************//

        $(function () {
            InitGridData();
            InitSPGridData();
            InitAllFollowerGridData();
            InitFollowerGridData();
            init();
            if (CRReadOnly)
                $('#dialog_comments').attr('disabled', 'disabled');

            $("#div_container").tab();
            function resizeContent() {
                $('#divcontent').css('height', $(window).height() - $('#divcontent').offset().top - 4);
            }

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

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

            $('#addfollowerpopupdialog').dialog(function () {
                showmaskbg(false);
            });
            $('#selfollower_search').bind('input propertychange', function () {
                searchFollower(false);
            });
            $('#selfollower_search').keydown(function () {
                searchFollower(false);
            });
            $('#sp_searchinputtxt').keydown(searchSalespersonEnter);

            window.onresize = resizeContent;
            resizeContent();
        });

    </script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div>
        <div class="function_title">
            <%if (!CRReadOnly)
                {%>
            <span class="sbutton iconsave" onclick="OnSave(0);" data-lgid="P_UM_SAVE">Save</span>
            <span class="sbutton iconsave" onclick="OnSave(1);" data-lgid="P_UM_SAVE1">Save and Exit</span>
            <%}%>
            <span class="sbutton iconexit" onclick="OnExit(0);" data-lgid="P_UM_SAVE2">Exit Without Saving</span>
            <span class="sbutton iconcomment" onclick="openComments();" id="btncomments" data-lgid="P_CR_COMMENTS">Comments</span>
        </div>
        <div class="clear"></div>
        <div class="content_main" id="divcontent" style="overflow: auto;">
            <div class="edit-content">
                <div id="div_container">
                    <ul id="ul_container" class="tab_header" style="padding-top: 5px;">
                        <li id="tab_header_info" data-href="tab_custinfo" class="selected" data-lgid="P_CR_CUSTOMERINFORMATION">Customer Information</li>
                        <li id="tab_header_assignment" data-href="tab_assignment" onclick="onassignmentclick()" data-lgid="P_UM_ASSETASSIGNMENT" style="display: none;">Asset Assignment</li>
                    </ul>
                    <div id="tab_custinfo" data-page="tab_custinfo">
                        <table style="line-height: 30px; table-layout: fixed; width: 600px;">
                            <tr>
                                <td class="label" data-lgid="P_CR_CODE_COLON">Code:</td>
                                <td style="width: 330px;">
                                    <input type="text" id="dialog_code" tabindex="1" maxlength="50" autocomplete="off" /></td>
                                <td class="label" data-lgid="P_CR_SALESPERSONCODE_COLON">Salesperson Code:</td>
                                <td style="width: 400px;">
                                    <input type="text" id="dialog_salespersoncode" tabindex="1" style="width: 296px;" disabled="disabled" autocomplete="off" />
                                    <%if (!CRReadOnly)
                                        {%>
                                    <span class="sbutton iconsearch" style="display: inline; padding: 6px 0px 6px 5px;" onclick="onOpenSalesperson()" data-titlt-lgid="P_CR_SELECTSALESPERSON" title="Select Salesperson"></span>
                                    <span class="sbutton icondelete" style="display: inline; padding: 6px 0px 6px 5px;" onclick="onDeleteSalesperson()" data-titlt-lgid="P_CR_DELETESALESPERSON" title="Delete Salesperson"></span>
                                    <%}%>
                                </td>
                                <td></td>
                            </tr>
                            <tr>
                                <td class="label"><span data-lgid="P_CR_COMPANYNAME_COLON">Company Name:</span><span class="redasterisk">*</span></td>
                                <td>
                                    <input type="text" id="dialog_name" tabindex="1" maxlength="200" autocomplete="off" /></td>
                                <td class="label" data-lgid="P_CR_SALESPERSONNAME_COLON">Salesperson Name:</td>
                                <td>
                                    <input type="text" id="dialog_salespersonname" tabindex="1" style="width: 296px;" disabled="disabled" autocomplete="off" />
                                </td>
                                <td></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_CR_ADDRESS_COLON">Address:</td>
                                <td colspan="4">
                                    <input type="text" id="dialog_custaddress" tabindex="1" maxlength="500" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_CR_NOTES_COLON">Notes:</td>
                                <td colspan="4">
                                    <textarea id="dialog_notes" tabindex="1" style="width: 840px; height: 100px; margin-top: 6px;" maxlength="2000"></textarea></td>
                            </tr>
                        </table>

                        <div class="subtitle">
                            <span data-lgid="P_CR_CONTACTINFORMATION">Contact Information</span>
                            <%if (!CRReadOnly)
                                {%>
                            <span class="sbutton iconadd" style="display: inline;" onclick="onAddContact()">Add</span>
                            <%}%>
                            <hr />
                        </div>

                        <table style="line-height: 30px; table-layout: fixed;">
                            <tr>
                                <td class="label"></td>
                                <td>
                                    <div id="contactlist" style="height: 240px; width: 940px;"></div>
                                </td>
                            </tr>
                        </table>


                        <div class="subtitle">
                            <span data-lgid="P_CR_XXX">Following</span>
                            <%if (!CRReadOnly)
                                {%>
                            <span class="sbutton iconadd" style="display: inline;" onclick="onAddFollower()">Add</span>
                            <%}%>
                            <hr />
                        </div>

                        <table style="line-height: 30px; table-layout: fixed;">
                            <tr>
                                <td class="label"></td>
                                <td>
                                    <div id="followerlist" style="height: 240px; width: 940px;"></div>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <div id="tab_assignment" data-page="tab_assignment" style="display: none;">
                        <div style="display: inline-block;">
                            <div class="machine_filter" style="margin: 9px 6px 5px">
                                <span class="title" data-lgid="P_UM_ASSETASS">Asset(s)</span>
                                <%if (!CRReadOnly)
                                    {%>
                                <span class="sbutton iconadd" onclick="OnAssetAdd()" data-lgid="P_UM_ADD">Add</span>
                                <span class="sbutton icondelete" onclick="OnMachineDelete()" data-lgid="P_UM_DELETE">Delete</span>
                                <%}%>
                            </div>
                            <div id="selectedmachinelist" style="height: 500px; width: 1000px;"></div>
                        </div>
                    </div>
                    <div class="mask_loading dialog" style="display: none;"></div>


                    <div class="comments" style="display: none; width: 400px; background-color: #f4f4f4; position: absolute; right: 0; top: 0; bottom: 0; box-shadow: #CECACA -4px 0px 6px;">
                        <div style="padding: 5px 0 5px 10px; background-color: #dcdcdc;">
                            <span data-lgid="P_CR_COMMENTS">Comments</span>
                            <em class="spanbtn icondelete" style="float: right; margin-right: 5px; font-size: 14px;" onclick="closeComments()"></em>
                        </div>
                        <div style="clear: both;"></div>
                        <div style="position: absolute; width: 380px; top: 32px; bottom: 1px; right: 10px;">
                            <div style="left: 2px; top: 5px; height: 106px;">
                                <table>
                                    <tr>
                                        <td>
                                            <div style="border: solid 1px rgb(123,28,33);">
                                                <textarea id="dialog_comments" maxlength="3000" tabindex="1" style="margin-top: 4px; width: 360px; height: 60px; border: none; outline: none;"></textarea>
                                                <br />
                                                <div style="font-size: 20px; text-align: right; margin-bottom: 3px;">
                                                    <%if (!CRReadOnly)
                                                        {%>
                                                    <span class="spanbtn iconsend" onclick="OnAddComment();"></span>
                                                    <%}%>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            <div id="divcomments" style="position: absolute; bottom: 5px; top: 110px; left: 5px; right: 0; overflow: auto;">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div id="dialogmask" class="maskbg" style="display: none;">
            <div class="loading_icon icon c-spin"></div>
        </div>
    </div>
    
    <div id="mask_bg" style="display: none; "><div class="loading c-spin"></div></div>
    <div class="dialog" id="dialog_contact" style="display: none;">
        <div class="dialog-title"><span class="title" data-lgid="P_CR_ADDCONTACT">Add Contact</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <table style="line-height: 30px; table-layout: fixed; width: 480px;">
                <tr>
                    <td class="label"><span data-lgid="P_CR_CONTACTNAME_COLON">Contact Name:</span><span class="redasterisk">*</span></td>
                    <td>
                        <input type="text" id="dialog_contactname" tabindex="1" maxlength="200" autocomplete="off" /></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_CR_CONTACTPREFERENCES_COLON">Contact Preference:</td>
                    <td>
                        <select id="dialog_contactpreference" tabindex="1" style="width: 324px; height: 24px;">
                            <option value="0" data-lgid="P_CR_TEXT">Text</option>
                            <option value="1" data-lgid="P_CR_EMAIL">Email</option>
                            <option value="2" data-lgid="P_CR_PHONE">Phone</option>
                        </select></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_CR_EMAILADDRESS_COLON">Email Address:</td>
                    <td>
                        <input type="text" id="dialog_emailaddress" tabindex="1" maxlength="100" autocomplete="off" /></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_UM_MOBILE_COLON">Mobile:</td>
                    <td>
                        <input type="text" id="dialog_mobile" tabindex="1" maxlength="50" autocomplete="off" /></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_UM_ADDRESS_COLON">Address:</td>
                    <td>
                        <input type="text" id="dialog_address" tabindex="1" maxlength="500" autocomplete="off" /></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_CR_ACTIVE_COLON">Active:</td>
                    <td>
                        <input type="checkbox" id="dialog_active" checked="checked" tabindex="1" /></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_CR_XXXXXX">Opt Out:</td>
                    <td>
                        <input type="checkbox" id="dialog_optout" tabindex="1" /></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_CR_XXXXXX">Survey Opt Out:</td>
                    <td>
                        <input type="checkbox" id="dialog_surveyoptout" tabindex="1" /></td>
                </tr>
                <%if (AllowCanOpenWO)
                    {%>
                <tr>
                    <td class="label" data-lgid="P_CR_XXXXXX">Can Open WO:</td>
                    <td>
                        <input type="checkbox" id="dialog_canopenwo" tabindex="1" /></td>
                </tr>
                <%}%>
                <tr>
                    <td class="label" data-lgid="P_CR_NOTES_COLON">Notes:</td>
                    <td>
                        <textarea id="dialog_contactnotes" tabindex="1" style="width: 320px; height: 100px; margin-top: 6px;" maxlength="2000"></textarea></td>
                </tr>
            </table>
        </div>
        <div class="dialog-func">
            <input type="button" value="Cancel" data-lgid="P_UM_CANCEL" class="dialog-close" tabindex="18" style="height: unset;" />
            <input type="button" onclick="onSaveContact();" value="OK" data-lgid="P_UM_OK" tabindex="17" />
            <div style="clear: both;"></div>
        </div>
        <div class="maskbg" id="contatcmask" style="display: none;"></div>
    </div>

    <div class="dialog" id="dialog_salesperson" style="display: none;">
        <div class="dialog-title"><span class="title" data-lgid="P_CR_SELECTSALESPERSON">Select Salesperson</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <div style="position: relative; width: 400px; margin-top: 4px; float: left">
                <input id="sp_searchinputtxt" type="text" placeholder="Search" style="width: 100%; padding-right: 28px; height: 25px; line-height: 25px; box-sizing: border-box; text-indent: 4px;" />
                <div onclick="GetSalespersons();" style="position: absolute; top: 0px; right: 0px; height: 25px; width: 28px; text-align: center; line-height: 25px; font-size: 1.2em; font-family: FontAwesome; font-weight: 900; color: rgb(123, 28, 33); cursor: pointer;"></div>
            </div>
            <div style="clear: both"></div>
            <div id="salespersonlist" style="width: 650px; height: 400px; margin: 10px 0 4px"></div>
        </div>
        <div class="dialog-func">
            <input type="button" value="Cancel" data-lgid="P_UM_CANCEL" class="dialog-close" tabindex="18" style="height: unset;" />
            <input type="button" onclick="onSetSalesperson();" value="OK" data-lgid="P_UM_OK" tabindex="17" />
            <div style="clear: both;"></div>
        </div>
        <div class="maskbg" id="salespersonmask" style="display: none;"></div>
    </div>

    <div id="addfollowerpopupmask" class="maskbg" style="display: none;"></div>
    <div class="dialog" id="addfollowerpopupdialog" style="display: none; width: 560px;">
        <div class="dialog-title"><span class="title" data-lgid="P_WO_XXXXXX">Add Followers</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <table style="line-height: 25px;">
                <tr>
                    <td data-lgid="P_WO_XXXXXX">Who do you want to receive customer notifications?</td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="text" id="selfollower_search" style="width: 445px; margin-left: 10px;" placeholder="Search" /></td>
                </tr>
                <tr>
                    <td>
                        <div id="allfollowerlist" style="height: 240px; width: 520px; margin-left: 10px; margin-right: 10px;"></div>
                    </td>
                </tr>
            </table>
        </div>
        <div class="dialog-func">
            <input type="button" value="Cancel" data-lgid="P_WO_CANCEL" class="dialog-close" tabindex="153" />
            <input type="button" onclick="onSaveFollowers();" value="OK" data-lgid="P_WO_OK" tabindex="152" />
            <div class="clear"></div>
        </div>
    </div>
</asp:Content>