<%@ Page Title="" Language="C#" MasterPageFile="~/MachineDeviceManagement/DeviceManagementBase.master" AutoEventWireup="true" CodeFile="AddDevice.aspx.cs" Inherits="AddDevice" %>


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

        .popus-close {
            float: right;
            margin-right: 6px;
            cursor: pointer;
        }

            .popus-close:before {
                content: '\e600';
            }

        textarea {
            resize: none;
        }

        .divtab {
            overflow: auto;
        }

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

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

            .assetcontent table td input,
            .assetcontent table td textarea {
                border: 1px solid #a9a9a9;
                width: 320px;
                height: 18px;
                padding: 1px;
            }

                .assetcontent table td input[type="checkbox"] {
                    border: none;
                    width: 13px;
                }

            .assetcontent table td textarea {
                height: 100px;
            }

        #divcontent {
            margin: 8px;
        }

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

        .msgtime {
            text-align: right;
        }

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

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

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

        .divattp {
            width: 200px;
            margin-right: 10px;
            margin-left: 10px;
            float: left;
            position: relative;
        }

        .divatt {
            width: 200px;
            height: 200px;
            margin-top: 5px;
            margin-bottom: 5px;
            margin-right: 10px;
            cursor: pointer;
            border: 1px solid #b0b0b0;
            border-radius: 2px;
            box-shadow: rgba(0, 0, 0, 0.4);
            text-align: center;
            float: left;
            position: relative;
        }

        .picture {
            max-height: 100%;
            max-width: 100%;
            margin: auto;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
        }


        .download {
            line-height: 200px;
            font-size: 200px;
            margin: 0 auto;
            font-family: 'Fontawesome';
            color: silver;
        }

            .download::before {
                content: '\f15c';
            }

        .wolist_download {
            font-size: 60px;
            margin: 0 auto;
            font-family: 'Fontawesome';
            color: silver;
        }

            .wolist_download::before {
                content: '\f15c';
            }


        .file-word::before {
            content: '\f1c2';
        }

        .file-excel::before {
            content: '\f1c3';
        }

        .file-ppt::before {
            content: '\f1c4';
        }

        .file-pdf::before {
            content: '\f1c1';
        }

        .file-video::before {
            content: '\f1c8';
        }

        .file-zip::before {
            content: '\f1c6';
        }

        .file-msg::before {
            content: '\f0e0';
        }


        .delete {
            position: absolute;
            vertical-align: top;
            font-size: 20px;
            font-family: 'Fontawesome';
            color: rgb(123,28,33);
            right: 8px;
        }

            .delete::before {
                content: '\f00d';
            }

        .attadownload {
            position: absolute;
            vertical-align: top;
            font-size: 16px;
            font-family: 'Fontawesome';
            color: rgb(123,28,33);
            right: 5px;
            bottom: 5px;
        }

            .attadownload::before {
                content: '\f019';
            }

        .attaprint {
            position: absolute;
            vertical-align: top;
            font-size: 16px;
            font-family: 'Fontawesome';
            color: rgb(123,28,33);
            right: 30px;
            bottom: 5px;
        }

            .attaprint::before {
                content: '\f02f';
            }

        .attaedit {
            font-size: 14px;
            font-family: 'Fontawesome';
            color: rgb(123,28,33);
            padding: 3px;
        }

            .attaedit::before {
                content: '\f044';
            }

        .attasave {
            font-size: 18px;
            font-family: 'Fontawesome';
            color: rgb(123,28,33);
            margin-left: 3px;
        }

            .attasave::before {
                content: '\f00c';
            }

        .divattp input {
            width: 60px;
            border: 1px solid #fff;
        }
        /*
            .divattp input.focused,
            .divattp input:hover {
                border-color: #666;
            }

            .divattp input:disabled,
            .divattp input:disabled:hover,
            .divattp td input:disabled {
                background: #ddd;
                color: #ddd;
                border-color: #ddd;
            }*/

        .inp_name {
            height: 24px;
        }

        .tab_deviceparing tr {
            border-bottom: none;
        }

            .tab_deviceparing tr td.label {
                width: 167px;
                text-align: right;
                padding-right: 10px;
                line-height: unset;
                height: unset;
                vertical-align: middle;
            }
    </style>
    <script src="<%=GetFileUrlWithVersion("../Maintenance/js/inputdatactr.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../js/jquery.datetimepicker.full.js")%>"></script>
    <script src="<%=GetFileUrlWithVersion("../js/editableselect.js")%>"></script>
    <script src="<%=GetFileUrlWithVersion("../js/controls.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../js/assetselector.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("js/deviceparinglogs.js")%>" type="text/javascript"></script>
    <script type="text/javascript">
        var IsDealer = <%=IsDealer ?"true":"false"%>;
        var IsAdmin =<%=IsAdmin ?"true":"false"%>;
        var IsSupperAdmin =<%=IsSupperAdmin ?"true":"false"%>;
        var isAllowed = false;
        var currentDevice = null;

        var deviceid = undefined;

        var needRefreshDataOnCancel = false;//在点Cancel时需要刷新数据

        function devicerequest(method, param, callback, error) {
            _network.request("MachineDeviceManagement/ManageMachines.aspx", -1, method, param, callback, error || function (e) {
                console.log(e);
                showmaskbg(false, true);
                showAlert('An unknown error occurred.  Please refresh page.', 'Query');
            });
        }

        function init(cid, device, type) {
            if (IsSupperAdmin)
                $('.sadminonly').show();
            else
                $('.sadminonly').hide();

            currentDevice = device;

            $('#sel_contractor').val(cid);
            $("#li_comments").data("loaded", false);
            $("#li_installationnotes").data("loaded", false);
            $('#dialog_comments').val("");
            $('#dialog_installationnotes').val("");
            inImages = [];
            $("#divINImages").empty();

            if (device) {
                deviceid = device.Id;
                $("#li_comments").show();
                if (type == 1)
                    $("#li_comments").click();
                else
                    $("#li_deviceinfo").click();
                if (IsSupperAdmin) {
                    $("#li_installationnotes").show();
                }
                else
                    $("#li_installationnotes").hide();

                $("#li_devicepairinginfo").show();
                OnEdit(device);
            } else {
                deviceid = undefined;
                $("#li_comments").hide();
                $("#li_installationnotes").hide();
                $("#li_devicepairinginfo").hide();
                if ($("#li_comments").hasClass("selected")
                    || $("#li_installationnotes").hasClass("selected")
                    || $("#li_devicepairinginfo").hasClass("selected"))
                    $("#li_deviceinfo").click();

                OnAdd();
            }
        }

        function setNimbeLink(hide) {
            $('#dialog_tamperalerts').prop('checked', true);
            $('#dialog_utilization').prop('checked', false);
            $('#dialog_devicetype').val('');
            $('#dialog_seldevicetype').val('ATU-RB-1');
            $('#tr_utilization').hide();
            if (hide) {
                $('#dialog_devicetype').show();
                $('#dialog_seldevicetype').hide();
                $('#tr_tamper').hide();
            }
            else {
                $('#dialog_devicetype').hide();
                $('#dialog_seldevicetype').show();
                $('#tr_tamper').show();
            }
        }


        function OnAdd() {
            setNimbeLink(true);
            $('#tr_utilization').hide();
            $('#dialog_sn').attr('disabled', false);
            $('#dialog_asn').attr('disabled', false);
            $('#dialog_source').attr('disabled', false);
            $('#dialog_sn').val('');
            $('#dialog_asn').val('');
            $('#dialog_devicetype').val('');
            $('#dialog_source').val('CALAMP').change();
            $('#dialog_status').val(1);
            $('#dialog_notes').val('');
            $('#dialog_invoicedate').val('');
            $('#dialog_invoiceno').val('');
            $('#dialog_salesordernumber').val('');
            $('#dialog_servicestartdate').val('');
            $('#dialog_fiinstall').prop('checked', false);
            $('#dialog_installer').val('');

            setMachineInfo();
        }

        function OnEdit(device) {
            setNimbeLink(true);
            $('#dialog_sn').attr('disabled', true);
            $('#dialog_asn').attr('disabled', true);
            $('#dialog_source').attr('disabled', true);
            $('#dialog_sn').val(device.SerialNumber);
            $('#dialog_asn').val(device.AlternativeSerialNumber);
            if (device.Source.toUpperCase() == "DIGITALMATTER")//DigitalMatter对应ATU-RB-8
                device.Source = "NIMBELINK"
            $('#dialog_source').val(device.Source.toUpperCase()).change();
            $('#dialog_status').val(device.Status.Value);
            $('#dialog_notes').val(device.Notes);
            $('#dialog_invoicedate').val(device.InvoiceDateStr);
            $('#dialog_invoiceno').val(device.InvoiceNumber);
            $('#dialog_salesordernumber').val(device.SalesOrderNumber);
            $('#dialog_servicestartdate').val(device.ServiceStartDateStr);
            $('#dialog_fiinstall').prop('checked', device.FIInstalltion.Value);
            $('#dialog_installer').val(device.Installer);

            if (device.Source.toUpperCase() === "NIMBELINK") {
                $('#dialog_devicetype').hide();
                $('#dialog_seldevicetype').show();
                $('#dialog_seldevicetype').val(device.DeviceType);
                if (device.DeviceType !== "ATU-RB-8")
                    $('#tr_tamper').show();
                else
                    $('#tr_tamper').hide();

                $('#dialog_tamperalerts').prop('checked', device.Tamper);
                if (device.DeviceType === "ATU-RB-5" || device.DeviceType === "ATU-RB-6") {
                    $('#tr_utilization').show();
                    $('#dialog_utilization').prop('checked', device.Utilization);
                }
                else {
                    $('#tr_utilization').hide();
                    $('#dialog_utilization').prop('checked', false);
                }
            }
            else
                $('#dialog_devicetype').val(device.DeviceType);

            if (device.Source.toUpperCase() == "CALAMP")
                checkCalampDeviceHasData(device.SerialNumber);
            setMachineInfo(device.PairedAsset);
        }

        function setMachineInfo(asset) {
            if (asset) {
                $('#spassignedasset').text(asset.Name).data("aid", asset.MachineID ? asset.MachineID : asset.Id);
                $('#dialog_vin').text(asset.VIN);
                $('#dialog_make').text(asset.Make ? asset.Make : asset.MakeName);
                $('#dialog_model').text(asset.Model ? asset.Model : asset.ModelName);
                $('#dialog_type').text(asset.MachineType ? asset.MachineType : asset.TypeName);
            }
            else {
                $('#spassignedasset').text(GetTextByKey("P_MD_UNASSIGNED", 'Unassigned')).data("aid", -1);
                $('#dialog_vin').text('');
                $('#dialog_make').text('');
                $('#dialog_model').text('');
                $('#dialog_type').text('');
            }
        }

        function OnSave(exit, callback) {
            var cid = $('#sel_contractor').val();
            var item = {
                'SerialNumber': $.trim($('#dialog_sn').val()),
                'AlternativeSerialNumber': $.trim($('#dialog_asn').val()),
                'Source': $('#dialog_source').val(),
                'Status': $('#dialog_status').val(),
                'Notes': $('#dialog_notes').val(),
                'InvoiceDate': $('#dialog_invoicedate').val(),
                'InvoiceNumber': $('#dialog_invoiceno').val(),
                'SalesOrderNumber': $('#dialog_salesordernumber').val(),
                'ServiceStartDate': $('#dialog_servicestartdate').val(),
                'ContractorID': cid,
                'FIInstalltion': $('#dialog_fiinstall').prop('checked'),
                'Installer': $('#dialog_installer').val(),
                'PairedAsset': {}
            };
            item.PairedAsset.Id = $('#spassignedasset').data("aid");
            item.Tamper = false;
            item.Utilization = false;
            if (item.Source.toUpperCase() === "NIMBELINK") {
                item.DeviceType = $('#dialog_seldevicetype').val();
                if (item.DeviceType == "ATU-RB-8")
                    item.Source = "DIGITALMATTER"
                else
                    item.Tamper = $('#dialog_tamperalerts').prop('checked');
                if (item.DeviceType === "ATU-RB-5" || item.DeviceType === "ATU-RB-6" || item.DeviceType === "ATU-RB-8")
                    item.Utilization = $('#dialog_utilization').prop('checked');
            }
            else
                item.DeviceType = $.trim($('#dialog_devicetype').val());

            var alerttitle;
            if (deviceid) {
                item.Id = deviceid;
                alerttitle = GetTextByKey("P_MD_EDITDEVICE", "Edit Device");
            } else {
                item.Id = -1;
                alerttitle = GetTextByKey("P_MD_ADDDEVICE", "Add Device");
            }

            if (!item.SerialNumber || item.SerialNumber.length == 0) {
                if (item.Source.toUpperCase() === "CALAMP")
                    showAlert(GetTextByKey("P_MD_XXXXX", 'The Device Air ID can not be empty.'), alerttitle);
                else
                    showAlert(GetTextByKey("P_MD_SNCANNOTBEEMPTY", 'SN cannot be empty.'), alerttitle);
                $('#dialog_sn').focus();
                return;
            }

            if (item.InvoiceDate.length > 0) {
                if (!checkDate(item.InvoiceDate)) {
                    $('#dialog_gpsdevice').css('z-index', 0);
                    showAlert(GetTextByKey("P_MD_INVOICEDATEFORMATERROR", "Invoice Date format error."), alerttitle);
                    return false;
                }
            }

            if (item.ServiceStartDate.length > 0) {
                if (!checkDate(item.ServiceStartDate)) {
                    $('#dialog_gpsdevice').css('z-index', 0);
                    showAlert(GetTextByKey("P_MD_SERVICESTARTDATEFORMATERROR", "Service Start Date format error."), alerttitle);
                    return false;
                }
            }

            showloading(true);
            var param = JSON.stringify(item);
            param = htmlencode(param);
            var savetitle = GetTextByKey("P_MD_SAVEDEVICE", "Save Device");
            devicerequest("SaveGPSDevice", param, function (data) {
                showloading(false);
                if (typeof (data) === "string") {
                    showAlert(data, savetitle);
                } else {
                    deviceid = data[0];
                    if (item.Source.toUpperCase() == "CALAMP") {
                        if (currentDevice && currentDevice.SerialNumber != item.SerialNumber) {
                            currentDevice = item;
                            $('#dialog_asn').val("");
                        }
                    }
                    else
                        $('#dialog_sn').attr('disabled', true);
                    $('#dialog_asn').attr('disabled', true);
                    $('#dialog_source').attr('disabled', true);
                    $('#dialog_gpsdevice').hideDialog();

                    needRefreshDataOnCancel = true;
                    if (callback) {
                        callback(item);
                    } else {
                        if (parseInt(data[1]) == -10) {
                            var msg = GetTextByKey("P_MD_XXX", "Only 1 {0} can be assigned to an asset at a time.");
                            msg = msg.replace("{0}", $("#dialog_source").find("option:selected").text())
                            showAlert(msg, savetitle);
                        }
                        else {
                            if (exit == 0)
                                showAlert(GetTextByKey("P_MD_SAVSUCCESSFULLY", "Saved successfully."), savetitle);
                            else if (exit == 1)
                                OnExit(exit);
                        }
                    }
                }
            }, function (err) {
                showloading(false);
                showAlert(GetTextByKey("P_MD_FAILEDSAVEDEVICE", 'Failed to save device.'), savetitle);
            });
        }

        function OnExit(type) {
            if (type === 0) {
                if (needRefreshDataOnCancel) {
                    type = 1;
                    needRefreshDataOnCancel = false;
                }
            }
            window.parent.CloseDialog(type);
        }

        function checkCalampDeviceHasData(sn) {
            var cid = $('#sel_contractor').val();
            devicerequest("CalampDeviceHasData", JSON.stringify([cid, sn]), function (data) {
                if (data === false) {
                    $('#dialog_sn').attr('disabled', false);
                    $('#dialog_asn').attr('disabled', false);
                }
            }, function (err) {
            });
        }

        function getCalampDeviceSNInfo(esnorairid) {
            devicerequest("GetCalampDeviceSNInfo", htmlencode(esnorairid), function (data) {
                if (data && data != "") {
                    var temp = data.split(";");
                    $('#dialog_sn').val(temp[1]);//air id
                    $('#dialog_asn').val(temp[0]);//esn
                }
            }, function (err) {
            });
        }

        function getGPSSources() {
            devicerequest("GetGPSSources", '', function (data) {
                if (typeof (data) === "string") {
                    showAlert(data, GetTextByKey("P_MD_ERROR", 'Error'));
                    return;
                }
                if (data && data.length > 0) {
                    $("#dialog_source").empty();
                    for (var i = 0; i < data.length; i++) {
                        var kv = data[i];
                        if (kv.Key.toUpperCase() == "DIGITALMATTER")
                            continue;
                        var op = $("<option></option>").val(kv.Key.toUpperCase()).text(kv.Value);
                        $("#dialog_source").append(op);
                    }
                }

            }, function (err) {
            });
        }

        function getDeviceComments() {
            var cid = $('#sel_contractor').val();
            $('#mask_bg').show();
            devicerequest("GetDeviceComments", JSON.stringify([cid, deviceid]), function (data) {
                $('#mask_bg').hide();
                if (typeof (data) === "string") {
                    return;
                }
                $("#li_comments").data("loaded", true);
                $("#divcomments").empty();
                if (data && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var comment = data[i];
                        showComment(comment, i == 0)
                    }
                }
            }, function (err) {
                $('#mask_bg').hide();
            });
        }

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

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

            var cid = $('#sel_contractor').val();
            var param = JSON.stringify([cid, deviceid, comment]);
            param = htmlencode(param);
            $('#mask_bg').show();
            devicerequest("AddDeviceComment", param, function (data) {
                $('#mask_bg').hide();
                if (data !== "") {
                    showAlert(data, GetTextByKey("P_MD_ERROR", 'Error'));
                    return;
                }
                $('#dialog_comments').val("");
                getDeviceComments();
            }, function (err) {
                $('#mask_bg').hide();
            });
        }

        function OnAddComment() {
            addDeviceComment();
        }

        function getDeviceInstallationNotes() {
            var cid = $('#sel_contractor').val();
            $('#mask_bg').show();
            devicerequest("GetDeviceInstallationNotes", JSON.stringify([cid, deviceid]), function (data) {
                $('#mask_bg').hide();
                if (typeof (data) === "string") {
                    return;
                }
                $("#li_installationnotes").data("loaded", true);
                $("#divinstallationnotes").empty();
                if (data && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var inotes = data[i];
                        showInstallationNotes(inotes, i == 0)
                    }
                }
            }, function (err) {
                $('#mask_bg').hide();
            });
        }

        function showInstallationNotes(inotes, isfirst) {
            var inotesctrl = $("#divinstallationnotes");
            var div = $("<div class='msgdiv'></div>").appendTo(inotesctrl);
            if (isfirst)
                div.css("margin-top", 0);
            var tbuser = $("<table class='msgtime' style='width:100%;'></table>").appendTo(div);
            var tr = $("<tr></tr>").appendTo(tbuser);
            tr.append($("<td style='text-align:left;font-weight:bold;padding:0;width:180px;'></td>").text(inotes.AssetName == "-1" ? "" : inotes.AssetName));
            tr.append($("<td style='text-align:left;font-weight:bold;padding:0;width:180px;'></td>").text(inotes.InstallerName));
            tr.append($("<td style='text-align:right;color:#aaa;'></td>").text(inotes.InstallTimeLocalStr));

            var contentctrl = $("<div style='clear:both;padding-left:5px;'></div>").appendTo(div);
            contentctrl.html(replaceHtmlText(inotes.Notes));

            if (inotes.ImageAddresses && inotes.ImageAddresses.length > 0) {
                var divimg = $("<div style='margin-top:10px;padding-left:5px;'></div>").appendTo(div);
                for (var i in inotes.ImageAddresses) {
                    var imgaddr = inotes.ImageAddresses[i];
                    var img = $("<img style='height:24px;cursor:pointer;margin-right:3px;' />").attr("src", imgaddr);
                    img.click(imgaddr, function (e) {
                        window.open(e.data, "_blank");
                    })
                    divimg.append(img);
                }
            }
        }

        function addInstallationNotes() {
            var alerttitle = GetTextByKey("P_MD_ADDINSTALLATIONNOTES", "Add Installation Notes");
            var inotes = $('#dialog_installationnotes').val();
            if ($.trim(inotes) == "") {
                showAlert(GetTextByKey("P_MD_PLEASEINPUTTHEINSTALLATIONNOTES", "Please input the installation notes."), alerttitle);
                return;
            }

            var cid = $('#sel_contractor').val();
            var param = JSON.stringify([cid, deviceid, inotes]);
            $('#mask_bg').show();

            var formData = new FormData();
            if (inImages && inImages.length > 0) {
                inImages.forEach(function (file) {
                    formData.append('files', file, file.name);
                });
            }
            formData.append("MethodName", "AddInstallationNotes");
            formData.append("ClientData", htmlencode(param));
            $.ajax({
                url: 'ManageMachines.aspx?tp=ashx',
                type: 'POST',
                dataType: 'json',
                processData: false,
                contentType: false,
                data: formData,
                async: true,
                success: function (data) {
                    if (data !== "OK") {
                        showAlert(data, alerttitle);
                        return;
                    }
                    $('#mask_bg').hide();
                    $('#dialog_installationnotes').val("");
                    inImages = [];
                    $("#divINImages").empty();
                    getDeviceInstallationNotes();
                },
                error: function (err) {
                    $('#mask_bg').hide();
                }
            });
        }

        var inImages = [];
        function addINImages() {
            var file = $('<input type="file" style="display: none;" multiple="multiple" accept="image/png,image/jpeg" />');
            file.change(function () {
                var files = this.files;
                for (var i = 0; i < files.length; i++) {
                    if (inImages.length >= 6)
                        return false;
                    var file = files[i];
                    if (!/image\/\w+/.test(file.type)) {
                        showAlert(GetTextByKey("P_MA_UPLOADASSETICONTIPS", 'The file type for the asset icon is invalid. The file must be JPG or PNG.'), GetTextByKey("P_MA_SAVEASSET", 'Save Asset'));
                        return false;
                    }
                    if (file.size == 0) {
                        alert(GetTextByKey("P_IPT_FILETIPS", "File size is 0kb, uploading failed."));
                        return false;
                    }
                    if (file.size > 1024 * 1024 * 2) {
                        alert(GetTextByKey("P_IPT_FILETIPS1", "File is too large. Maximum size is 2MB."));
                        return false;
                    }
                    var reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.filedata = file;
                    reader.onload = function (r) {
                        var img = $("<img style='height:24px;margin-right:3px;' />").attr("src", r.target.result);
                        $("#divINImages").append(img);
                        //img.click(function (e) {
                        //    inImages.splice(inImages.indexOf(r.target.filedata), 1);
                        //    $(e.target).remove();
                        //});
                        //document.getElementById("img1").src = reader.result;
                    };

                    inImages.push(file);
                }
            }).click();
        }



        var dialogAssets;
        $(function () {
            getGPSSources();

            dialogAssets = new $assetselector('dialog_machines');
            dialogAssets.forceSingle = true;
            dialogAssets.onDialogClosed = function () {
                showmaskbg(false);
            };
            dialogAssets.onOK = function (source, selectedIndex) {
                var selectedAsset = null;
                if (selectedIndex >= 0)
                    selectedAsset = source[selectedIndex].Values;
                setMachineInfo(selectedAsset);
                showmaskbg(false);
            };
            $("#btnSelectAsset").click(function () {
                showmaskbg(true);
                dialogAssets.companyId = $('#sel_contractor').val();
                dialogAssets.includechild = false;
                dialogAssets.showSelector();
            });

            $("#btnUnpair").click(function () {
                setMachineInfo();
            });

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

            $('#dialog_servicestartdate').datetimepicker({
                timepicker: false,
                format: 'm/d/Y',
                enterLikeTab: false,
                onSelectDate: function (v, inp) {
                    var date = new DateFormatter().formatDate(v, 'm/d/Y 00:00:00');
                    inp.parent().data('val', [date]);
                }
            });
            $('#dialog_source').change(function () {
                setNimbeLink(true);
                if ($('#dialog_source').val() == "CALAMP") {
                    $('#tr_asn').show();
                    $("#lblsn").text(GetTextByKey("P_MD_DEVICEAIRID_COLON", "Device Air Id:"));
                }
                else {
                    $('#tr_asn').hide();
                    $('#dialog_asn').val("");
                    $("#lblsn").text(GetTextByKey("P_MD_SN_COLON", "SN:"));

                    if ($('#dialog_source').val() == "NIMBELINK") //NimbeLink 
                    {
                        setNimbeLink(false);
                        var type = $('#dialog_seldevicetype').val();
                        if (type === "ATU-RB-5" || type === "ATU-RB-6")
                            $('#tr_utilization').show();
                        if (type !== "ATU-RB-8")
                            $('#tr_tamper').show();
                        else
                            $('#tr_tamper').hide();
                    }
                }
            });

            $('#dialog_seldevicetype').change(function () {
                if ($('#dialog_source').val() === "NIMBELINK") {
                    $('#tr_utilization').hide();
                    $('#dialog_utilization').prop('checked', false);
                    var type = $('#dialog_seldevicetype').val();
                    if (type === "ATU-RB-5" || type === "ATU-RB-6")
                        $('#tr_utilization').show();
                    if (type !== "ATU-RB-8")
                        $('#tr_tamper').show();
                    else
                        $('#tr_tamper').hide();
                }
            });

            $("#dialog_sn").blur(function () {
                if ($('#dialog_source').val() == "CALAMP") {
                    getCalampDeviceSNInfo($.trim($("#dialog_sn").val()));
                }
            });

            $("#dialog_asn").blur(function () {
                if ($('#dialog_source').val() == "CALAMP") {
                    getCalampDeviceSNInfo($.trim($("#dialog_asn").val()));
                }
            });

            $('#dialog_tamperalerts').change(function () {
                var alerttitle = GetTextByKey("P_MD_ADDDEVICE", "Add Device");
                if (deviceid)
                    alerttitle = GetTextByKey("P_MD_EDITDEVICE", "Edit Device");
                showAlert(GetTextByKey("P_MD_CONFIGURATIONCHANGETIPS", "This configuration change may take up to 24 hours to take affect."), alerttitle);
            });
            $('#dialog_utilization').change(function () {
                var alerttitle = GetTextByKey("P_MD_ADDDEVICE", "Add Device");
                if (deviceid)
                    alerttitle = GetTextByKey("P_MD_EDITDEVICE", "Edit Device");
                showAlert(GetTextByKey("P_MD_CONFIGURATIONCHANGETIPS", "This configuration change may take up to 24 hours to take affect."), alerttitle);
            });

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

            $("#li_comments").click(function () {
                if (!$("#li_comments").data("loaded"))
                    getDeviceComments();
            });

            $("#li_installationnotes").click(function () {
                if (!$("#li_installationnotes").data("loaded"))
                    getDeviceInstallationNotes();
            });

            $("#li_devicepairinginfo").click(function () {
                getDevicePairingLogsByDevice();
            });
        });

    </script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <input type="hidden" id="sel_contractor" />
    <div class="function_title">
        <span class="sbutton iconsave" onclick="OnSave(0);" data-lgid="P_MD_SAVE">Save</span>
        <span class="sbutton iconsave" onclick="OnSave(1);" data-lgid="P_MD_SAVE1">Save and Exit</span>
        <span class="sbutton iconexit" onclick="OnExit(0);" data-lgid="P_MD_SAVE2">Exit Without Saving</span>
    </div>
    <div id="div_container" style="height: 100%;">
        <ul id="ul_container" class="tab_header" style="height: 29px;">
            <li id="li_deviceinfo" data-href="tab_deviceinfo" class="selected" data-lgid="P_MD_SUMMARY">Summary</li>
            <li id="li_comments" data-href="tab_comments" data-lgid="P_MD_NOTES">Notes</li>
            <li id="li_installationnotes" data-href="tab_installationnotes" data-lgid="P_MD_INSTALLATIONNOTES">Installation Notes</li>
            <li id="li_devicepairinginfo" data-href="tab_devicepairinginfo" data-lgid="P_MD_XXX">Pairing Info</li>
        </ul>
        <div id="dialog_device" data-page="tab_deviceinfo" style="padding-top: 30px;">
            <div id="div_content">
                <div class="clear"></div>
                <div id="divcontent" class="assetcontent">
                    <table>
                        <tr>
                            <td class="label" data-lgid="P_MD_SOURCE_COLON">Source:</td>
                            <td>
                                <select id="dialog_source" tabindex="1" style="width: 204px;"></select></td>
                        </tr>
                        <tr>
                            <td class="label" id="lblsn" data-lgid="P_MD_SN_COLON">SN:</td>
                            <td>
                                <input type="text" id="dialog_sn" maxlength="200" tabindex="2" autocomplete="off" /></td>
                        </tr>
                        <tr id="tr_asn">
                            <td class="label" data-lgid="P_MD_DEVICEESN_COLON">Device ESN:</td>
                            <td>
                                <input type="text" id="dialog_asn" maxlength="200" tabindex="3" autocomplete="off" /></td>
                        </tr>
                        <tr>
                            <td class="label" data-lgid="P_MD_DEVICETYPE_COLON">Device Type:</td>
                            <td>
                                <input type="text" id="dialog_devicetype" maxlength="100" tabindex="4" autocomplete="off" />
                                <select id="dialog_seldevicetype" tabindex="4" style="width: 204px; display: none;">
                                    <option value="ATU-RB-1">ATU-RB-1</option>
                                    <option value="ATU-RB-5">ATU-RB-5</option>
                                    <option value="ATU-RB-6">ATU-RB-6</option>
                                    <option value="ATU-RB-8">ATU-RB-8</option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td class="label" data-lgid="P_MD_STATUS_COLON">Status:</td>
                            <td>
                                <select id="dialog_status" tabindex="5" style="width: 204px;">
                                    <option value="1" data-lgid="P_MD_ACTIVE">Active</option>
                                    <option value="0" data-lgid="P_MD_INACTIVE">Inactive</option>
                                </select></td>
                        </tr>
                        <tr>
                            <td class="label" data-lgid="P_MD_INVOICEDATE_COLON">Invoice Date:</td>
                            <td>
                                <input type="text" id="dialog_invoicedate" maxlength="50" tabindex="6" autocomplete="off" /></td>
                        </tr>
                        <tr>
                            <td class="label" data-lgid="P_MD_INVOICENUMBER_COLON">Invoice #:</td>
                            <td>
                                <input type="text" id="dialog_invoiceno" maxlength="200" tabindex="7" autocomplete="off" /></td>
                        </tr>
                        <tr class="sadminonly">
                            <td class="label" data-lgid="P_MD_XXXXXX_COLON">Sales Order #:</td>
                            <td>
                                <input type="text" id="dialog_salesordernumber" maxlength="100" tabindex="7" autocomplete="off" /></td>
                        </tr>
                        <tr>
                            <td class="label" data-lgid="P_MD_SERVICESTATDATE_COLON">Service Start Date:</td>
                            <td>
                                <input type="text" id="dialog_servicestartdate" maxlength="50" tabindex="8" autocomplete="off" /></td>
                        </tr>
                        <tr id="tr_tamper" style="display: none;">
                            <td class="label" data-lgid="P_MD_TAMPERALERTS_COLON">Tamper Alerts:</td>
                            <td>
                                <input type="checkbox" id="dialog_tamperalerts" tabindex="8" style="width: auto; height: 13px; margin-left: 0; margin-top: -2px; margin-bottom: 1px; vertical-align: middle;" /></td>
                        </tr>
                        <tr id="tr_utilization" style="display: none;">
                            <td class="label" data-lgid="P_MD_UTILIZATION_COLON">Utilization:</td>
                            <td>
                                <input type="checkbox" id="dialog_utilization" tabindex="8" style="width: auto; height: 13px; margin-left: 0; margin-top: -2px; margin-bottom: 1px; vertical-align: middle;" /></td>
                        </tr>
                        <tr class="sadminonly" style="display: none;">
                            <td class="label" data-lgid="P_MD_FIINSTALLATION_COLON">FI Installation:</td>
                            <td>
                                <input type="checkbox" id="dialog_fiinstall" tabindex="8" style="width: auto; height: 13px; margin-left: 0; margin-top: -2px; margin-bottom: 1px; vertical-align: middle;" /></td>
                        </tr>
                        <tr class="sadminonly" style="display: none;">
                            <td class="label" data-lgid="P_MD_INSTALLER_COLON">Installer:</td>
                            <td>
                                <input type="text" id="dialog_installer" maxlength="50" tabindex="8" autocomplete="off" /></td>
                        </tr>
                        <tr>
                            <td class="label" style="width: 100px;" data-lgid="P_MD_ASSETASSIGNMENT_COLON">Asset Assignment:</td>
                            <td>
                                <span id="spassignedasset"></span>
                                <input type="button" id="btnSelectAsset" value="Select Asset" data-lgid="P_MD_ASSETASSIGNMENT" tabindex="9" style="width: 80px; height: 22px; margin-left: 5px;" />
                                <input type="button" id="btnUnpair" value="Unpair This Device" data-lgid="P_MD_UNPAIRTHISDEVICE" tabindex="10" style="width: 120px; height: 22px; margin-left: 5px;" />
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td>
                                <table style="width: unset; line-height: 24px;">
                                    <tr>
                                        <td data-lgid="P_MD_VIN_COLON">VIN:</td>
                                        <td id="dialog_vin" style="width: 160px;"></td>
                                        <td data-lgid="P_MD_TYPE_COLON">Type:</td>
                                        <td id="dialog_type" style="width: 160px;"></td>
                                    </tr>
                                    <tr>
                                        <td data-lgid="P_MD_MAKE_COLON">Make:</td>
                                        <td id="dialog_make" style="width: 160px;"></td>
                                        <td data-lgid="P_MD_MODEL_COLON">Model:</td>
                                        <td id="dialog_model" style="width: 160px;"></td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td class="label" data-lgid="P_MD_NOTES_COLON">Notes:</td>
                            <td>
                                <textarea id="dialog_notes" maxlength="3000" tabindex="11" style="margin-top: 4px;"></textarea></td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>

        <div id="tab_comments" data-page="tab_comments" style="padding-top: 30px;">
            <div style="position: absolute; width: 540px; top: 60px; bottom: 1px; left: 0; right: 0;">
                <div style="position: absolute; left: 2px; top: 5px; height: 106px;">
                    <table>
                        <tr>
                            <td>
                                <div style="border: solid 1px rgb(123,28,33);">
                                    <textarea id="dialog_comments" maxlength="3000" tabindex="20" style="margin-top: 4px; width: 519px; height: 60px; border: none; outline: none;"></textarea>
                                    <br />
                                    <div style="text-align: right; margin-bottom: 3px;">
                                        <span class="spanbtn iconsend" style="font-size: 20px;" onclick="OnAddComment();"></span>
                                    </div>
                                </div>
                            </td>
                            <%--<td style="display: none;">
                                <input type="button" value="Submit" data-lgid="P_MD_SUBMIT" tabindex="21" style="box-sizing: border-box; height: 60px; margin: 10px; width: 90px;" onclick="OnAddComment();" />
                            </td>--%>
                        </tr>
                    </table>
                </div>
                <div id="divcomments" style="position: absolute; bottom: 5px; top: 120px; left: 5px; right: 10px; overflow: auto;">
                </div>
            </div>
        </div>

        <div id="tab_installationnotes" data-page="tab_installationnotes">
            <div style="position: absolute; width: 540px; top: 60px; bottom: 1px; left: 0; right: 0;">
                <div style="position: absolute; left: 2px; top: 5px; height: 106px;">
                    <table>
                        <tr>
                            <td>
                                <div style="border: solid 1px rgb(123,28,33);">
                                    <textarea id="dialog_installationnotes" maxlength="3000" tabindex="20" style="margin-top: 4px; width: 519px; height: 60px; border: none; outline: none;"></textarea>
                                    <br />
                                    <table style="width: 100%; margin-bottom: 3px;">
                                        <tr>
                                            <td id="divINImages"></td>
                                            <td style="width: 80px; text-align: right;">
                                                <span class="spanbtn iconimage" style="font-size: 20px; padding-right: 0;" onclick="addINImages();"></span>
                                                <span class="spanbtn iconsave" style="font-size: 20px;" onclick="addInstallationNotes();"></span></td>
                                        </tr>
                                    </table>
                                </div>
                            </td>
                        </tr>
                    </table>
                </div>
                <div id="divinstallationnotes" style="position: absolute; bottom: 5px; top: 120px; left: 5px; right: 10px; overflow: auto;">
                </div>
            </div>
        </div>

        <div id="tab_devicepairinginfo" data-page="tab_devicepairinginfo">
            <div class="function_title">
                <%--<span class="sbutton iconadd" onclick="UpLoadWorkOrderAttachment();" data-lgid="P_WO_ADDFILE">Add File</span>--%>
                <%-- <span class="sbutton iconprint" onclick="openPAndDGDialog(0);" data-lgid="P_WO_PRINT">Print</span>
                <span class="sbutton icondownload" onclick="openPAndDGDialog(1);" data-lgid="P_WO_DOWNLOAD">Download</span>--%>
            </div>
            <div id="div_attlarge">
            </div>
        </div>

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