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


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <link href="<%=GetFileUrlWithVersion("css/maintenance.css")%>" rel="stylesheet" />
    <style type="text/css">
        body {
            min-height: 640px;
        }

        ::-ms-clear, ::-ms-reveal {
            display: none;
        }

        .dialog-content .dropdown .dropdown-wrapper > .dropdown-header {
            min-height: 22px;
        }

            .dialog-content .dropdown .dropdown-wrapper > .dropdown-header > .dropdown-text {
                line-height: 22px;
            }

        .dropdown {
            width: 240px;
        }

        #mask_bg, #dialogattmask, .mask_dialog, .dialog {
            z-index: 3;
        }
    </style>

    <link href="<%=GetFileUrlWithVersion("../css/tabcontrol.css")%>" rel="stylesheet" />
    <link href="<%=GetFileUrlWithVersion("../css/panel.css")%>" rel="stylesheet" />
    <link href="<%=GetFileUrlWithVersion("../css/jquery.datetimepicker.css")%>" rel="stylesheet" />
    <script src="<%=GetFileUrlWithVersion("../js/lib/amrnb.js")%>"></script>
    <script src="<%=GetFileUrlWithVersion("../Maintenance/js/inputdatactr.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../js/jquery.datetimepicker.full.js")%>"></script>
    <script src="<%=GetFileUrlWithVersion("../js/controls.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("js/workordersendemail.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("js/wocommunication.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../js/assetselector.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("js/workordertabitems.min.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("js/addworkorder.js")%>" type="text/javascript"></script>
    <script type="text/javascript">
        var contacts;

        var workorderid = "<%=WorkOrderID %>";
        var machineid = "<%=MachineID %>";
        var workorderdata;
        var customercontacts = [];
        var followers = [];
        var machine = null;
        var alertids = [<%=AlertIDs%>];
        var IsAdvisor =<%=IsAdvisor ?"true":"false"%>;
        var IsAdmin =<%=IsAdmin ?"true":"false"%>;
        var AllowCommunicate =<%=AllowCommunicate ?"true":"false"%>;
        var AllowCustomer =<%=AllowCustomer ?"true":"false"%>;
        var WOReadOnly =<%=WOReadOnly ?"true":"false"%>;
        var CRReadOnly =<%=CRReadOnly ?"true":"false"%>;
        var COMMReadOnly =<%=COMMReadOnly ?"true":"false"%>;
        var AllowReopenWorkorders = <%=AllowReopenWorkorders ?"true":"false"%>;
        var AllowReassignWorkorders = <%=AllowReassignWorkorders ?"true":"false"%>;
        var AllowDeleteAtta = <%=AllowDeleteAtta ?"true":"false"%>;
        var meterType = "<%=MeterType%>";
        var nowDate = new DateFormatter().formatDate(new Date("<%=NowDate%>"), 'm/d/Y');
        var currentdate = "<%=NowDate %>";

        var _attachments = [];

        var wotypedata = [];
        var WorkorderParams;

        //动态加载列表
        var displayCountPerPage = 100;//每页显示的条数
        var currentShownIndex = -1;//当前显示的索引 
        var needRefreshDataOnCancel = false;

        // communication parameter
        var customer;
        var internal;

        function worequest(method, param, callback, error) {
            _network.request("Maintenance/AddWorkOrder.aspx", -1, method, param, callback, error || function (e) {
                showAlert(GetTextByKey('P_WO_PAGEERROR', 'An unknown error occurred.  Please refresh page.'), GetTextByKey('P_WO_QUERY', 'Query'));
            });
        }

        function alertrequest(method, param, callback, error) {
            _network.request("Maintenance/AlertsManagement.aspx", -1, method, param, callback, error || function (e) {
                showAlert(GetTextByKey('P_WO_PAGEERROR', 'An unknown error occurred.  Please refresh page.'), GetTextByKey('P_WO_QUERY', 'Query'));
            });
        }

        customerquery = function (method, param, callback, error) {
            _network.request("Maintenance/CustomerRecordManagement.aspx", -1, method, param, callback, error);
        }

        function showThreeButtonConfirm(msg, title, fyes, fno, fcancel) {
            showmaskbg(true);
            _dialog.showConfirmYesNoCancel(msg, title, function (e) {
                showmaskbg(false);
                if (typeof fyes === 'function') {
                    fyes(e);
                }
            }, function (e) {
                showmaskbg(false);
                if (typeof fno === 'function') {
                    fno(e);
                }
            }, function (e) {
                showmaskbg(false);
                if (typeof fcancel === 'function') {
                    fcancel(e);
                }
            });
        }

        function OnAdd() {
            if (machineid === "")
                $("#btnSelectAsset").show();
            else
                $("#btnSelectAsset").hide();

            meterType = "HourMeter";
            SetWorkOrderDisabled(false);
        }

        function SetWorkOrderDisabled(di) {
            $('#dialog_wotype').dropdownDisabled(di);
            $('#dialog_partsordernumber').attr('disabled', di);
            $('#dialog_partsstatus').dropdownDisabled(di);
            $('#dialog_wocomponent').dropdownDisabled(di);
            $('#dialog_assignto').dropdownDisabled(di);
            $('#dialog_status').dropdownDisabled(di);
            $('#dialog_nextfollowupdate').attr('disabled', di);
            $('#dialog_duedate').attr('disabled', di);
            $('#dialog_description').attr('disabled', di);
            //$('#dialog_workordercosts').attr('disabled', di);
            $('#dialog_timetocomplete').attr('disabled', di);
            $('#dialog_completeddate').attr('disabled', di);
            $('#dialog_location').dropdownDisabled(di);
            $('#dialog_department').dropdownDisabled(di);
            $('#dialog_advisor').dropdownDisabled(di);
            $('#dialog_salesperson').dropdownDisabled(di);
            $('#dialog_isptemplate').dropdownDisabled(di);
            $('#dialog_internalid').attr('disabled', di);
            $('#dialog_ponumber').attr('disabled', di);
            $('#dialog_notes').attr('disabled', di);
            $('#dialog_metertype').dropdownDisabled(di);
            $('#dialog_hourmeter').attr('disabled', di);
            $('#dialog_odometer').attr('disabled', di);
            $('#dig_odometeruom').dropdownDisabled(di);
            if (!di)
                setMeterType();
            if (typeof customer !== 'undefined') {
                customer.autoUpdatesEnabled = !di;
            }

            $('#dialog_partsexpecteddate').attr('disabled', di);
            $('#dialog_lastlabordate').attr('disabled', di);
            $('#dialog_inspectionrequired').attr('disabled', di);
            $('#dialog_alternatestatus').attr('disabled', di);
            $('#dialog_billable').attr('disabled', di);
            $('#dialog_billtojob').dropdownDisabled(di);

            if (di) {
                $('#btnaddcustomer').hide();
                //$('#traddcontact').hide();
            }
            else {
                $('#btnaddcustomer').show();
                //$('#traddcontact').show();
            }

            $('#dialog_custcontactname').attr('disabled', di);
            $('#dialog_custcontactpreference').attr('disabled', di);
            $('#dialog_custemailaddress').attr('disabled', di);
            $('#dialog_custmobile').attr('disabled', di);

            $('#dialog_othercost').attr('disabled', di);
            $('#dialog_partscost').attr('disabled', di);
            $('#dialog_traveltimecost').attr('disabled', di);
            $('#dialog_invoicenumber').attr('disabled', di);
        }

        var loading = false;
        function OnEdit() {
            if (!workorderid || workorderid == "") return;

            if (loading)
                return;
            loading = true;

            contacts = undefined;
            $("#tdExportReport").hide();
            $("#btnSelectAsset").hide();
            $('#tabAttachments').hide();
            $("#tbAttas").empty();
            $('#tabAssetAttachments').hide();
            $("#tbAssetAttas").empty();
            $('.iconsave').hide();
            if (/*IsAdmin &&*/ AllowCustomer) {
                $("#tdExportReport").show();
            }

            showLoading(true);
            getWorkOrderContacts(workorderid);
            getWorkOrderFollowers(workorderid);
            worequest("GetWorkOrderInfo", workorderid, function (data) {
                showLoading(false);
                loading = false;
                if (typeof (data) === "string") {
                    showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
                    return;
                }
                var wo = data;
                if (wo.Id != workorderid) {
                    OnEdit();
                    return;
                }
                $('.iconsave').show();

                workorderdata = wo;
                meterType = wo.MeterType;
                $('#dialog_metertype').dropdownVal(meterType);
                setMeterType();

                machineid = wo.AssetID;
                machine = { Id: wo.AssetID, VIN: wo.VIN, DisplayName: wo.AssetName };
                woalertobj && woalertobj.changeasset(machineid);
                woinspectionobj && woinspectionobj.changeasset(machineid);
                wosegmentobj.setwodata(workorderdata);
                woestimateobj.setwodata(workorderdata);
                woinvoiceobj.setwodata(workorderdata);
                setMachineInfo(wo);
                getAssetDetailInfo(machineid);

                var isshowmachine = false;
                if (!IsAdmin && wo.Completed && !AllowReopenWorkorders) {
                    SetWorkOrderDisabled(true);
                    isshowmachine = true;
                    $("#btnSelectAsset").hide();
                }
                else
                    SetWorkOrderDisabled(false);

                if (wo.Completed) {
                    $('#span_addalerts').css('display', 'none');
                    $('#span_removealerts').css('display', 'none');
                    $('#btnaddpmalerts').css('display', 'none');
                    $('.span_required').show();
                }
                else {
                    if (!WOReadOnly) {
                        $('#span_addalerts').css('display', '');
                        $('#span_removealerts').css('display', '');
                        $('#btnaddpmalerts').css('display', '');
                        $('.span_required').hide();
                    }
                }

                setPageTitle(GetTextByKey("P_WORKORDER", "Work Order") + " " + (wo.WorkOrderNumber === "" ? wo.Id : wo.WorkOrderNumber), true);
                $('#dialog_wonumber').text(wo.WorkOrderNumber === "" ? wo.Id : wo.WorkOrderNumber);
                $('#divwonumber').show();
                $('#dialog_wotype').dropdownVal(wo.WorkOrderType);
                $('#dialog_partsordernumber').val(wo.PartsOrderNumber);
                $('#dialog_partsstatus').dropdownVal(wo.PartsStatus);
                $('#dialog_wocomponent').dropdownVal(wo.Component);
                showContacts();//$('#dialog_assignto').dropdownVal(wo.AssignedTo);
                showWorkOrderStatusSource();//$('#dialog_status').dropdownVal(wo.Status);                
                $('#dialog_description').val(wo.Description);
                $('#dialog_nextfollowupdate').val(wo.NextFollowUpDateStr);
                if (new Date(wo.NextFollowUpDateStr) < new Date(currentdate))
                    $('#dialog_nextfollowupdate').css("color", "red");
                else
                    $('#dialog_nextfollowupdate').css("color", "unset");
                $('#dialog_duedate').val(wo.DueDateStr);
                if (new Date(wo.DueDateStr) < new Date(currentdate))
                    $('#dialog_duedate').css("color", "red");
                else
                    $('#dialog_duedate').css("color", "unset");
                $('#dialog_completeddate').val(wo.CompleteDateStr);
                $('#dialog_workordercosts').val(wo.WorkOrderTotalCost == 0 ? "" : wo.WorkOrderTotalCost);
                $('#dialog_timetocomplete').val(wo.HoursToComplete == 0 ? "" : wo.HoursToComplete);
                $('#dialog_location').dropdownVal(wo.LocationId);
                $('#dialog_department').dropdownVal(wo.DepartmentId);
                $('#dialog_advisor').dropdownVal(wo.AdvisorId);
                $('#dialog_internalid').val(wo.InternalID);
                $('#dialog_ponumber').val(wo.PONumber);
                $('#dialog_notes').val(wo.Notes);
                $('#dialog_hourmeter').val(wo.HourMeter < 0 ? "" : wo.HourMeter);
                $('#dialog_odometer').val(wo.Odometer < 0 ? "" : wo.Odometer);
                $('#dig_odometeruom').dropdownVal(wo.OdometerUnits);
                $('#dialog_billable').prop('checked', wo.Billable);
                if (!alljobsites) {
                    if (wo.BillToJob > 0)
                        $('#dialog_billtojob').dropdownSource([{ ID: wo.BillToJob, Name: wo.BillToJobName == "" ? " " : wo.BillToJobName }]).dropdownVal(wo.BillToJob);
                }
                else
                    $('#dialog_billtojob').dropdownVal(wo.BillToJob);

                if (!allsalespersons) {
                    if (wo.SalespersonId !== "")
                        $('#dialog_salesperson').dropdownSource([{ Key: wo.SalespersonId, Value: wo.SalespersonName == "" ? " " : wo.SalespersonName }]).dropdownVal(wo.SalespersonId);
                }
                else
                    $('#dialog_salesperson').dropdownVal(wo.SalespersonId);

                if (!allisptemplates) {
                    if (wo.InspectionTemplateId !== "")
                        $('#dialog_isptemplate').dropdownSource([{ Key: wo.InspectionTemplateId, Value: wo.InspectionTemplateName == "" ? " " : wo.InspectionTemplateName }]).dropdownVal(wo.InspectionTemplateId);
                }
                else
                    $('#dialog_isptemplate').dropdownVal(wo.InspectionTemplateId);

                customerid = wo.CustomerId;
                $('#dialog_custcustomername').text(wo.CustomerName);
                $('#dialog_custcustomercode').text(wo.CustomerCode);
                if (customerid && customerid != "")
                    $(".custcode").show();
                else
                    $(".custcode").hide();

                $('#dialog_othercost').val(wo.OtherCost == 0 ? "" : wo.OtherCost);
                $('#dialog_partscost').val(wo.PartsCost == 0 ? "" : wo.PartsCost);
                $('#dialog_traveltimecost').val(wo.TravelTimeCost == 0 ? "" : wo.TravelTimeCost);
                $('#dialog_laborcost').val(wo.LaborCost == 0 ? "" : wo.LaborCost);
                $('#dialog_hourlyrate').val(wo.HourlyRate == 0 ? "" : wo.HourlyRate);
                $('#dialog_invoicenumber').val(wo.InvoiceNumber);
                if (typeof customer !== 'undefined') {
                    customer.companyName = wo.CustomerName;
                    customer.companyCode = wo.CustomerCode;
                    customer.setData('companyCode', wo.CustomerCode);
                    customer.autoUpdates = wo.AutoText;
                }
                $('#dialog_partsexpecteddate').val(wo.PartsExpectedDateStr);
                if (new Date(wo.PartsExpectedDateStr) < new Date(currentdate))
                    $('#dialog_partsexpecteddate').css("color", "red");
                else
                    $('#dialog_partsexpecteddate').css("color", "unset");
                $('#dialog_lastlabordate').val(wo.LastLaborDateStr);
                $('#dialog_inspectionrequired').prop('checked', wo.InspectionRequired);
                $('#dialog_inspectioncount').text(wo.InspectionCount).css('color', 'unset');
                if (wo.InspectionRequired && wo.InspectionCount > 0 && wo.InspectionTemplateId > 0) {
                    $('#dialog_inspectioncount').css('color', wo.RequiredInspectionCompleted ? '#2eda2e' : 'red');
                }
                $('#dialog_alternatestatus').val(wo.AlternateStatus);

                $('#dialog_location').dropdownVal("" + wo.LocationId);
                $('#dialog_department').dropdownVal("" + wo.DepartmentId);

                if (AllowCustomer) {
                    $('#dialog_estimatestatus').text(woestimateobj.getEstimateStatus(wo.EstimateStatus));
                }

                getLaborCost(false);
                $('#dialog_assignto').dropdownSource([{ value: wo.AssignedTo.toLowerCase(), DisplayName: wo.AssignedTo == "" ? " " : wo.AssignedToName }]).dropdownVal(wo.AssignedTo.toLowerCase());
                $('#dialog_advisor').dropdownSource([{ value: wo.AdvisorId, DisplayName: wo.AdvisorId == "" ? " " : wo.AdvisorName }]).dropdownVal(wo.AdvisorId);
                getWorkOrderTypes();
                getPartsStatuses();
                getComments(true);
                if (AllowCommunicate)
                    getCommunications(true);

                if (WOReadOnly || (!IsAdmin && wo.Completed && !AllowReopenWorkorders)) {
                    $('.iconsave').css("display", 'none');
                    $('#td_attachment input').attr('disabled', true);
                }
                else {
                    $('.iconsave').css("display", '');
                    $('#td_attachment input').attr('disabled', false);
                }

                if (IsAdvisor) {
                    if (!wo.CommunicationAcknowledged)
                        updateCommunicationAcknowledged(workorderid, true);
                    if (!wo.EstimateAcknowledged)
                        updateEstimateAcknowledged(workorderid, true);
                }

            }, function (err) {
                loading = false;
                showLoading(false);
            });
        }


        function setMachineInfo(asset) {
            if (asset) {
                $('#spassignedasset').text("" + (asset.DisplayName || asset.AssetName || asset.Name));
                $('#dialog_vin').text(asset.VIN);
                $('#dialog_make').text("" + (asset.Make || asset.MakeName));
                $('#dialog_model').text("" + (asset.Model || asset.ModelName));
                $('#dialog_type').text("" + (asset.MachineType || asset.TypeName));

                if (meterType === "") {
                    meterType = asset.OnRoad ? "Odometer" : "HourMeter";
                }

                if (asset.CurrentHours) {
                    if (($('#dialog_hourmeter').val() === "" || $('#dialog_hourmeter').val() === "0") && (meterType == "HourMeter" || meterType == "Both")) {
                        $('#dialog_hourmeter').val(asset.CurrentHours.Corrected > 0 ? Math.round(asset.CurrentHours.Corrected) : "");
                    }
                }
                if (asset.CurrentOdometer) {
                    if (($('#dialog_odometer').val() === "" || $('#dialog_odometer').val() === "0") && (meterType == "Odometer" || meterType == "Both")) {
                        $('#dialog_odometer').val(asset.CurrentOdometer.Corrected > 0 ? Math.round(asset.CurrentOdometer.Corrected) : "");
                    }
                }

                if (asset.OnRoad) {
                    if (asset.CurrentOdometer)
                        $("#dialog_codometer").text("" + Math.round(asset.CurrentOdometer.Corrected));
                    else
                        $("#dialog_codometer").text("");
                    $("#trcodometer").show();
                    $("#trchours").hide();
                } else {
                    if (asset.CurrentHours)
                        $("#dialog_chours").text("" + Math.round(asset.CurrentHours.Corrected));
                    else
                        $("#dialog_chours").text("");
                    $("#trcodometer").hide();
                    $("#trchours").show();
                }

                $('#dialog_metertype').dropdownVal(meterType);
                setMeterType();
            }
            else {
                $('#spassignedasset').text(GetTextByKey("P_MD_UNASSIGNED", 'Unassigned')).data("aid", -1);
                $('#dialog_vin').text('');
                $('#dialog_make').text('');
                $('#dialog_model').text('');
                $('#dialog_type').text('');
            }
        }

        function GetAssetContacts() {
            if (!machineid)
                return;
            var loc = $('#dialog_location').dropdownVal();
            var dep = $('#dialog_department').dropdownVal();
            worequest("GetAssetContacts", JSON.stringify([machineid, loc, dep]), function (data) {
                if (data && data.length > 0) {
                    contacts = data;
                    showContacts();
                    showAdvisors();
                }
            }, function (err) {
            });
        }

        function showContacts() {
            if ((!workorderid && workorderid != "" && !workorderdata) || !contacts) return;
            var exists = false;
            var sel = null;
            if (workorderdata)
                sel = workorderdata.AssignedTo;
            if (!sel || sel == "" || sel == "-1")
                exists = true;

            var selector = $("#dialog_assignto");
            var selCurrent = selector.val();
            var source = [{ value: '', DisplayName: ' ' }];
            for (var i = 0; i < contacts.length; i++) {
                var kv = contacts[i];
                if (!kv.AssignedWorkOrders) continue;
                kv.value = kv.IID.toLowerCase();
                source.push(kv);

                if (!exists && sel.toLowerCase() == kv.IID.toLowerCase())
                    exists = true;
            }
            if (!exists) {
                source.push({ value: workorderdata.AssignedTo.toLowerCase(), DisplayName: workorderdata.AssignedToName });
            }
            $('#dialog_assignto').dropdownSource(source);
            if (sel && sel != "")
                selector.dropdownVal(sel.toLowerCase());
            else if (selCurrent)
                selector.dropdownVal(selCurrent);
        }

        function showAdvisors() {//使用contacts的数据
            if ((!workorderid && workorderid != "" && !workorderdata) || !contacts) return;
            var exists = false;
            var sel = null;
            if (workorderdata)
                sel = workorderdata.AdvisorId;
            if (!sel && $.isGuid(sel))
                sel = sel.toLowerCase();
            if (!sel || sel == "" || sel == "-1")
                exists = true;

            var selector = $("#dialog_advisor");
            var selCurrent = selector.dropdownVal();
            var source = [{ value: '', DisplayName: ' ' }];
            for (var i = 0; i < contacts.length; i++) {
                var kv = contacts[i];
                if (kv.ContactType != 7) continue;
                kv.value = kv.IID.toLowerCase();
                source.push(kv);

                if (!exists && sel.toLowerCase() == kv.IID.toLowerCase())
                    exists = true;
            }
            if (!exists) {
                source.push({ value: workorderdata.AdvisorId, DisplayName: workorderdata.AdvisorName });
            }
            selector.dropdownSource(source);
            if (sel && sel != "")
                selector.dropdownVal(sel);
            else if (selCurrent)
                selector.dropdownVal(selCurrent);
        }

        function getWorkorderParams() {
            worequest("GetWorkorderParams", null, function (data) {
                if (!data || typeof (data) === "string") {
                    return;
                }
                WorkorderParams = data;

            }, function (err) {
            });
        }

        var allWorkOrderStatuses = [];
        var completedWorkOrderStatuses = [];
        var uncompletedWorkOrderStatuses = [];
        function getWorkOrderStatuses() {
            worequest("GetWorkOrderStatuses", null, function (data) {
                if (!data || typeof (data) === "string") {
                    return;
                }

                for (var i = 0; i < data.length; i++) {
                    var s = data[i];
                    allWorkOrderStatuses.push(s);
                    if (s.Completed)
                        completedWorkOrderStatuses.push(s);
                    else
                        uncompletedWorkOrderStatuses.push(s);
                }
                showWorkOrderStatusSource();
                $('#dialog_completed_status').dropdownSource(completedWorkOrderStatuses);

            }, function (err) {
            });
        }

        function showWorkOrderStatusSource() {
            var statuses = allWorkOrderStatuses;
            if (workorderdata && !workorderdata.CanClose)
                statuses = uncompletedWorkOrderStatuses;

            var source = [{ Id: '-1', Name: ' ' }];
            var defaultOnOpenStatus = "-1";
            var exists = false;
            for (var i = 0; i < statuses.length; i++) {
                var s = statuses[i];
                if (s.DefaultOnOpen)
                    defaultOnOpenStatus = s.Id;

                if (workorderdata && workorderdata.Status == s.Id) {
                    exists = true;
                }
                source.push(s);
            }

            $('#dialog_status').dropdownSource(source);
            if (workorderdata) {
                if (!exists && !isNaN(workorderdata.Status)) {
                    source.push({
                        Id: workorderdata.Status,
                        Name: workorderdata.StatusName,
                        Color: workorderdata.StatusColor,
                        StatusType: workorderdata.StatusType
                    });
                }
                $('#dialog_status').dropdownVal(workorderdata.Status)
            }
            else
                $('#dialog_status').dropdownVal(defaultOnOpenStatus);
        }

        var workOrderTypes = null;
        function getWorkOrderTypes() {
            if (workOrderTypes != null) {
                if (workorderdata && workOrderTypes.indexOf(workorderdata.WorkOrderType) < 0) {
                    workOrderTypes.push(workorderdata.WorkOrderType);
                    workOrderTypes.sort();
                    var source = [];
                    for (var type of workOrderTypes) {
                        source.push({ value: type });
                    }

                    $('#dialog_wotype').dropdownSource(source);
                }
                return;
            }
            worequest("GetWorkOrderTypes", null, function (data) {
                if (!data || typeof (data) === "string") {
                    return;
                }
                workOrderTypes = data;

                var source = [];
                for (var type of data) {
                    source.push({ value: type });
                }

                $('#dialog_wotype').dropdownSource(source);

                if (workorderdata)
                    $('#dialog_wotype').dropdownVal(workorderdata.WorkOrderType);

            }, function (err) {
            });
        }

        var partsStatuses = null;
        function getPartsStatuses() {
            if (partsStatuses != null) {
                if (workorderdata && partsStatuses.indexOf(workorderdata.PartsStatus) < 0) {
                    partsStatuses.push(workorderdata.PartsStatus);
                    partsStatuses.sort();
                    var source = [];
                    for (var type of partsStatuses) {
                        source.push({ value: type });
                    }

                    $('#dialog_partsstatus').dropdownSource(source);
                }
                return;
            }
            worequest("GetPartsStatuses", null, function (data) {
                if (!data || typeof (data) === "string") {
                    return;
                }
                partsStatuses = data;

                var source = [];
                for (var type of data) {
                    source.push({ value: type });
                }

                $('#dialog_partsstatus').dropdownSource(source);

                if (workorderdata)
                    $('#dialog_partsstatus').dropdownVal(workorderdata.PartsStatus);

            }, function (err) {
            });
        }

        var allcomponents;
        var londingcomp = false;
        function GetComponents() {
            if (londingcomp) return;
            londingcomp = true;
            worequest("GetComponents", 0, function (data) {
                londingcomp = false;
                if (!data || typeof (data) === "string") {
                    return;
                }

                var source = [];
                for (var type of data) {
                    source.push({ value: type });
                }
                allcomponents = source;

                $('#dialog_wocomponent').dropdownSource(source);

                if (workorderdata)
                    $('#dialog_wocomponent').dropdownVal(workorderdata.Component);

            }, function (err) {
                londingcomp = false;
            });
        }

        var alljobsites;
        var londingjobsites = false;
        function GetJobsites() {
            if (londingjobsites) return;
            londingjobsites = true;
            worequest("GetJobsites", null, function (data) {
                londingjobsites = false;
                if (!data || typeof (data) === "string") {
                    return;
                }
                data.splice(0, 0, { ID: -1, Name: " " })
                alljobsites = data;
                $('#dialog_billtojob').dropdownSource(data);

                if (workorderdata)
                    $('#dialog_billtojob').dropdownVal(workorderdata.BillToJob);

            }, function (err) {
                londingjobsites = false;
            });
        }

        var allsalespersons;
        var londingsalespersons = false;
        function getSalespersons() {
            if (londingsalespersons) return;
            londingsalespersons = true;
            worequest("GetSalespersons", null, function (data) {
                londingsalespersons = false;
                if (!data || typeof (data) === "string") {
                    return;
                }
                data.splice(0, 0, { Key: "", Value: " " })
                allsalespersons = data;
                $('#dialog_salesperson').dropdownSource(data);

                if (workorderdata)
                    $('#dialog_salesperson').dropdownVal(workorderdata.SalespersonId);

            }, function (err) {
                londingsalespersons = false;
            });
        }

        var allisptemplates;
        var londingisptemplates = false;
        function getInspectionTemplateItems() {
            if (londingisptemplates) return;
            londingisptemplates = true;
            worequest("GetInspectionTemplateItems", null, function (data) {
                londingisptemplates = false;
                if (!data || typeof (data) === "string") {
                    return;
                }
                data.splice(0, 0, { Key: "", Value: " " })
                allisptemplates = data;
                $('#dialog_isptemplate').dropdownSource(data);

                if (workorderdata)
                    $('#dialog_isptemplate').dropdownVal(workorderdata.InspectionTemplateId);

            }, function (err) {
                londingisptemplates = false;
            });
        }


        function getLocationsAndDepartments() {
            worequest("GetLocationsAndDepartments", null, function (data) {
                if (!data || typeof (data) === "string") {
                    return;
                }

                var locs = [{ ID: '-1', Name: ' ', html: '&nbsp;' }];
                var depts = [{ Id: '-1', Name: ' ', html: '&nbsp;' }];

                if (data.Locations && data.Locations.length > 0) {
                    for (var i = 0; i < data.Locations.length; i++) {
                        var s = data.Locations[i];
                        if (s.PId > 0) {
                            s.html = '&nbsp;&nbsp;&nbsp;&nbsp;' + s.Name;
                        } else {
                            s.html = s.Name;
                        }
                        locs.push(s);
                    }
                }
                if (data.Departments && data.Departments.length > 0) {
                    for (var i = 0; i < data.Departments.length; i++) {
                        var s = data.Departments[i];
                        if (s.PId > 0) {
                            s.html = '&nbsp;&nbsp;&nbsp;&nbsp;' + s.Name;
                        } else {
                            s.html = s.Name;
                        }
                        depts.push(s);
                    }
                }
                $('#dialog_location').dropdownSource(locs);
                $('#dialog_department').dropdownSource(depts);
                if (workorderdata) {
                    $('#dialog_location').dropdownVal(workorderdata.LocationId);
                    $('#dialog_department').dropdownVal(workorderdata.DepartmentId);
                }
            }, function (err) {
            });
        }


        function getLaborCost(isassignto, istotalcost) {
            if (isassignto === true) {
                $('#dialog_hourlyrate').val("0");
                var contact = $("#dialog_assignto").data('dropdown').selected;
                if (contact && contact.ContactType === 6) {
                    $('#dialog_hourlyrate').val(contact.HourlyRate);
                }
            }

            var hourlyrate = $('#dialog_hourlyrate').val();
            var time = $('#dialog_timetocomplete').val();
            var labor = 0;
            if (hourlyrate !== "" && !isNaN(hourlyrate) && time !== "" && !isNaN(time))
                labor = eval(hourlyrate) * eval(time);
            $('#dialog_laborcost').val(labor);
            if (isassignto || istotalcost)
                getTotalCost();
        }

        function getTotalCost() {
            //if (segmentdata && segmentdata.length > 0)
            //    return;
            if (wosegmentobj && wosegmentobj.hasSegment())
                return;
            var othercost = $('#dialog_othercost').val();
            var partscost = $('#dialog_partscost').val();
            var traveltimecost = $('#dialog_traveltimecost').val();
            var laborcost = $('#dialog_laborcost').val();
            var totalcost = 0;
            if (othercost !== "" && !isNaN(othercost))
                totalcost += eval(othercost);
            if (partscost !== "" && !isNaN(partscost))
                totalcost += eval(partscost);
            if (traveltimecost !== "" && !isNaN(traveltimecost))
                totalcost += eval(traveltimecost);
            if (laborcost !== "" && !isNaN(laborcost))
                totalcost += eval(laborcost);
            $('#dialog_workordercosts').val(totalcost.toFixed(2));
        }

        function OnSave(exit, callback) {
            var item = {
                'WorkOrderType': $.trim($('#dialog_wotype').dropdownVal()),
                'PartsOrderNumber': $.trim($('#dialog_partsordernumber').val()),
                'PartsStatus': $.trim($('#dialog_partsstatus').dropdownVal()),
                'Component': $.trim($('#dialog_wocomponent').dropdownVal()),
                'AssignedTo': $.trim($('#dialog_assignto').dropdownVal()),
                'Description': $.trim($('#dialog_description').val()),
                'NextFollowUpDate': $('#dialog_nextfollowupdate').val(),
                'DueDate': $('#dialog_duedate').val(),
                'CompleteDate': $('#dialog_completeddate').val(),
                'WorkOrderTotalCost': $.trim($('#dialog_workordercosts').val()),
                'HoursToComplete': $.trim($('#dialog_timetocomplete').val()),
                'LocationId': $.trim($('#dialog_location').dropdownVal()),
                'DepartmentId': $.trim($('#dialog_department').dropdownVal()),
                'AdvisorId': $.trim($('#dialog_advisor').dropdownVal()),
                'InternalID': $.trim($('#dialog_internalid').val()),
                'PONumber': $.trim($('#dialog_ponumber').val()),
                'Notes': $.trim($('#dialog_notes').val()),
                'MeterType': $('#dialog_metertype').dropdownVal(),
                'HourMeter': $('#dialog_hourmeter').val(),
                'Odometer': $('#dialog_odometer').val(),
                'OdometerUnits': $('#dig_odometeruom').dropdownVal(),
                'OtherCost': $.trim($('#dialog_othercost').val()),
                'PartsCost': $.trim($('#dialog_partscost').val()),
                'TravelTimeCost': $.trim($('#dialog_traveltimecost').val()),
                'LaborCost': $.trim($('#dialog_laborcost').val()),
                'HourlyRate': $.trim($('#dialog_hourlyrate').val()),
                'InvoiceNumber': $.trim($('#dialog_invoicenumber').val()),
                'CustomerId': customerid,
                'CustomerName': $.trim($('#dialog_custcustomername').text()),
                'AutoText': customer?.autoUpdates,
                'PartsExpectedDate': $('#dialog_partsexpecteddate').val(),
                'LastLaborDate': $('#dialog_lastlabordate').val(),
                'InspectionRequired': $('#dialog_inspectionrequired').prop('checked'),
                'AlternateStatus': $.trim($('#dialog_alternatestatus').val()),
                'Billable': $('#dialog_billable').prop('checked'),
                'BillToJob': $('#dialog_billtojob').dropdownVal(),
                'SalespersonId': $('#dialog_salesperson').dropdownVal(),
                'InspectionTemplateId': $('#dialog_isptemplate').dropdownVal()
            };
            var s = $('#dialog_status').data('dropdown').selected;
            if (s) {
                item.Status = s.Id;
                item.StatusType = s.StatusType;
                item.StatusName = s.Name;
                item.StatusAutoText = s.AutoText;
                item.StatusMessage = s.Message;
            }
            item.Contacts = customercontacts;
            item.ContactsClient = customercontacts;
            item.Followers = followers;

            if (!item.CustomerId)
                item.CustomerId = -1;

            var alerttitle;
            if (workorderid && workorderid !== '') {
                item.Id = workorderid;
                alerttitle = GetTextByKey("P_WO_EDITWORKORDER", 'Edit Work Order');
            } else {
                item.Id = -1;
                alerttitle = GetTextByKey("P_WO_ADDWORKORDER", "Add Work Order");
            }

            if (machine == null) {
                showAlert(GetTextByKey("P_WO_ASSETNOTEMPTY", 'Asset cannot be empty.'), alerttitle);
                $('#dialog_machine').focus();
                return;
            }
            else {
                item.AssetID = machine.Id || machine.ID;
                item.VIN = machine.VIN;
                item.AssetName = machine.DisplayName;
            }

            if (item.WorkOrderTotalCost !== "" && isNaN(item.WorkOrderTotalCost)) {
                showAlert(GetTextByKey("P_WO_WORKORDERCOSTSFORMATERROR", 'Work Order Costs format error.'), alerttitle);
                return;
            }

            if (item.OtherCost !== "" && isNaN(item.OtherCost)) {
                showAlert(GetTextByKey("P_WO_OTHERCOSTFORMATERROR", 'Other Cost format error.'), alerttitle);
                return;
            }
            if (item.PartsCost !== "" && isNaN(item.PartsCost)) {
                showAlert(GetTextByKey("P_WO_PARTSCOSTFORMATERROR", 'Parts Cost format error.'), alerttitle);
                return;
            }
            if (item.TravelTimeCost !== "" && isNaN(item.TravelTimeCost)) {
                showAlert(GetTextByKey("P_WO_TRAVELTIMECOSTFORMATERROR", 'Travel Time Cost format error.'), alerttitle);
                return;
            }

            if (item.HoursToComplete !== "" && isNaN(item.HoursToComplete)) {
                showAlert(GetTextByKey("P_WO_TIMETOCOMPLETEFORMATERROR", 'Time To Complete format error.'), alerttitle);
                return;
            }
            if (item.NextFollowUpDate.length > 0) {
                if (!checkDate(item.NextFollowUpDate)) {
                    showAlert(GetTextByKey("P_WO_NEXTFOLLOWUPDATEFORMATERROR", "Next Follow Up Date format error."), alerttitle);
                    return false;
                }
            }
            else {
                item.NextFollowUpDate = "";
            }

            if (item.DueDate.length > 0) {
                if (!checkDate(item.DueDate)) {
                    showAlert(GetTextByKey("P_WO_DUEDATEFORMATERROR", "Due Date format error."), alerttitle);
                    return false;
                }
            }
            else {
                item.DueDate = "";
            }
            if (!item.LocationId || item.LocationId == "") item.LocationId = -1;
            if (!item.DepartmentId || item.DepartmentId == "") item.DepartmentId = -1;

            if (item.CompleteDate.length > 0) {
                if (!checkDate(item.CompleteDate)) {
                    showAlert(GetTextByKey("P_WO_COMPLETEDDATEFORMATERROR", "Completed Date format error."), alerttitle);
                    return false;
                }
            }
            else {
                item.CompleteDate = "";
            }

            if (!item.Description || item.Description.length == 0) {
                showAlert(GetTextByKey("P_WO_DESCRIPTIONCANNOTBEEMPTY", 'Description cannot be empty.'), alerttitle);
                //$('#dialog_description').focus();
                return;
            }

            if (item.MeterType === "HourMeter") {
                if (item.HourMeter !== "" && isNaN(item.HourMeter)) {
                    showAlert(GetTextByKey("P_WO_HOURMETERFORMATERROR", 'Hour Meter format error.'), alerttitle);
                    $('#dialog_hourmeter').focus();
                    return;
                }
            }
            else if (item.MeterType === "Odometer") {
                if (item.Odometer !== "" && isNaN(item.Odometer)) {
                    showAlert(GetTextByKey("P_WO_ODOMETERFORMATERROR", 'Odometer format error.'), alerttitle);
                    $('#dialog_odometer').focus();
                    return;
                }
            }
            else if (item.MeterType === "Both") {
                if (item.HourMeter !== "" && isNaN(item.HourMeter)) {
                    showAlert(GetTextByKey("P_WO_HOURMETERFORMATERROR", 'Hour Meter format error.'), alerttitle);
                    $('#dialog_odometer').focus();
                    return;
                }
                if (item.Odometer !== "" && isNaN(item.Odometer)) {
                    showAlert(GetTextByKey("P_WO_ODOMETERFORMATERROR", 'Odometer format error.'), alerttitle);
                    $('#dialog_odometer').focus();
                    return;
                }
            }
            if (isNaN(item.Status))
                item.Status = -1;

            if (item.Status == 100 || s.StatusType == 100) {
                if (item.CompleteDate === "") {
                    showAlert(GetTextByKey("P_WO_COMPLETEDDATECANNOTBEEMPTY", 'Completed Date cannot be empty.'), alerttitle);
                    $('#dialog_completeddate').focus();
                    return;
                }

                if (item.MeterType === "HourMeter") {
                    if (item.HourMeter === "") {
                        showAlert(GetTextByKey("P_WO_HOURMETERCANNOTBEEMPTY", 'Hour Meter cannot be empty.'), alerttitle);
                        $('#dialog_hourmeter').focus();
                        return;
                    }
                    item.Odometer = -1;
                    item.OdometerUnits = "";
                }
                else if (item.MeterType === "Odometer") {
                    if (item.Odometer === "") {
                        showAlert(GetTextByKey("P_WO_ODOMETERCANNOTBEEMPTY", 'Odometer cannot be empty.'), alerttitle);
                        $('#dialog_odometer').focus();
                        return;
                    }
                    item.HourMeter = -1;
                }
                else if (item.MeterType === "Both") {
                    if (item.HourMeter === "") {
                        showAlert(GetTextByKey("P_WO_HOURMETERCANNOTBEEMPTY", 'Hour Meter cannot be empty.'), alerttitle);
                        $('#dialog_hourmeter').focus();
                        return;
                    }
                    if (item.Odometer === "") {
                        showAlert(GetTextByKey("P_WO_ODOMETERCANNOTBEEMPTY", 'Odometer cannot be empty.'), alerttitle);
                        $('#dialog_odometer').focus();
                        return;
                    }
                }
            }

            if (item.InspectionRequired && (item.Status === 100 || item.StatusType === 100)) {
                if (item.Id === -1 || (workorderdata && workorderdata.InspectionCount === 0)) {
                    showAlert(GetTextByKey('P_WO_INSPECTIONREQUIREDTIP', 'The work order cannot be updated Until an inspection is completed.'), alerttitle);
                    return;
                }
            }

            if (item.CompleteDate !== "" && item.Status !== 100 && item.StatusType !== 100) {
                if (workorderdata && !workorderdata.CanClose)
                    item.CompleteDate = "";
                else {
                    $('#sptitle_completedstatus').text(alerttitle);
                    openCompletedStatusDialog(exit, callback);
                    return;
                }
            }

            if (item.HourMeter === "")
                item.HourMeter = -1;
            if (item.Odometer === "") {
                item.Odometer = -1;
                //item.OdometerUnits = "";
            }

            if (item.WorkOrderTotalCost === "" || item.WorkOrderTotalCost === 0)
                item.WorkOrderTotalCost = -1;
            if (item.HoursToComplete === "" || item.HoursToComplete === 0)
                item.HoursToComplete = -1;

            if (item.OtherCost === "" || item.OtherCost === 0)
                item.OtherCost = -1;
            if (item.PartsCost === "" || item.PartsCost === 0)
                item.PartsCost = -1;
            if (item.TravelTimeCost === "" || item.TravelTimeCost === 0)
                item.TravelTimeCost = -1;
            if (item.LaborCost === "" || item.LaborCost === 0)
                item.LaborCost = -1;
            if (item.HourlyRate === "" || item.HourlyRate === 0)
                item.HourlyRate = -1;

            if (item.InspectionTemplateId === "")
                item.InspectionTemplateId = -1;

            if (item.CompleteDate !== "" && item.CompleteDate !== nowDate) {
                var rst = false;
                var msg = "";
                if ((item.MeterType === "Odometer" || item.MeterType === "Both")
                    && machine.CurrentOdometer && parseFloat(item.Odometer) === Math.round(machine.CurrentOdometer.Corrected)) {
                    if ((item.OdometerUnits.toLowerCase() === "mile" && ['mi', 'm'].indexOf(machine.CurrentOdometer.UOM) >= 0)
                        || (item.OdometerUnits.toLowerCase() === "kilometre" && ['km', 'Kilometres'].indexOf(machine.CurrentOdometer.UOM) >= 0)
                    ) {
                        rst = true;
                        var odoumits = (item.OdometerUnits == "Mile" ? "miles" : "kilometers");
                        msg = 'mileage (' + parseFloat(item.Odometer).toLocaleString() + ' ' + odoumits + ')';
                    }
                }
                if ((item.MeterType === "HourMeter" || item.MeterType === "Both")
                    && machine.CurrentHours && parseFloat(item.HourMeter) === Math.round(machine.CurrentHours.Corrected)) {
                    rst = true;
                    msg = 'hours (' + parseFloat(item.HourMeter).toLocaleString() + ' hours)';
                }

                if (rst) {
                    showConfirm(GetTextByKey("P_WO_THISWORKORDERWASCOMPLETEDTIPS", "This work order was completed on {1} but is using the current {0} is this correct? ").replace('{0}', msg).replace('{1}', item.CompleteDate), alerttitle, function () {
                        checkStatusChange(item, function (phoneemail) {
                            saveWorkOrder(item, alerttitle, exit, callback, phoneemail);
                        });
                    }, function (err) {
                    });
                }
                else
                    checkStatusChange(item, function (phoneemail) {
                        saveWorkOrder(item, alerttitle, exit, callback, phoneemail);
                    });
            }
            else
                checkStatusChange(item, function (phoneemail) {
                    saveWorkOrder(item, alerttitle, exit, callback, phoneemail);
                });
        }

        function checkStatusChange(item, next) {
            onRemoveSelectedAttachment();
            if (AllowCommunicate && !COMMReadOnly && (!workorderdata || item.Status != workorderdata.Status)) {
                showmaskbg(true);
                $('#dialog_statuschange .dialog-title span.title').text(GetTextByKey("P_WO_STATUSCHANGE", 'Status Change') + " - " + item.StatusName);
                $('#dialog_statuschange')
                    .css({
                        'top': (document.documentElement.clientHeight - $('#dialog_statuschange').height()) / 3,
                        'left': (document.documentElement.clientWidth - $('#dialog_statuschange').width()) / 2
                    }).showDialogfixed();

                if (!workorderid || workorderid == "")
                    $("#trselectatta").hide();
                else
                    $("#trselectatta").show();

                $('#dialog_chksendtextmsg').prop('checked', item.StatusAutoText && !COMMReadOnly).prop('disabled', COMMReadOnly).change();
                if (!COMMReadOnly)
                    $('#dialog_textmsg').val(item.StatusMessage);

                $("#btn_savestatuschange").unbind().click(function () {
                    showmaskbg(false);
                    $('#dialog_statuschange').hideDialog();
                    if (next) {
                        var phoneemail = null;
                        if ($('#dialog_chksendtextmsg').prop('checked'))
                            phoneemail = $('#txtphonenum_statuschange').val();
                        next(phoneemail);//需先取txtphonenum_statuschange值,否则会被通知刷新掉
                    }
                });
            }
            else if (next)
                next(null);
        }


        function saveWorkOrder(item, alerttitle, exit, callback, phoneemail) {
            var param = JSON.stringify(item);
            param = htmlencode(param);
            var tempalertids = woalertobj && woalertobj.getalertids();

            showloading(true);
            worequest("SaveWorkOrder", param + String.fromCharCode(170) + JSON.stringify(tempalertids), function (data) {
                showloading(false);
                if (typeof (data) === "string") {
                    showAlert(data, alerttitle);
                } else {
                    var isadd = true;
                    if (workorderid)
                        isadd = false;

                    workorderid = data[0];
                    item.Id = workorderid;
                    resetComments();
                    $(".comm").show();

                    $('#dialog_wonumber').text(data[1]);
                    $('#divwonumber').show();

                    if (isadd) {
                        woalertobj && woalertobj.changewo(workorderid, machineid);
                        wosegmentobj && wosegmentobj.changewo(workorderid, machineid);
                        //GetInvoiceNumber();
                    }

                    if (phoneemail)
                        SendTextMsg(item, phoneemail);

                    if (callback) {
                        callback(item);
                        needRefreshDataOnCancel = true;
                        loadworkorder(workorderid, true);
                        //getWorkOrderTypes();
                        //getPartsStatuses();
                    }
                    else {
                        if (exit == 0) {
                            needRefreshDataOnCancel = true;
                            showAlert(GetTextByKey("P_WO_SAVSUCCESSFULLY", "Saved successfully."), alerttitle);
                            loadworkorder(workorderid, true);
                            //getWorkOrderTypes();
                            //getPartsStatuses();
                        }
                        if (exit == 1)
                            OnExit(exit);
                        else
                            $("#btnSelectAsset").hide();
                    }
                }
            }, function (err) {
                showloading(false);
                showAlert(GetTextByKey("P_WO_FAILEDTOSAVEWORKORDER", 'Failed to save Work Order.'), alerttitle);
            });
        }

        var exited = false;
        function OnExit(type) {
            exited = true;
            workorderid = "";
            clearWorkOrderInfo();
            if (type === 0) {
                if (needRefreshDataOnCancel) {
                    type = 1;
                    needRefreshDataOnCancel = false;
                }
            }
            if (window.parent && typeof window.parent.CloseDialog == 'function')
                window.parent.CloseDialog(type);
            else
                window.location = "maintenance.aspx#nav_workorder";
        }

        function SendTextMsg(wo, phoneemail) {
            var phoneemail = phoneemail;// $('#txtphonenum_statuschange').val();
            if ($.trim(phoneemail) == "") {
                return;
            }

            var phoneemails = phoneemail.split(';');
            var pmemails = [];
            for (var i = 0; i < phoneemails.length; i++) {
                var pm = phoneemails[i];
                if (checkPhoneNumber(pm) || isEmail(pm)) {
                    pmemails.push({ 'Key': pm, 'Value': pm });
                }
                else {
                    if (customercontacts) {
                        for (var j = 0; j < customercontacts.length; j++) {
                            var c = customercontacts[j];
                            if (c.OptOut || c.OptOut_BC) continue;
                            var mp = $.trim(c.MobilePhone);
                            var email = $.trim(c.Email);
                            if (c.Name === pm) {
                                if (c.ContactPreference == "0" && checkPhoneNumber(mp)) {
                                    pmemails.push({ 'Key': mp, 'Value': pm });
                                    break;
                                }
                                if (c.ContactPreference == "1" && isEmail(email)) {
                                    pmemails.push({ 'Key': email, 'Value': pm });
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            var comm = $('#dialog_textmsg').val();
            if ($.trim(comm) == "") {
                //showAlert(GetTextByKey("P_WO_PLEASEINPUTTHEMESSAGE", "Please input the message."), GetTextByKey("P_WO_ERROR", 'Error'));
                return;
            }
            var includeStatusLink = $('#dialog_chkIncludeStatusLink').prop("checked");

            var url = 'AddWorkOrder.aspx';
            var method = 'AddWorkOrderCommunication';
            var data = new FormData();
            data.append('MethodName', method);
            data.append('WorkorderId', wo.Id.Value || wo.Id);
            data.append('PMEmails', JSON.stringify(pmemails));
            data.append('Comment', encodeURIComponent(comm));
            data.append('IncludeStatusLink', includeStatusLink ? "1" : "0");
            if (_selectedattachment) {
                data.append('AttaData', encodeURIComponent(JSON.stringify(_selectedattachment)));
            }
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                processData: false,
                contentType: false,
                cache: false,
                data: data,
                success: function (data) {
                    //$('#mask_over_bg').hide();
                    if (data !== "") {
                        showAlert(data, GetTextByKey("P_WO_ERROR", 'Error'));
                        return;
                    }
                    //getCommunications();
                },
                error: function (request, textStatus, errorThrown) {
                    if (request?.readyState == 0) {
                        console.log(request);
                    } else {
                        writelog_ironintel("onAddMessage", url + ".-1." + method + "." + JSON.stringify(param), JSON.stringify(request), textStatus + errorThrown);
                    }
                }
            });
        }

        function setPhoneNumber_statuschange() {
            if (customercontacts && !COMMReadOnly) {
                var names = "";
                for (var i = 0; i < customercontacts.length; i++) {
                    var c = customercontacts[i];
                    if (c.OptOut || c.OptOut_BC) continue;
                    var mp = $.trim(c.MobilePhone);
                    var email = $.trim(c.Email);
                    if ((c.ContactPreference == "0" && (checkPhoneNumber(mp))
                        || (c.ContactPreference == "1" && isEmail(email)))) {
                        if (names == "")
                            names = c.Name;
                        else
                            names += ";" + c.Name;
                    }
                }
                $('#txtphonenum_statuschange').val(names);
            }
            else
                $('#txtphonenum_statuschange').val("");
        }

        function clearWorkOrderInfo() {
            machine = null;
            $('#spassignedasset').text(GetTextByKey("P_MD_UNASSIGNED", 'Unassigned')).data("aid", -1);
            $('#dialog_vin').text('');
            $('#dialog_make').text('');
            $('#dialog_model').text('');
            $('#dialog_type').text('');
            $("#dialog_clocation").text("");
            $("#dialog_cjobsite").text("");

            contacts = undefined;
            $('#dialog_assignto').dropdownSource([]);
            $('#dialog_advisor').dropdownSource([]);
            $("#btnSelectAsset").hide();
            if (AllowCustomer) {
                $('#dialog_estimatestatus').text("");
            }
            $('#dialog_wonumber').text("");
            $('#divwonumber').hide();
            $('#dialog_wotype').dropdownVal('');
            $('#dialog_partsordernumber').val('');
            $('#dialog_partsstatus').dropdownVal('');
            $('#dialog_wocomponent').dropdownVal('');
            $('#dialog_assignto').dropdownVal('-1');
            $('#dialog_status').dropdownVal('-1');
            $('#dialog_nextfollowupdate').val('');
            $('#dialog_nextfollowupdate').css("color", "unset");
            $('#dialog_duedate').val('');
            $('#dialog_duedate').css("color", "unset");
            $('#dialog_description').val('');
            $('#dialog_workordercosts').val('');
            $('#dialog_timetocomplete').val('');
            $('#dialog_completeddate').val('');
            $('#dialog_location').dropdownVal('-1');
            $('#dialog_department').dropdownVal('-1');
            $('#dialog_advisor').dropdownVal('-1');
            $('#dialog_internalid').val('');
            $('#dialog_ponumber').val('');
            $('#dialog_notes').val('');
            $('#dialog_hourmeter').val('');
            $('#dialog_expectedcost').val('');
            $('#dialog_odometer').val('');
            $('#dig_odometeruom').dropdownVal(systemunitofodometer);

            $('#dialog_billable').prop('checked', false);
            $('#dialog_billtojob').dropdownVal('-1');
            $('#dialog_salesperson').dropdownVal('');

            customerid = null;
            $('#dialog_custcustomername').text('');
            $('#dialog_custcustomercode').text('');
            $('.custcode').hide();
            showCustomerContacts([]);

            $('#dialog_othercost').val('');
            $('#dialog_partscost').val('');
            $('#dialog_laborcost').val('');
            $('#dialog_traveltimecost').val('');
            $('#dialog_hourlyrate').val('');
            $('#dialog_invoicenumber').val('');
            if (typeof customer !== 'undefined') {
                customer.autoUpdates = false;
            }
            $('#dialog_partsexpecteddate').val('');
            $('#dialog_partsexpecteddate').css("color", "unset");
            $('#dialog_lastlabordate').val('');
            $('#dialog_inspectionrequired').prop('checked', false);
            $('#dialog_inspectioncount').text('0').css('color', 'unset');
            $('#dialog_alternatestatus').val('');

            $('#tabAttachments').hide();
            $("#tbAttas").empty();
            $('#tabAssetAttachments').hide();
            $("#tbAssetAttas").empty();
            clearWorkOrderOther();

            resetComments();
            resetCommunications();
            $('#tab_segments .segments_table').remove();
        }

        function loadworkorder(woid, keepinfo) {
            exited = false;
            workorderid = woid;
            allcomponents = null;//这是为null,展开时重新取allcomponents
            if (!keepinfo)
                clearWorkOrderInfo();
            if (workorderid && workorderid !== '') {
                if (!keepinfo) {
                    $("#li_workorder").click();
                    $("#li_segments").data("dataload", false);
                    $("#li_attachments").data("dataload", false);
                    $("#li_inspections").data("dataload", false);
                    $("#li_estimates").data("dataload", false);
                    $("#li_invoices").data("dataload", false);
                }

                $('#spanopenworkorders').hide();
                $(".comm").show();
                $("#li_inspections").show();
                $("#li_estimates").show();
                $("#li_invoices").show();
                //getWorkOrderStatuses();
                OnEdit();
                woalertobj && woalertobj.changewo(workorderid, machineid);
            }
            else {
                $('#spanopenworkorders').show();
                $(".comm").hide();
                $("#li_inspections").hide();
                $("#li_estimates").hide();
                $("#li_invoices").hide();
                OnAdd();
                machineid = "";
            }
        }

        function refreshstatus() {
            getWorkOrderStatuses();
            getWorkorderParams();
        }

        //判断是否显示状态变化弹窗 21749
        function CheckIfShowStatusPopup(requiredFiledChanged) {
            var item = {};
            //if (requiredFiledChanged) {
            //    item = {
            //        'Description': $.trim($('#dialog_description').val()),
            //    };
            //    if (machine == null) {
            //        return;
            //    }
            //    if (!item.Description || item.Description.length == 0) {
            //        return;
            //    }
            //}
            var s = $('#dialog_status').data('dropdown').selected;
            item.Status = s.Id;
            if (AllowCommunicate && !COMMReadOnly && (workorderdata && item.Status != workorderdata.Status)) {//新建WO在Save的时候弹窗
                OnSave(0);
            }
        }

        var inspectionloaded = false;
        function init() {
            if (AllowCustomer) {
                $(".contactinfo").show();
                $(".alternatestatus").show();
            }
            else {
                $(".contactinfo").hide();
                $(".alternatestatus").hide();
            }

            // dropdown

            $('#dialog_status').dropdown([
                { Id: '-1', Name: ' ' }
            ], {
                search: false,
                valueKey: 'Id',
                textKey: 'Name'
            }).on('select', function (_e, st) {
                if (st.Id == 100 || st.StatusType == 100) {
                    $('.span_required').show();
                    if ($('#dialog_completeddate').val() === "")
                        if (workorderdata && !workorderdata.CanClose)
                            $('#dialog_completeddate').val(workorderdata.CompleteDateStr);
                        else
                            $('#dialog_completeddate').val(nowDate);

                    if (machine) {
                        var mtype = $('#dialog_metertype').dropdownVal();
                        if (machine.CurrentHours) {
                            if (($('#dialog_hourmeter').val() === "" || $('#dialog_hourmeter').val() === "0") && (mtype == "HourMeter" || mtype == "Both")) {
                                $('#dialog_hourmeter').val(machine.CurrentHours.Corrected > 0 ? Math.round(machine.CurrentHours.Corrected) : "");
                            }
                        }
                        if (machine.CurrentOdometer) {
                            if (($('#dialog_odometer').val() === "" || $('#dialog_odometer').val() === "0") && (mtype == "Odometer" || mtype == "Both")) {
                                $('#dialog_odometer').val(machine.CurrentOdometer.Corrected > 0 ? Math.round(machine.CurrentOdometer.Corrected) : "");
                            }
                        }
                    }
                } else {
                    $('.span_required').hide();
                    $('#dialog_completeddate').val('');
                }

                CheckIfShowStatusPopup();
            });

            $('#dialog_description').blur(function () {
                setTimeout(function () {
                    if (!exited)
                        CheckIfShowStatusPopup();
                }, 100);
            });

            $('#dialog_completed_status').dropdown([], {
                search: false,
                valueKey: 'Id',
                textKey: 'Name'
            });

            $('#dialog_metertype').dropdown([
                { value: 'HourMeter', text: GetTextByKey('P_WO_HOURMETER', 'Hour Meter') },
                { value: 'Odometer', text: GetTextByKey('P_WO_ODOMETER', 'Odometer') },
                { value: 'Both', text: GetTextByKey('P_WO_BOTH', 'Both') }
            ], {
                selected: 'HourMeter'
            }).on('select', function (_e, type) {
                meterType = type.value;
                setMeterType();
                if (machine) {
                    if (machine.CurrentHours) {
                        if (($('#dialog_hourmeter').val() === "" || $('#dialog_hourmeter').val() === "0") && (meterType == "HourMeter" || meterType == "Both")) {
                            $('#dialog_hourmeter').val(machine.CurrentHours.Corrected > 0 ? Math.round(machine.CurrentHours.Corrected) : "");
                        }
                    }
                    if (machine.CurrentOdometer) {
                        if (($('#dialog_odometer').val() === "" || $('#dialog_odometer').val() === "0") && (meterType == "Odometer" || meterType == "Both")) {
                            $('#dialog_odometer').val(machine.CurrentOdometer.Corrected > 0 ? Math.round(machine.CurrentOdometer.Corrected) : "");
                        }
                    }
                }
            });
            $('#dig_odometeruom').dropdown([
                { value: 'Mile', text: GetTextByKey('P_WO_MILE', 'Mile') },
                { value: 'Kilometre', text: GetTextByKey('P_WO_KILOMETER', 'Kilometer') }
            ], {
                selected: 'Mile',
                disabled: true
            });

            $('#dialog_location').dropdown([
                { ID: '-1', Name: ' ', html: '&nbsp;' }
            ], {
                valueKey: 'ID',
                textKey: 'Name'
            }).on('select', function () {
                GetAssetContacts();
            });

            $('#dialog_department').dropdown([
                { Id: '-1', Name: ' ', html: '&nbsp;' }
            ], {
                valueKey: 'Id',
                textKey: 'Name'
            }).on('select', function () {
                GetAssetContacts();
            });

            $("#dialog_advisor")
                .dropdown([{ value: '', DisplayName: ' ' }], { textKey: 'DisplayName' })
                .on('expand', function () {
                    if (!contacts)
                        GetAssetContacts();
                });


            $("#dialog_assignto")
                .dropdown([{ value: '', DisplayName: ' ' }], { textKey: 'DisplayName' })
                .on('select', function () {
                    getLaborCost(true);
                })
                .on('expand', function () {
                    if (!contacts)
                        GetAssetContacts();
                });

            $('#dialog_wotype').dropdown([], {
                input: true,
                maxlength: 50,
                textKey: 'value'
            });

            $('#dialog_partsstatus').dropdown([], {
                input: true,
                maxlength: 50,
                textKey: 'value'
            });

            $('#dialog_wocomponent').dropdown([{ value: '' }], {
                input: true,
                maxlength: 50,
                textKey: 'value'
            }).on('expand', function () {
                if (!allcomponents)
                    GetComponents();
            });;

            $('#dialog_contactpreference').dropdown([
                { value: '0', text: GetTextByKey('P_CR_TEXT', 'Text') },
                { value: '1', text: GetTextByKey('P_CR_EMAIL', 'Email') },
                { value: '2', text: GetTextByKey('P_CR_PHONE', 'Phone') }
            ]);

            $('#dialog_billtojob').dropdown([{ ID: '', Name: ' ' }], {
                search: true,
                valueKey: 'ID',
                textKey: 'Name'
            }).on('expand', function () {
                if (!alljobsites)
                    GetJobsites();
            });

            $('#dialog_salesperson').dropdown([{ Key: '', Value: ' ' }], {
                search: true,
                valueKey: 'Key',
                textKey: 'Value'
            });

            $('#dialog_isptemplate').dropdown([{ Key: '', Value: ' ' }], {
                search: true,
                valueKey: 'Key',
                textKey: 'Value'
            });


            // end dropdown
            getWorkorderParams();
            getWorkOrderStatuses();
            getWorkOrderTypes();
            getPartsStatuses();
            getLocationsAndDepartments();
            if (!allsalespersons)
                getSalespersons();
            if (!allisptemplates)
                getInspectionTemplateItems();
            if (workorderid && workorderid !== '') {
                $("#li_workorder").click();
                $("#li_segments").data("dataload", false);
                $("#li_attachments").data("dataload", false);
                $("#li_inspections").data("dataload", false);
                $("#li_estimates").data("dataload", false);
                $("#li_invoices").data("dataload", false);

                $(".comm").show();
                $("#li_inspections").show();
                $("#li_estimates").show();
                $("#li_invoices").show();
                OnEdit();
                woalertobj && woalertobj.changewo(workorderid, machineid);
            }
            else {
                $(".comm").hide();
                $("#li_inspections").hide();
                $("#li_estimates").hide();
                $("#li_invoices").hide();
                OnAdd();
                if (machineid !== "")
                    woalertobj && woalertobj.getAssetAlerts(machineid);
            }
            if (machineid !== "") {
                GetOpenWorkOrderID(machineid);
                getAssetDetailInfo(machineid);
            }
        }

        function setMeterType() {
            //$('#tr_hourmeter').css('display', 'none');
            //$('#tr_odometer').css('display', 'none');
            //if (meterType == "HourMeter" || meterType == "Both") {
            //    $('#tr_hourmeter').css('display', '');
            //}
            //if (meterType == "Odometer" || meterType == "Both") {
            //    $('#tr_odometer').css('display', '');
            //}

            if (meterType == "HourMeter" || meterType == "Both") {
                $("#dialog_hourmeter").prop("disabled", false);
            }
            else {
                $("#dialog_hourmeter").prop("disabled", true).val("");
            }

            if (meterType == "Odometer" || meterType == "Both") {
                $("#dialog_odometer").prop("disabled", false);
                $('#dig_odometeruom').dropdownDisabled(false);
            }
            else {
                $("#dialog_odometer").prop("disabled", true).val("");
                $('#dig_odometeruom').dropdownDisabled(true);
            }
        }

        function GetOpenWorkOrderID(mid) {
            $('#spanopenworkorders').css('display', 'none');
            $('#spanopenworkorderstext').text('');

            worequest("GetOpenWorkOrderID", mid, function (data) {
                var ary = [];
                if (data !== "")
                    ary = data.split("|")
                if (ary[0] == mid && ary[1] !== "") {
                    $('#spanopenworkorders').css('display', "");
                    $('#spanopenworkorderstext').text(ary[1]);
                }
                else {
                    $('#spanopenworkorders').css('display', "none");
                    $('#spanopenworkorderstext').text('');
                }
            }, function (err) {
            });
        }

        function updateCommunicationAcknowledged(id, chk) {
            var item = [id, chk];
            var param = JSON.stringify(item);
            param = htmlencode(param);

            worequest('UpdateCommunicationAcknowledged', param, function (data) {
                if (data !== 'OK') {
                    showAlert(data, GetTextByKey("P_WORKORDER", 'Work Order'));
                }
            }, function (err) {
            });
        }

        function updateEstimateAcknowledged(id, chk) {
            var item = [id, chk];
            var param = JSON.stringify(item);
            param = htmlencode(param);

            worequest('UpdateEstimateAcknowledged', param, function (data) {
                if (data !== 'OK') {
                    showAlert(data, GetTextByKey("P_WORKORDER", 'Work Order'));
                }
            }, function (err) {
            });
        }

        function OnPrint() {
            var alerttitle = GetTextByKey("P_WO_PRINTWORKORDER", "Print Work Order");
            if (!workorderid || workorderid === "") {
                showAlert(GetTextByKey("P_WO_SAVEWORKORDERFIRST", "Please save work order first."), alerttitle);
                return;
            }
            window.open("../Print.aspx?pt=1&wo=" + workorderid);
        }

        function workorderreportyes() {
            window.open("WorkOrderMaintenance.aspx?tt=1&id=" + workorderid + "&t=3&rt=f");
        }

        function workorderreportno() {
            window.open("WorkOrderMaintenance.aspx?tt=0&id=" + workorderid + "&t=3&rt=f");
        }


        function OnExportReport() {
            if (!(/*IsAdmin && */AllowCustomer)) {
                return;
            }
            var alerttitle = GetTextByKey("P_WO_WORKORDERREPORT", "Work Order Report");
            if (!workorderid || workorderid === "") {
                showAlert(GetTextByKey("P_WO_SAVEWORKORDERFIRST", "Please save work order first."), alerttitle);
                return;
            }
            showThreeButtonConfirm(GetTextByKey("P_WO_WORKORDERREPORT_CONFIM", "Should only customer facing items be included?"), alerttitle, workorderreportyes, workorderreportno);
            //window.open("../Print.aspx?pt=1&wo=" + workorderid);
        }

        function getAssetDetailInfo(mid) {
            $("#dialog_clocation").text("");
            $("#dialog_cjobsite").text("");
            worequest("GetAssetDetailInfo", "" + String.fromCharCode(170) + mid, function (data) {
                if (typeof (data) === "string") {
                    return;
                }
                if (data.ID != machineid)
                    return;

                machine = data;
                setMachineInfo(machine);
                if (data.CurrentLocation) {
                    $("#dialog_clocation").text(data.CurrentLocation.Address);
                }
                $("#dialog_cjobsite").text(data.CurrentJobSiteNames);
            }, function (err) {
            });
        }

        function OnExpend(e) {
            var t = $(e);
            var tid = t.attr("target");
            if (t.hasClass("iconchevrondown")) {
                t.removeClass("iconchevrondown").addClass("iconchevronright");
                $("#" + tid).hide();
            }
            else {
                t.removeClass("iconchevronright").addClass("iconchevrondown");
                $("#" + tid).show();
            }
            saveWorkOrderCollapsed();
        }

        function getMessageStatusHistoryText(p) {
            var getStatusText = function (s) {
                switch (s) {
                    case 0: return GetTextByKey('P_CU_PENDING', 'Pending');
                    case 1: return GetTextByKey('P_WO_SENT', 'Sent');
                    case 5: return GetTextByKey('P_CU_DELIVERYCONFIRMED', 'Delivery Confirmed');
                    case 6: return GetTextByKey('P_CU_RESENT', 'Resent');
                    case 9:
                    case 10:
                    case 412: return GetTextByKey('P_MA_FAILED', 'Failed');
                    default: return GetTextByKey('P_CU_UNKNOWN', 'Unknown');
                }
            };
            var msg = GetTextByKey('P_CU_UPDATESTATUSDESC', 'Status changed from {0} to {1}\nBy {2} on {3}')
                .replace('{0}', getStatusText(p.History.StatusFrom))
                .replace('{1}', getStatusText(p.History.StatusTo))
                .replace('{2}', p.History.UpdatedBy)
                .replace('{3}', p.UpdatedOnStr);
            return msg;
        }

        var dialogAssets;
        var woalertobj = null;
        var woattachmentobj = null;
        var wosegmentobj = null;
        var woestimateobj = null;
        var woinvoiceobj = null;
        var woinspectionobj = null;
        $(function () {
            woalertobj = new $woalert({ parent: $('#tab_alerts'), showloading: function (flag) { showLoading(flag) }, workorderid: workorderid, machineid: machineid, alertids: alertids });
            woattachmentobj = new $woattachment({ parent: $('#tab_attachments'), showloading: function (flag) { showLoading(flag) }, canExport: canExport, workorderid: workorderid, machineid: machineid });
            wosegmentobj = new $wosegment({ parent: $('#tab_segments'), showloading: function (flag) { showLoading(flag) }, workorderid: workorderid });
            woestimateobj = new $woestimate({ parent: $('#tab_estimates'), showloading: function (flag) { showLoading(flag) }, workorderid: workorderid });
            woinvoiceobj = new $woinvoice({ parent: $('#tab_invoices'), showloading: function (flag) { showLoading(flag) }, workorderid: workorderid });
            woinspectionobj = new $woinspection({ parent: $('#tab_inspections'), showloading: function (flag) { showLoading(flag) }, workorderid: workorderid, machineid: machineid });

            InitGridCustomers();
            InitGridSelectedAttachments();

            if (WOReadOnly) {
                $(".iconadd").hide();
                $(".icondelete").hide();
            }

            dialogAssets = new $assetselector('dialog_machines');
            dialogAssets.forceSingle = true;
            dialogAssets.onDialogClosed = function () {
                showmaskbg(false);
            };
            dialogAssets.onOK = function (source, selectedIndex) {
                meterType = "";
                var selectedAsset = null;
                if (selectedIndex >= 0)
                    selectedAsset = source[selectedIndex];
                setMachineInfo(selectedAsset);
                if (selectedAsset) {
                    machineid = selectedAsset.Id;
                    machine = selectedAsset;

                    CheckIfShowStatusPopup();

                    if (!machine.OnRoad && (meterType == "HourMeter" || meterType == "Both")) {
                        $('#dialog_hourmeter').val(machine.EngineHours > 0 ? Math.round(machine.EngineHours) : "");
                    }
                    if (machine.OnRoad && (meterType == "Odometer" || meterType == "Both")) {
                        $('#dialog_odometer').val(machine.Odometer > 0 ? Math.round(machine.Odometer) : "");
                    }

                    GetOpenWorkOrderID(machineid);
                    woalertobj && woalertobj.getAssetAlerts(machineid);
                    getAssetDetailInfo(machineid);
                    GetAssetContacts();
                    $("#li_attachments").data("dataload", false);
                }
                showmaskbg(false);
            };

            $("#btnSelectAsset").click(function () {
                showmaskbg(true);
                dialogAssets.companyId = $('#sel_contractor').val();
                dialogAssets.showSelector();
            });

            //if (!AllowCommunicate) {
            //    $("#divCommunicate").remove();
            //}
            const ui = window['lib-ui'];
            const app = window['lib-app'];
            if (AllowCommunicate) {
                customer = new app.CustomerCommunication({
                    getText: GetTextByKey,
                    autoUpdates: false,
                    statusLink: window.parent.wowidgetobj?.widgets?.CustomerCommunication?.customer?.statusLink ?? false,
                    readonly: WOReadOnly || COMMReadOnly,
                    recordReadonly: !AllowCustomer || WOReadOnly || CRReadOnly,
                    contactCollapserVisible: false,
                    onStatusLinkChanged: function (checked) {
                        var widgetobj = window.parent.wowidgetobj;
                        var customer = widgetobj?.widgets?.CustomerCommunication?.customer;
                        if (customer != null && !customer.freeze) {
                            customer.statusLink = checked;
                            var checklink = widgetobj.popups?.CustomerCommunication?.container?.querySelector('.check-status-link>input');
                            if (checklink != null) {
                                checklink.checked = checked;
                                ui.setTooltip(widgetobj.popups?.CustomerCommunication?.container?.querySelector('.check-status-link'), checked ?
                                    GetTextByKey('P_WO_STATUSLINKINCLUDED', 'Status Link Included') :
                                    GetTextByKey('P_WO_STATUSLINKEXCLUDED', 'Status Link Excluded'));
                            }
                        }
                    },
                    onAddMessage: addWorkOrderCommunication,
                    onUpdateMessageStatus: function (msgs) {
                        if (msgs?.length > 0) {
                            worequest('UpdateMessageStatus', JSON.stringify(msgs), function (data) {
                                if (data !== 'OK') {
                                    ui.showAlert(GetTextByKey('P_WO_ERROR', 'Error'), data, 'error');
                                    return;
                                }
                                getCommunications();
                            });
                        }
                    },
                    onMessageStatusClicked: function (p) {
                        worequest('GetMessageStatusHistory', String(p.Id), function (data) {
                            if (typeof data === 'string') {
                                ui.showAlert(GetTextByKey('P_WO_ERROR', 'Error'), data, 'error');
                                return;
                            }
                            if (data.length > 0) {
                                var msg = data.map(function (p) { return getMessageStatusHistoryText(p) }).join('\n\n');
                                ui.showAlert(data[0].CustomerNumberFormatted, msg);
                            }
                        });
                    },
                    onSave: function (item, add) {
                        if (!add) {
                            contact = customercontacts.filter(function (f) { return f.Id < 0 ? f.Name === item.OldName && f.MobilePhone === item.OldMobilePhone : f.Id === item.Id })[0];
                        }
                        var array = [];
                        for (let c of customercontacts) {
                            if (c === contact) {
                                let ct = {
                                    ...contact,
                                    Name: item.Name,
                                    ContactPreference: item.ContactPreference,
                                    Email: item.Email,
                                    MobilePhone: item.MobilePhone,
                                    OptOut: item.OptOut,
                                    Notes: item.Notes,
                                    SaveToCustomer: item.SaveToCustomer
                                };

                                if (parseInt(ct.ContactPreference) == 0) {
                                    ct.ContactPreferenceStr = GetTextByKey("P_CR_TEXT", "Text");
                                } else if (parseInt(ct.ContactPreference) == 1) {
                                    ct.ContactPreferenceStr = GetTextByKey("P_CR_EMAIL", "Email");
                                } else if (parseInt(ct.ContactPreference) == 2) {
                                    ct.ContactPreferenceStr = GetTextByKey("P_CR_PHONE", "Phone");
                                }
                                array.push(ct)
                            } else {
                                array.push(c);
                            }
                        }
                        if (add) {
                            item.Id = -1;
                            array.push(item);
                        }

                        return new Promise(function (resolve, reject) {
                            SaveWorkorderContact(array, function (data) {
                                if (typeof data === 'string') {
                                    ui.showAlert(GetTextByKey('P_WO_ERROR', 'Error'), data, 'error')
                                    reject();
                                } else {
                                    for (let d of data) {
                                        const c = customercontacts.find(function (c) {
                                            return c.Id < 0 ?
                                                c.Name === d.Name && c.MobilePhone === d.MobilePhone :
                                                c.Id === d.Id
                                        });
                                        if (c != null) {
                                            d.selected = c.selected;
                                        } else {
                                            d.selected = true;
                                        }
                                    }
                                    showCustomerContacts(customercontacts = data);
                                    resolve(data);
                                }
                            });
                        });
                        //showCustomerContacts(customercontacts);
                    },
                    onDelete: function (_op, item, customer) {
                        var index;
                        if (customer) {
                            index = customercontacts.findIndex(function (c) { return c.Id === item.Id });
                        } else {
                            index = customercontacts.findIndex(function (c) { return c.Name === item.Name && c.MobilePhone === item.MobilePhone });
                        }
                        if (index >= 0) {
                            customercontacts.splice(index, 1);
                            SaveWorkorderContact();
                            showCustomerContacts(customercontacts);

                            // from customer record
                            if (customer) {
                                _network.request("Maintenance/AddCustomerRecord.aspx", -1, 'DeleteContact', item.Id, function () { }, function (e) {
                                    console.log(e);
                                    ui.showAlert(GetTextByKey("P_WO_ERROR", 'Error'), GetTextByKey('P_UM_PAGEERROR', 'An unknown error occurred.  Please refresh page.'), 'error');
                                });
                            }
                        }
                    },
                    onChanged: function (source) {
                        customer.contacts = source;
                    },
                    onDeleteFollower: function (_op, f) {
                        var index = followers.findIndex(function (c) { return c.UserIID === f.UserIID });
                        if (index < 0) {
                            return;
                        }
                        followers.splice(index, 1);
                        SaveWorkOrderFollower();
                        showWorkOrderFollowers(followers);
                    },
                    onChangeFollower: function (_op, f, text, email) {
                        var follower = followers.find(function (c) { return c.UserIID === f.UserIID });
                        if (follower != null) {
                            follower.SendText = text;
                            follower.SendEmail = email;
                            SaveWorkOrderFollower();
                            showWorkOrderFollowers(followers);
                        }
                    },
                    onInitFollower: function (selfollowers) {
                        if (isloadfollower && allfollowers?.length > 0) {
                            for (let f of allfollowers) {
                                f.Email = false;
                                f.Text = false;
                                if (selfollowers) {
                                    var tf = selfollowers.find(function (c) { return c.UserIID.toLowerCase() === f.IID.toLowerCase() });
                                    if (tf) {
                                        f.Email = tf.SendEmail;
                                        f.Text = tf.SendText;
                                    }
                                }
                            }
                            return Promise.resolve(allfollowers);
                        }
                        return new Promise(function (resolve) {
                            getAllFollowers(function (data) {
                                if (Array.isArray(data)) {
                                    isloadfollower = true;
                                    allfollowers = data;
                                }
                                for (let f of allfollowers) {
                                    f.Email = false;
                                    f.Text = false;
                                    if (selfollowers) {
                                        var tf = selfollowers.find(function (c) { return c.UserIID.toLowerCase() === f.IID.toLowerCase() });
                                        if (tf) {
                                            f.Email = tf.SendEmail;
                                            f.Text = tf.SendText;
                                        }
                                    }
                                }
                                resolve(data);
                            });
                        });
                    },
                    onAddFollower: function (list) {
                        followers = [];
                        for (let f of list) {
                            let iid = f.IID.toLowerCase();
                            let o = followers?.find(function (a) { return a.UserIID.toLowerCase() === iid });
                            if (o == null) {
                                o = {
                                    Id: -1,
                                    UserIID: f.IID
                                };
                                followers.push(o);
                            }
                            o.Name = f.DisplayName;
                            o.Email = f.ID;
                            o.MobilePhone = f.Mobile;
                            o.SendEmail = f.Email;
                            o.SendText = f.Text;
                        }
                        return new Promise(function (resolve, reject) {
                            SaveWorkOrderFollower(function (data) {
                                if (data !== 'OK') {
                                    ui.showAlert(GetTextByKey("P_WO_ERROR", 'Error'), data, 'error')
                                    reject();
                                } else {
                                    resolve(followers);
                                }
                            });
                        });
                    },
                    onOpenSelectCRContacts: function () {
                        return new Promise(function (resolve) {
                            if (!customerid || customerid === "") {
                                setTimeout(function () { resolve([]) }, 0);
                                return;
                            }
                            getCustomerContacts(customerid, function (data) {
                                resolve(data);
                            });
                        });
                    },
                    onSelectCRContacts: function (list) {
                        showCustomerContacts(list);
                        SaveWorkorderContact();
                    }
                });

                document.querySelector('#communication_holder').append(customer.create());
            }
            internal = new app.InternalComment({
                getText: GetTextByKey,
                readonly: WOReadOnly,
                onAddMessage: openSendICEmail,
                onAddComment: addWorkOrderComment,

                onUpdateMessageStatus: function (msgs) {
                    if (msgs?.length > 0) {
                        worequest('UpdateMessageStatus', JSON.stringify(msgs), function (data) {
                            if (data !== 'OK') {
                                ui.showAlert(GetTextByKey('P_WO_ERROR', 'Error'), data, 'error');
                                return;
                            }
                            getComments();
                        });
                    }
                },
                onMessageStatusClicked: function (p) {
                    worequest('GetMessageStatusHistory', String(p.Id), function (data) {
                        if (typeof data === 'string') {
                            ui.showAlert(GetTextByKey('P_WO_ERROR', 'Error'), data, 'error');
                            return;
                        }
                        if (data.length > 0) {
                            var msg = data.map(function (p) { return getMessageStatusHistoryText(p) }).join('\n\n');
                            ui.showAlert(data[0].CustomerNumberFormatted, msg);
                        }
                    });
                }
            });
            document.querySelector('#communication_holder').append(internal.create());

            init();

            $('#div_container').tab();

            $('#dialog_nextfollowupdate').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]);
                    if (new Date(date) < new Date(currentdate))
                        $('#dialog_nextfollowupdate').css("color", "red");
                    else
                        $('#dialog_nextfollowupdate').css("color", "unset");
                }
            });

            $('#dialog_duedate').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]);
                    if (new Date(date) < new Date(currentdate))
                        $('#dialog_duedate').css("color", "red");
                    else
                        $('#dialog_duedate').css("color", "unset");
                }
            });
            $('#dialog_partsexpecteddate').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]);
                    if (new Date(date) < new Date(currentdate))
                        $('#dialog_partsexpecteddate').css("color", "red");
                    else
                        $('#dialog_partsexpecteddate').css("color", "unset");
                }
            });
            $('#dialog_lastlabordate').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_completeddate').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]);
                }
            });

            $('.span_vieuploadmsg').click(function (ev) {
                if ($('.panel_holder.attuoloadmsgmenus').is(':visible')) {
                    return;
                }
                hidePanels();
                var left = $(this).offset().left;
                var top = $(this).offset().top;
                $('.panel_holder.attuoloadmsgmenus').css({
                    'opacity': 0,
                    'left': left,
                    'right': 'auto',
                    'top': top + $(this).height() + 7
                }).show().animate({ 'opacity': 1 }, 100);
                $('.panel_holder.attuoloadmsgmenus .trigledown').css({
                    'left': left + $(this).width() - $('.panel_holder.attuoloadmsgmenus').offset().left - 14,
                    'right': 'auto'
                });
                return false;
            });

            $('#dialog_segmentcompleteddate').change(function () {
                var date = $('#dialog_segmentcompleteddate').val();
                if (date.length > 0 && checkDate(date)) {
                    $('#dialog_segmentcompleted').prop('checked', true);
                }
            });

            $('#dialog_customer').prop('iframe', true).dialog(function () {
                showmaskbg(false);
            });
            $("#txt_customer_key").keypress(onCustomerKeyPress);

            function resizeContent() {
                $('.tabcontent').css('height', $(window).height() - $('#divcontent').offset().top - 4);
                $('.content_main').css('min-height', 0);
            }

            $("#li_segments").click(function () {
                if (!$("#li_segments").data("dataload")) {
                    if (workorderid && workorderid !== '')
                        wosegmentobj.changewo(workorderid);
                    else
                        wosegmentobj.loadsource();

                    $("#li_segments").data("dataload", true);
                }
            });

            $("#li_attachments").click(function () {
                if (!$("#li_attachments").data("dataload")) {
                    woattachmentobj && woattachmentobj.changewo(workorderid, machineid);
                    $("#li_attachments").data("dataload", true);
                }
            });

            $("#li_inspections").click(function () {
                if (!$("#li_inspections").data("dataload")) {
                    woinspectionobj && woinspectionobj.changewo(workorderid, machineid);
                    $("#li_inspections").data("dataload", true);
                }
            });

            $("#li_estimates").click(function () {
                if (!$("#li_estimates").data("dataload")) {
                    woestimateobj && woestimateobj.changewo(workorderid);
                    $("#li_estimates").data("dataload", true);
                }
            });

            $("#li_invoices").click(function () {
                if (!$("#li_invoices").data("dataload")) {
                    woinvoiceobj && woinvoiceobj.changewo(workorderid);
                    $("#li_invoices").data("dataload", true);
                }
            });

            $("#dialog_invoice_status").change(function () {
                var status = $("#dialog_invoice_status").val();
                if (status == "6")
                    $("#tr_payment").show();
                else
                    $("#tr_payment").hide();

                if (status == "0" || status == "10")
                    $("#dialog_invoice_customervisible").prop('checked', false).attr('disabled', true);
                else
                    $("#dialog_invoice_customervisible").attr('disabled', false);
            });

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

            $('#dialog_selecteattachments').dialog(function () {
                $('#statuschange_maskbg').hide();
            });

            if (!canExport) {
                $('#btnExportReport').hide();
                $('#btnPrint').hide();
            }

            $('#dialog_chksendtextmsg').change(function () {
                var checked = $('#dialog_chksendtextmsg').prop('checked');
                $('#txtphonenum_statuschange').prop('disabled', !checked);
                $('#dialog_chkIncludeStatusLink').prop('disabled', !checked);
                $('#dialog_textmsg').prop('disabled', !checked);
                $('#dialog_variables').prop('disabled', !checked);
                $('#dialog_insertfield').prop('disabled', !checked);
            });
            $('input[placeholder=Search]').attr("placeholder", GetTextByKey("P_AM_SEARCH", "Search"));

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

        function insertfield() {
            var field = $("#dialog_variables").find("option:selected").text();
            $("#dialog_textmsg").focus();
            document.execCommand('insertText', false, field);
        }

        function onmsgreceived(data) {
            console.log(JSON.stringify(data));
            if (data.Message != workorderid)
                return;

            if (data && data.Code == "501")
                loadworkorder(workorderid, true);
            else if (data && data.Code == "502")
                OnExit(0);
            else if (data && (data.Code == "503" || data.Code == "504"))
                getCommunications();
            else if (data && (data.Code == "505"))
                getComments();
            else if (data && (data.Code == "506")) {
                if (workorderid)
                    getWorkOrderContacts(workorderid);
            }
            else if (data && (data.Code == "507")) {
                if (workorderid)
                    getWorkOrderFollowers(workorderid);
            }
            else if (data.Code == "508") {
                woalertobj && woalertobj.changewo(workorderid, machineid);
            }
            else if (data.Code == "509") {
                if ($('#tab_segments').is(':visible'))
                    wosegmentobj && wosegmentobj.changewo(workorderid);
                else
                    $("#li_segments").data("dataload", false);
            }
            else if (data.Code == "510") {
                if ($('#tab_attachments').is(':visible'))
                    woattachmentobj && woattachmentobj.changewo(workorderid, machineid);
                else
                    $("#li_attachments").data("dataload", false);
            }
            else if (data.Code == "511") {
                if ($('#tab_inspections').is(':visible'))
                    woinspectionobj && woinspectionobj.changewo(workorderid);
                else
                    $("#li_inspections").data("dataload", false);

                woalertobj.changewo(workorderid, machineid);

                if ($('#tab_attachments').is(':visible'))
                    woattachmentobj && woattachmentobj.changewo(workorderid, machineid);
                else
                    $("#li_attachments").data("dataload", false);
            }
            else if (data.Code == "512") {
                if ($('#tab_estimates').is(':visible'))
                    woestimateobj && woestimateobj.changewo(workorderid);
                else
                    $("#li_estimates").data("dataload", false);
            }
            else if (data.Code == "513") {
                if ($('#tab_invoices').is(':visible'))
                    woinvoiceobj && woinvoiceobj.changewo(workorderid);
                else
                    $("#li_invoices").data("dataload", false);
            }
        }

        var loadingCount = 0;
        function showLoading(flag) {
            if (flag) {
                loadingCount++;
                $("#dialogattmask").show();
            }
            else {
                loadingCount--;
                if (loadingCount === 0)
                    $("#dialogattmask").hide();
            }
        }

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

        function clearWorkOrderOther() {
            //attachment上传提示信息
            $('.lable_attuploadname').empty();
            $('.span_vieuploadmsg').hide();
            $('.span_attupload').hide();
            $('#attupload_ul').empty();
        }

        function reshowalertgrid() {
            woalertobj && woalertobj.reshowalertgrid();
        }
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div class="function_title">
        <span class="sbutton iconsave" onclick="OnSave(0);" data-lgid="P_WO_SAVE">Save</span>
        <span class="sbutton iconsave" onclick="OnSave(1);" data-lgid="P_WO_SAVE1">Save and Exit</span>
        <span class="sbutton iconexit" onclick="OnExit(0);" data-lgid="P_WO_SAVE2">Exit Without Saving</span>
    </div>
    <div id="div_container">
        <ul id="ul_container" class="tab_header">
            <li id="li_workorder" data-href="tab_workorder" class="selected" data-lgid="P_WORKORDER">Work Order</li>
            <li data-href="tab_alerts" onclick="reshowalertgrid();" data-lgid="P_WO_ALERTS">Alerts</li>
            <li id="li_segments" data-href="tab_segments" data-lgid="P_WO_SEGMENTS">Segments</li>
            <li id="li_attachments" data-href="tab_attachments" data-lgid="P_WO_ATTACHMENTS">Attachments</li>
            <%if (AllowInspection)
                { %>
            <li id="li_inspections" data-href="tab_inspections" data-lgid="P_WO_INSPECTIONS">Inspections</li>
            <%} %>
            <%if (AllowCustomer)
                { %>
            <li id="li_estimates" data-href="tab_estimates" data-lgid="P_WO_ESTIMATES">Estimates</li>
            <li id="li_invoices" data-href="tab_invoices" data-lgid="P_WO_INVOICES">Invoices</li>
            <%} %>
        </ul>

        <div id="tab_workorder" data-page="tab_workorder" class="tabcontent" style="overflow: auto; min-width: 1610px;">
            <div id="divcontent">
                <div class="edit-content">
                    <div style="width: 920px;">
                        <div class="subtitle">
                            <table>
                                <tr>
                                    <td style="width: 36px;">
                                        <span class="sbutton iconchevrondown" id="spanasset" target="tbasset" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span></td>
                                    <td><span data-lgid="P_WO_ASSETINFORMATION">Asset Information</span></td>
                                    <td style="width: 400px;">
                                        <div id="divwonumber" style="display: none; margin-left: 15px; color: black; font-weight: bold; font-size: 12px;">
                                            <span data-lgid="P_WO_WORKORDERNUMBER_COLON">Work Order Number:</span>
                                            <span id="dialog_wonumber"></span>
                                        </div>
                                        <div id="spanopenworkorders" style="display: none; margin-left: 15px; color: red; font-weight: bold; font-size: 12px;">
                                            <span data-lgid="P_WO_OPENWORKORDERNUMBERS">Open Work Order Numbers:</span>
                                            <span id="spanopenworkorderstext"></span>
                                        </div>
                                    </td>
                                    <td style="width: 120px;">
                                        <button id="input_emaildetails" onclick="openSendEmail();" style="width: unset;" data-lgid="P_WO_EMAILDETAILS">Email Details</button>
                                    </td>
                                    <td style="width: 60px;">
                                        <button id="btnPrint" value="Print" onclick="OnPrint();" style="width: unset; margin-left: 10px;" data-lgid="P_WO_PRINT">Print</button>
                                    </td>
                                    <td id="tdExportReport" style="width: 80px;">
                                        <button id="btnExportReport" value="Report" onclick="OnExportReport();" style="width: unset; margin-left: 10px;" data-lgid="P_WO_WORKORDERREPORT">Work Order Report</button>
                                    </td>
                                    <td></td>
                                </tr>
                            </table>
                            <hr />
                        </div>
                        <table class="workorder_table" id="tbasset">
                            <tr>
                                <td class="label">
                                    <span data-lgid="P_WO_ASSET_COLON">Asset:</span><span class="redasterisk">*</span></td>
                                <td class="cont">
                                    <span id="spassignedasset"></span>
                                    <span class="sbutton iconsearch" id="btnSelectAsset" style="display: none;" data-title-lgid="P_MD_ASSETASSIGNMENT"></span>
                                </td>
                                <td class="label" style="width: 110px;"></td>
                                <td class="cont"></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_VIN_COLON">VIN:</td>
                                <td class="cont" id="dialog_vin"></td>
                                <td class="label" style="width: 110px;" data-lgid="P_WO_ASSETTYPE_COLON">Type:</td>
                                <td class="cont" id="dialog_type"></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_MAKE_COLON">Make:</td>
                                <td id="dialog_make"></td>
                                <td class="label" data-lgid="P_WO_MODEL_COLON">Model:</td>
                                <td id="dialog_model"></td>
                            </tr>
                            <tr id="trchours">
                                <td class="label" data-lgid="P_WO_CURRENTHOURS_COLON">Current Hours:</td>
                                <td id="dialog_chours" colspan="4"></td>
                            </tr>
                            <tr id="trcodometer" style="display: none;">
                                <td class="label" data-lgid="P_WO_CURRENTODOMETER_COLON">Current Odometer:</td>
                                <td id="dialog_codometer" colspan="4"></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_CURRJOBSITE_COLON">Current Jobsite:</td>
                                <td id="dialog_cjobsite"></td>
                                <td class="label" data-lgid="P_WO_CURRLOCATION_COLON">Current Location:</td>
                                <td id="dialog_clocation"></td>
                            </tr>
                        </table>

                        <div class="subtitle contactinfo" style="display: none;">
                            <span class="sbutton iconchevronright" id="spancustomer" target="tbcustomer" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span>
                            <span data-lgid="P_WO_CONTACTINFORMATION">Contact Information</span>
                            <hr />
                        </div>
                        <table class="workorder_table" style="display: none;" id="tbcustomer">
                            <tr>
                                <td class="label" data-lgid="P_CR_COMPANYNAME_COLON" style="white-space: nowrap;">Company Name:</td>
                                <td>
                                    <span id="dialog_custcustomername"></span>
                                    <span class="label custcode" data-lgid="P_CR_COMPANYCODE_COLON" style="white-space: nowrap; margin-left: 50px; display: none;">Company Code:</span>
                                    <span id="dialog_custcustomercode" class="custcode" style="display: none;"></span>
                                    <%if (!CRReadOnly)
                                        {%>
                                    <span class="sbutton iconsearch" id="btnaddcustomer" onclick="onSelectCustomer()" data-title-lgid="P_WO_CONTACTINFORMATION" title="Select Customer"></span>
                                    <%}%>
                                </td>
                            </tr>
                        </table>

                        <div class="subtitle">
                            <span class="sbutton iconchevrondown" id="spansummary" target="tbsummary" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span>
                            <span data-lgid="P_WO_SUMMARY">Summary</span>
                            <hr />
                        </div>
                        <table class="workorder_table" id="tbsummary" style="position: relative">
                            <tr>
                                <td class="label"></td>
                                <td class="cont"></td>
                                <td class="label"></td>
                                <td class="cont"></td>
                            </tr>
                            <tr>
                                <td class="label" style="vertical-align: top;">
                                    <span data-lgid="P_WO_DESCRIPTION_COLON">Description:</span><span class="redasterisk">*</span></td>
                                <td colspan="3">
                                    <textarea id="dialog_description" maxlength="1000" tabindex="2" style="width: 703px; height: 80px;"></textarea></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_INSPECTIONREQUIRED_COLON">Inspection Required:</td>
                                <td class="cont">
                                    <div style="float: left; width: 30px;">
                                        <input type="checkbox" id="dialog_inspectionrequired" style="width: auto; margin-left: 5px;" tabindex="2" />
                                    </div>
                                    <div style="float: left;">
                                        <div id="dialog_isptemplate" tabindex="2" class="dropdown" style="width: 210px;"></div>
                                    </div>
                                </td>
                                <td class="label" data-lgid="P_WO_INSPECTIONCOMPLETED_COLON">Inspection Completed:</td>
                                <td class="cont">
                                    <label id="dialog_inspectioncount" style="font-weight: bold;"></label>
                                </td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_STATUS_COLON">Status:</td>
                                <td>
                                    <div id="dialog_status" tabindex="2" class="dropdown"></div>
                                </td>
                                <td class="label" data-lgid="P_WO_ASSIGNEDTO_COLON">Assigned To:</td>
                                <td>
                                    <div id="dialog_assignto" tabindex="2" class="dropdown"></div>
                                </td>
                            </tr>
                            <tr>
                                <td class="label">
                                    <span data-lgid="P_WO_COMPLETEDDATE_COLON">Completed Date:</span><span class="span_required redasterisk" style="display: none;">*</span>
                                </td>
                                <td>
                                    <input type="text" id="dialog_completeddate" maxlength="200" tabindex="2" autocomplete="off" /></td>
                                <td class="label" data-lgid="P_WO_DUEDATE_COLON">Due Date:</td>
                                <td>
                                    <input type="text" id="dialog_duedate" tabindex="2" maxlength="200" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_METERTYPE_COLON">Meter Type:</td>
                                <td>
                                    <div id="dialog_metertype" tabindex="2" class="dropdown"></div>
                                </td>
                                <td class="label" data-lgid="P_WO_WORKORDERTYPE_COLON">Work Order Type:</td>
                                <td>
                                    <div id="dialog_wotype" tabindex="2" class="dropdown"></div>
                                </td>
                            </tr>
                            <tr id="tr_hourmeter">
                                <td class="label">
                                    <span data-lgid="P_WO_HOURMETER_COLON">Hour Meter:</span><span class="span_required redasterisk" style="display: none;">*</span></td>
                                <td>
                                    <input type="text" id="dialog_hourmeter" maxlength="12" tabindex="2" autocomplete="off" /></td>
                                <td class="label" data-lgid="P_WO_PARTSORDERNUMBER_COLON">Parts Order Number:</td>
                                <td>
                                    <input type="text" id="dialog_partsordernumber" tabindex="2" maxlength="50" autocomplete="off" />
                                </td>
                            </tr>
                            <tr id="tr_odometer">
                                <td class="label">
                                    <span data-lgid="P_WO_ODOMETER_COLON">Odometer:</span><span class="span_required redasterisk" style="display: none;">*</span></td>
                                <td>
                                    <input type="text" id="dialog_odometer" disabled="disabled" maxlength="12" tabindex="2" style="width: 147px;" autocomplete="off" />
                                    <div id="dig_odometeruom" style="width: 90px; display: inline-block" tabindex="2" class="dropdown"></div>
                                </td>
                                <td class="label" data-lgid="P_WO_PARTSSTATUS_COLON">Parts Status:</td>
                                <td>
                                    <div id="dialog_partsstatus" tabindex="2" class="dropdown"></div>
                                </td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_LOCATION_COLON">Location:</td>
                                <td>
                                    <div id="dialog_location" tabindex="2" class="dropdown"></div>
                                </td>
                                <td class="label" data-lgid="P_WO_COMPONENT_COLON">Component:</td>
                                <td>
                                    <div id="dialog_wocomponent" tabindex="3" class="dropdown"></div>
                                </td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_DEPARTMENT_COLON">Department:</td>
                                <td>
                                    <div id="dialog_department" tabindex="2" class="dropdown"></div>
                                </td>
                                <td class="label" data-lgid="P_WO_PARTSEXPECTEDDATE_COLON">Parts Expected Date:</td>
                                <td class="cont">
                                    <input type="text" id="dialog_partsexpecteddate" tabindex="2" maxlength="200" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_ADVISOR_COLON">Advisor:</td>
                                <td>
                                    <%--<input type="text" id="dialog_advisor" maxlength="50" tabindex="2" autocomplete="off" />--%>
                                    <div id="dialog_advisor" tabindex="2" class="dropdown"></div>
                                </td>
                                <td class="label" data-lgid="P_WO_NEXTFOLLOWUPDATE_COLON">Next Follow Up Date:</td>
                                <td class="cont">
                                    <input type="text" id="dialog_nextfollowupdate" tabindex="2" maxlength="200" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_SALESPERSON_COLON">Salesperson:</td>
                                <td colspan="3">
                                    <div id="dialog_salesperson" tabindex="2" class="dropdown"></div>
                                </td>
                            </tr>
                            <tr>
                                <td class="label"><span class="alternatestatus" style="display: none;" data-lgid="P_WO_ALTERNATESTATUS_COLON">Alternate Status:</span></td>
                                <td>
                                    <input type="text" id="dialog_alternatestatus" style="display: none;" class="alternatestatus" maxlength="30" tabindex="2" autocomplete="off" /></td>
                                <td class="label" data-lgid="P_WO_LASTLABORDATE_COLON">Last Labor Date:</td>
                                <td class="cont">
                                    <input type="text" id="dialog_lastlabordate" tabindex="2" maxlength="200" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_NOTES_COLON" style="vertical-align: top;">Notes:</td>
                                <td colspan="3">
                                    <textarea id="dialog_notes" maxlength="500" tabindex="3" style="width: 703px; height: 80px;"></textarea></td>
                            </tr>
                        </table>

                        <div class="subtitle">
                            <span class="sbutton iconchevronright" id="spancost" target="tbcost" onclick="OnExpend(this)" style="margin-left: 0; padding-right: 5px;"></span>
                            <span data-lgid="P_WO_COST">Cost</span>
                            <hr />
                        </div>
                        <table class="workorder_table" id="tbcost" style="display: none; position: relative;">
                            <tr>
                                <td class="label" data-lgid="P_PM_EXPECTEDCOST_COLON">Expected Cost:</td>
                                <td class="cont">
                                    <input type="text" id="dialog_expectedcost" disabled="disabled" maxlength="12" tabindex="3" autocomplete="off" /></td>
                                <td class="label" data-lgid="P_WO_WORKORDERTOTALCOST_COLON">Work Order Total Cost ($):</td>
                                <td class="cont">
                                    <input type="text" id="dialog_workordercosts" maxlength="12" tabindex="3" disabled="disabled" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_OTHERCOST_COLON">Other Cost ($):</td>
                                <td>
                                    <input type="text" id="dialog_othercost" maxlength="12" tabindex="3" onblur="getTotalCost();" autocomplete="off" /></td>
                                <td class="label" data-lgid="P_WO_PARTSCOST_COLON">Parts Cost ($):</td>
                                <td>
                                    <input type="text" id="dialog_partscost" maxlength="12" tabindex="3" onblur="getTotalCost();" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_TRAVELTIMECOST_COLON">Travel Time Cost ($):</td>
                                <td>
                                    <input type="text" id="dialog_traveltimecost" maxlength="12" tabindex="3" onblur="getTotalCost();" autocomplete="off" /></td>
                                <td class="label" data-lgid="P_WO_LABORCOST_COLON">Labor Cost ($):</td>
                                <td>
                                    <input type="text" id="dialog_laborcost" maxlength="12" tabindex="3" disabled="disabled" onblur="getTotalCost();" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_HOURLYRATE_COLON">Hourly Rate:</td>
                                <td>
                                    <input type="text" id="dialog_hourlyrate" maxlength="12" tabindex="3" disabled="disabled" autocomplete="off" /></td>
                                <td class="label" data-lgid="P_WO_TIMETOCOMPLATEHOURS_COLON">Labor Hours:</td>
                                <td>
                                    <input type="text" id="dialog_timetocomplete" maxlength="12" tabindex="3" onblur="getLaborCost(false,true);" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_INVOICENUMBER_COLON">Invoice Number:</td>
                                <td>
                                    <input type="text" id="dialog_invoicenumber" maxlength="50" tabindex="3" autocomplete="off" />
                                    <%--<select id="dialog_invoicenumber" tabindex="3" style="height: 22px; width: 244px;"></select>--%>
                                </td>
                                <%if (AllowCustomer)
                                    { %>
                                <td class="label" data-lgid="P_WO_ESTIMATESTATUS_COLON">Estimate Status:</td>
                                <td rowspan="3" style="vertical-align: top">
                                    <span id="dialog_estimatestatus"></span></td>
                                <%} %>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_INTERNALID_COLON">Internal ID:</td>
                                <td>
                                    <input type="text" id="dialog_internalid" maxlength="50" tabindex="3" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_PONUMBER_COLON">PO Number:</td>
                                <td>
                                    <input type="text" id="dialog_ponumber" maxlength="50" tabindex="3" autocomplete="off" /></td>
                            </tr>
                            <tr>
                                <td class="label" data-lgid="P_WO_BILLABLE_COLON">Billable:</td>
                                <td>
                                    <input type="checkbox" id="dialog_billable" tabindex="3" autocomplete="off" /></td>
                                <td class="label" data-lgid="P_WO_BILLTOJOB_COLON">Bill to job:</td>
                                <td>
                                    <div id="dialog_billtojob" tabindex="3" class="dropdown"></div>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div style="position: absolute; left: 930px; top: 66px; bottom: 10px; width: 670px; min-height: 600px;">
                        <div id="communication_holder" style="position: absolute; left: 0; top: 10px; bottom: 0; display: flex"></div>
                    </div>
                    <div style="clear: both;"></div>
                </div>
            </div>
        </div>

        <div id="tab_alerts" data-page="tab_alerts" class="tabcontent" style="overflow: auto;">
        </div>

        <div id="tab_segments" data-page="tab_segments" class="tabcontent" style="overflow: auto;">
        </div>

        <div id="tab_attachments" data-page="tab_attachments" class="tabcontent" style="overflow: auto;">
        </div>

        <div id="tab_inspections" data-page="tab_inspections" class="tabcontent" style="overflow: auto;">
        </div>

        <div id="tab_estimates" class="edit-content tabcontent" data-page="tab_estimates" style="overflow: auto;">
        </div>

        <div id="tab_invoices" class="edit-content tabcontent" data-page="tab_invoices" style="overflow: auto;">
        </div>
    </div>

    <div id="mask_bg" style="display: none;">
        <div class="loading c-spin"></div>
    </div>

    <div class="dialog" id="sendemailpopupdialog" style="display: none; width: 510px;">
        <div class="dialog-title"><span class="title" data-lgid="P_WO_SENDWORKORDER">Send Work Order</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <table style="line-height: 24px;">
                <tr>
                    <td colspan="2" data-lgid="P_WO_SENDTHISTO">Who do you want to send this to? Select from existing relationships or manual entry.</td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="text" id="sendworkorder_search" style="width: 445px; margin-left: 10px;" placeholder="Search" /></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div id="contactlist" style="height: 240px; width: 450px; margin-left: 10px; margin-right: 10px;"></div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" data-lgid="P_WO_EMAILADDRESSESTIPS">Separate multiple manually entered email addresses with a semi-colon (;).</td>
                </tr>
                <tr>
                    <td style="text-align:right;padding-right:5px;"><span data-lgid="P_WO_OTHEREMAILADDRESS">Other Email Address</span></td>
                    <td>
                        <input type="text" id="sendworkorder_otheremailaddress" style="width: 350px;" autocomplete="off" /></td>
                </tr>
                <%--   <tr>
                    <td><span>Other Text Address</span>
                        <input type="text" id="sendlocation_othertextaddress" style="width: 312px; margin-left: 7px;" autocomplete="off" />
                    </td>
                </tr>--%>
                <tr>
                    <td style="text-align:right;padding-right:5px;"><span data-lgid="P_WO_DESCRIPTION">Description</span></td>
                    <td>
                        <textarea id="sendworkorder_desc" style="width: 350px; height: 80px; resize: none;" tabindex="151"></textarea></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="onSendWorkOrder();" value="OK" data-lgid="P_WO_OK" tabindex="152" />
            <div class="clear"></div>
        </div>
    </div>

    <div class="dialog" id="sendicemailpopupdialog" style="display: none; width: 510px;">
        <div class="dialog-title"><span class="title" data-lgid="P_WO_SENDINTERNALCOMMENTS">Send Internal Comments</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <table style="line-height: 24px;">
                <tr>
                    <td colspan="2" data-lgid="P_WO_SENDTHISTO">Who do you want to send this to? Select from existing relationships or manual entry.</td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="text" id="sendinternalcomments_search" style="width: 445px; margin-left: 10px;" placeholder="Search" /></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div id="iccontactlist" style="height: 240px; width: 440px; margin-left: 10px; margin-right: 10px;"></div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" data-lgid="P_WO_EMAILADDRESSESTIPS">Separate multiple manually entered email addresses with a semi-colon (;).</td>
                </tr>
                <tr>
                    <td style="text-align:right;padding-right:5px;">
                        <span data-lgid="P_WO_OTHEREMAILADDRESS">Other Email Address</span>
                    </td>
                    <td>
                        <input type="text" id="sendic_otheremailaddress" style="width: 350px;" autocomplete="off" /></td>
                </tr>
                <tr>
                    <td style="text-align:right;padding-right:5px;">
                        <span data-lgid="P_WO_PHONENUMBER">Phone Number</span>
                    </td>
                    <td>
                        <input type="text" id="sendic_phonenumber" style="width: 350px;" autocomplete="off" />
                    </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="onSendInternalComments();" value="OK" data-lgid="P_WO_OK" tabindex="152" />
            <div class="clear"></div>
        </div>
    </div>

    <div class="dialog" id="dialog_customer" style="display: none;">
        <div class="dialog-title"><span class="title" data-lgid="P_WO_SELECTCUSTOMER">Select Customer</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <div style="position: relative; width: 500px; margin-top: 4px; float: left">
                <input type="text" placeholder="Search" id="txt_customer_key" disabled="disabled" autocomplete="off" style="width: 100%; padding-right: 28px; height: 25px; line-height: 25px; box-sizing: border-box; text-indent: 4px;" />
                <div 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;" onclick="GetCustomerList()">&#xf002;</div>
            </div>
            <div style="float: left; margin-top: 10px;">
                <input id="chkshowallcust" type="checkbox" onclick="GetCustomerList();" style="margin-left: 20px;" /><label for="chkshowallcust" data-lgid="P_WO_SHOWALLCUSTOMER">Show All Customer</label>
            </div>
            <div style="float: left; margin-top: 10px;">
                <span class="sbutton iconadd" onclick="OnAddCustomer()" data-lgid="P_CR_ADDCUSTOMER">Add Customer</span>
            </div>
            <div style="clear: both;"></div>
            <div id="customerlist" style="height: 400px; width: 750px; 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="OnSetSelectCustomer();" value="OK" data-lgid="P_UM_OK" tabindex="17" />
            <div style="clear: both;"></div>
        </div>
        <div class="maskbg" style="display: none;"></div>
    </div>

    <div class="dialog" id="dialog_addcustomer" style="display: none; height: 100%; border-bottom: 0; border-top: 0;">
        <iframe id="iframecr" src="AddCustomerRecord.aspx" style="width: 100%; height: 100%; display: block; border: none;"></iframe>
        <div class="maskbg" style="display: none;"></div>
    </div>

    <div class="dialog" id="dialog_completedstatus" style="display: none;">
        <div class="dialog-title"><span class="title" id="sptitle_completedstatus" data-lgid="P_WO_ADDWORKORDER">Add Work Order</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <table style="line-height: 30px; margin-left: 10px; margin-right: 10px;">
                <tr>
                    <td>
                        <span data-lgid="P_WO_COMPLETEDDATETIPS">Completed Date has been entered. Plese choose a Completed Status.</span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div id="dialog_completed_status" tabindex="1" class="dropdown" style="width: 320px"></div>
                    </td>
                </tr>
            </table>
        </div>
        <div class="dialog-func">
            <input type="button" value="Cancel" data-lgid="P_UM_CANCEL" class="dialog-close" tabindex="1" style="height: unset;" />
            <input type="button" onclick="onSaveCompletedStatus();" value="OK" data-lgid="P_WO_OK" tabindex="1" />
            <div style="clear: both;"></div>
        </div>
        <div class="maskbg" style="display: none;"></div>
    </div>

    <div class="dialog" id="dialog_statuschange" style="display: none;">
        <div class="dialog-title"><span class="title" data-lgid="P_WO_STATUSCHANGE">Status Change</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <table style="line-height: 30px; margin-left: 10px; margin-right: 10px;">
                <tr>
                    <td style="text-align: right; width: 120px;">
                        <input id="dialog_chksendtextmsg" type="checkbox" style="width: unset;" /></td>
                    <td style="text-align: left;">
                        <label for="dialog_chksendtextmsg" data-lgid="P_WO_SENDUPDATETOCUSTOMER" style="user-select: none;">Send Update To Customer</label></td>
                </tr>
                <tr>
                    <td>
                        <div style="font-size: 20px; margin-right: 5px; float: right;"><em class="spanbtn iconmobile" style="font-weight: 900; font-size: 14px; cursor: default; padding-left: 0; padding-right: 3px; padding-top: 0;"></em></div>
                    </td>
                    <td>
                        <input type="text" id="txtphonenum_statuschange" tabindex="1" autocomplete="off" maxlength="100" style="width: 320px;" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right;">
                        <input id="dialog_chkIncludeStatusLink" type="checkbox" style="width: unset;" /></td>
                    <td style="text-align: left;">
                        <label for="dialog_chkIncludeStatusLink" data-lgid="P_WO_INCLUDESTATUSLINK" style="user-select: none;">Include Status Link</label></td>
                </tr>
                <tr>
                    <td class="label" style="width: 120px;"><span data-lgid="P_WO_MESSAGE_COLON">Message:</span></td>
                    <td>
                        <select id="dialog_variables" style="width: 156px;">
                            <option value="0">[Site_Name]</option>
                            <option value="1">[Location]</option>
                            <option value="14">[Asset]</option>
                            <option value="4">[VIN]</option>
                            <option value="2">[Make]</option>
                            <option value="3">[Model]</option>
                            <option value="5">[Id_Phone]</option>
                            <option value="6">[Advisor]</option>
                            <option value="7">[Company_Name]</option>
                            <option value="8">[Contact_Name]</option>
                            <option value="9">[Contact_First_Name]</option>
                            <option value="10">[Status_Link]</option>
                            <option value="11">[Technician_Name]</option>
                            <option value="12">[Work_Order_Number]</option>
                            <option value="13">[Parts_Order_Number]</option>
                        </select>
                        <input type="button" id="dialog_insertfield" onclick="insertfield();" data-lgid="P_WO_ADD" style="width: auto; height: auto; margin-left: 5px;" tabindex="1" />
                        <br />
                        <textarea id="dialog_textmsg" tabindex="1" style="width: 320px; height: 120px; margin-top: 6px;" maxlength="2000"></textarea></td>
                </tr>
                <tr id="trselectatta">
                    <td>
                        <div style="font-size: 20px; margin-right: 5px; float: right;" onclick="openSelectAttachment()"><em class="spanbtn iconlink" style="font-weight: 900; font-size: 14px; cursor: pointer; padding-left: 0; padding-right: 3px; padding-top: 0;" data-title-lgid="P_WO_SELECTATTACHMENT"></em></div>
                    </td>
                    <td>
                        <span id="span_attachmentname" style="float: left; width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: pre;"></span>
                        <span id="span_attachmentdelete" onclick="onRemoveSelectedAttachment()" style="display: none;">
                            <em class="spanbtn icondelete" style="font-weight: 900; font-size: 14px; cursor: default; padding-left: 5px; padding-right: 3px; padding-top: 0;"></em></span>
                    </td>
                </tr>
            </table>
        </div>
        <div class="dialog-func">
            <input type="button" value="Cancel" data-lgid="P_WO_CANCEL" class="dialog-close" tabindex="1" />
            <input type="button" id="btn_savestatuschange" value="Save Work Order and Send" data-lgid="P_WO_SAVEWORKORDERANDSEND" style="width: unset;" tabindex="1" />
            <div class="clear"></div>
        </div>
        <div id="statuschange_maskbg" class="maskbg" style="display: none;"></div>
    </div>

    <div class="dialog" id="dialog_selecteattachments" style="display: none;">
        <div class="dialog-title"><span class="title" data-lgid="P_WO_SELECTATTACHMENT">Select Attachment</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <div id="div_selectattachmentlist" style="height: 320px; width: 400px;"></div>
        </div>
        <div class="dialog-func">
            <input type="button" value="Cancel" data-lgid="P_UM_CANCEL" class="dialog-close" tabindex="1" />
            <input type="button" onclick="onSetSelectAttachment();" value="Attach" data-lgid="P_WO_ATTACH" tabindex="1" />
            <div style="clear: both;"></div>
        </div>
    </div>

    <div id="dialogattmask" class="maskbg" style="display: none;">
        <%-- 放到最后--%>
        <div class="loading c-spin"></div>
        <lable class="lable_attuploadname"></lable>
    </div>
    <iframe id="ifdiv" style="height: 1px; width: 1px; display: none;"></iframe>
</asp:Content>