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


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

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

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

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

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

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

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

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

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

    <link href="<%=GetFileUrlWithVersion("../css/jquery.datetimepicker.css")%>" rel="stylesheet" />
    <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")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../fic/js/utility.js")%>" type="text/javascript"></script>
    <script type="text/javascript">
        var IsSuperAdmin =<%=IsSuperAdmin ?"true":"false"%>;
        var IsAdmin =<%=IsAdmin ?"true":"false"%>;
        var IsDealer = <%=IsDealer ?"true":"false"%>;

        var contractors = [];

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



        function OnExportInImport() {
            var d = JSON.stringify(errordata);
            var data = new FormData();
            data.append('type', 'set');
            data.append('ClientData', d);
            $.ajax({
                url: "../ExportToFile.aspx",
                type: 'POST',
                dataType: 'json',
                processData: false,
                contentType: false,
                data: data,
                success: function (data) {
                    if (data && data != "")
                        window.open("../ExportToFile.aspx?type=devicesexcel&key=" + data);
                },
                error: function (err) {
                }
            });
        }

        function CloseDialog(type) {
            $('#dialog_gpsdevice1').hideDialog();
            if (type == 1) {
                OnRefresh();
            }
            else {
                showmaskbg(false);
            }
        }

        function ShowDeviceDialog(type) {
            showmaskbg(true);
            $('#dialog_gpsdevice1')
                .attr('act', type)
                .showDialogRight();
        }

        function OnAdd() {
            gpsDeviceID = undefined;
            gpsdata = undefined;

            var cid = $('#sel_contractor').val();
            ShowDeviceDialog('add');
            execIframeFunc("init", [cid], "iframe_gpsdevice");
        }

        var gpsDeviceID;
        var gpsdata;
        function OnEdit(type) {
            var gps = grid_dt.source[grid_dt.selectedIndex].Values;
            if (!gps) {
                gpsDeviceID = undefined;
                return;
            }

            gpsdata = gps;
            gpsDeviceID = gps.Id;

            var cid = $('#sel_contractor').val();
            ShowDeviceDialog('edit');
            execIframeFunc("init", [cid, gps, type], "iframe_gpsdevice");
        }

        function OnDblClick(e) {
            OnEdit(0);
        }

        function OnRefresh() {
            showloading(true);
            var cid = $('#sel_contractor').val();
            var searchtxt = "";
            searchtxt = htmlencode($.trim($('#searchinputtxt').val()));
            devicerequest("GetGPSDevices", JSON.stringify([cid, searchtxt]), function (data) {
                showDevices(data);

                showloading(false);
            }, function (err) {
                showloading(false);
            });
        }
        var errordata;
        function showDevices(data) {
            var rows = [];
            for (var i = 0; i < data.length; i++) {
                var r = data[i];
                if (r.PairedAsset) {
                    r.MachineID = r.PairedAsset.Id;
                    r.VIN = r.PairedAsset.VIN;
                    r.Name = r.PairedAsset.Name;
                    r.Year = r.PairedAsset.Year;
                    r.Make = r.PairedAsset.MakeName;
                    r.Model = r.PairedAsset.ModelName;
                    r.MachineType = r.PairedAsset.TypeName;
                    r.EngineHours = r.PairedAsset.EngineHours;
                    r.EngineHoursDate = r.PairedAsset.EngineHoursDate;
                    r.EngineHoursDateStr = r.PairedAsset.EngineHoursDateStr;
                }

                for (var j in r) {
                    if (j === "Status")
                        r[j] = { DisplayValue: r["Status"] === 1 ? "Active" : "Inactive", Value: r[j] };
                    else if (j === "AddDate")
                        r[j] = { DisplayValue: r["AddDateStr"], Value: r[j] };
                    else if (j === "InvoiceDate")
                        r[j] = { DisplayValue: r["InvoiceDateStr"], Value: r[j] };
                    else if (j === "ServiceStartDate")
                        r[j] = { DisplayValue: r["ServiceStartDateStr"], Value: r[j] };
                    else if (j === "EngineHoursDate")
                        r[j] = { DisplayValue: r["EngineHoursDateStr"], Value: r[j] };
                    else if (j === "EngineHours")
                        r[j] = r[j] === 0 ? "" : r[j];
                    else if (j === "Year")
                        r[j] = r[j] === 0 ? "" : r[j];
                    else if (j === "Name")
                        r[j] = r[j] === "0" ? "" : r[j];
                    else if (j == "FIInstalltion") {
                        r[j] = { DisplayValue: r[j] == 1 ? "Yes" : "No", Value: r[j] };
                    }
                }
                var fr = { Values: r };
                rows.push(fr);
            }

            grid_dt.setData(rows);
        }

        var grid_dt;
        function InitGridData() {
            grid_dt = new GridView('#devicelist');
            grid_dt.lang = {
                all: GetTextByKey("P_GRID_ALL", "(All)"),
                ok: GetTextByKey("P_GRID_OK", "OK"),
                reset: GetTextByKey("P_GRID_RESET", "Reset")
            };
            var list_columns = [
                { name: 'SN', caption: GetTextByKey("P_MD_SN", "Air ID or SN"), valueIndex: 'SerialNumber', css: { 'width': 120, 'text-align': 'left' } },
                { name: 'AlternativeSerialNumber', caption: GetTextByKey("P_MD_ESN", "ESN"), valueIndex: 'AlternativeSerialNumber', css: { 'width': 120, 'text-align': 'left' } },
                { name: 'DeviceType', caption: GetTextByKey("P_MD_DEVICETYPE", "Device Type"), valueIndex: 'DeviceType', allowFilter: true, css: { 'width': 120, 'text-align': 'left' } },
                { name: 'Source', caption: GetTextByKey("P_MD_SOURCE", "Source"), valueIndex: 'SourceName', allowFilter: true, css: { 'width': 120, 'text-align': 'left' } },
                { name: 'Status', caption: GetTextByKey("P_MD_STATUS", "Status"), valueIndex: 'Status', allowFilter: true, css: { 'width': 80, 'text-align': 'left' } },
                { name: 'AddDate', caption: GetTextByKey("P_MD_ADDDATE", "Add Date"), valueIndex: 'AddDate', allowFilter: true, css: { 'width': 100, 'text-align': 'left' } },
                { name: 'FIInstalltion', caption: GetTextByKey("P_MD_FIINSTALL", "FI Install"), valueIndex: 'FIInstalltion', allowFilter: true, css: { 'width': 100, 'text-align': 'left' } },
                { name: 'Installer', caption: GetTextByKey("P_MD_INSTALLER", "Installer"), valueIndex: 'Installer', allowFilter: true, css: { 'width': 100, 'text-align': 'left' } },
                { name: 'Notes', caption: GetTextByKey("P_MD_NOTES", "Notes"), valueIndex: 'Notes', css: { 'width': 200, 'text-align': 'left' } },
                { name: 'ServiceStartDate', caption: GetTextByKey("P_MD_SERVICESTATDATE", "Service Start Date"), valueIndex: 'ServiceStartDate', allowFilter: true, css: { 'width': 110, 'text-align': 'left' } },
                { name: 'VIN', caption: GetTextByKey("P_MD_ASSETVINSN", "Asset VIN/SN"), valueIndex: 'VIN', allowFilter: true, css: { 'width': 200, 'text-align': 'left' } },
                { name: 'Name', caption: GetTextByKey("P_MD_ASSETNAME", "Asset Name"), valueIndex: 'Name', allowFilter: true, css: { 'width': 200, 'text-align': 'left' } },
                { name: 'Year', caption: GetTextByKey("P_MD_YEAR", "Year"), valueIndex: 'Year', allowFilter: true, css: { 'width': 80, 'text-align': 'left' } },
                { name: 'Make', caption: GetTextByKey("P_MD_MAKE", "Make"), valueIndex: 'Make', allowFilter: true, css: { 'width': 150, 'text-align': 'left' } },
                { name: 'Model', caption: GetTextByKey("P_MD_MODEL", "Model"), valueIndex: 'Model', allowFilter: true, css: { 'width': 150, 'text-align': 'left' } },
                { name: 'MachineType', caption: GetTextByKey("P_MD_TYPE", "Type"), valueIndex: 'MachineType', allowFilter: true, css: { 'width': 150, 'text-align': 'left' } },
                { name: 'EngineHours', caption: GetTextByKey("P_MD_ENGINEHOURS", "Engine Hours"), valueIndex: 'EngineHours', css: { 'width': 90, 'text-align': 'left' } },
                { name: 'EngineHoursDate', caption: GetTextByKey("P_MD_ENGINEHOURSDATE", "Engine Hours Date"), valueIndex: 'EngineHoursDate', css: { 'width': 120, 'text-align': 'left' } },
                { name: 'InvoiceDate', caption: GetTextByKey("P_MD_INVOICEDATE", "Invoice Date"), valueIndex: 'InvoiceDate', css: { 'width': 100, 'text-align': 'left' } },
                { name: 'InvoiceNumber', caption: GetTextByKey("P_MD_INVOICENUMBER", "Invoice #"), valueIndex: 'InvoiceNumber', css: { 'width': 120, 'text-align': 'left' } },
                { name: 'SalesOrderNumber', caption: GetTextByKey("P_MD_XXXXXX", "Sales Order #"), valueIndex: 'SalesOrderNumber', css: { 'width': 120, 'text-align': 'left' } },
                { name: 'Edit', caption: "", css: { 'width': 30, 'text-align': 'center' } },
                { name: 'ONotes', caption: "", css: { 'width': 30, 'text-align': 'center' } },
                { name: 'ChangeContractor', caption: "", css: { 'width': 30, 'text-align': 'center' } }
            ];
            var columns = [];
            // head
            for (var hd in list_columns) {
                var col = {};
                col.name = list_columns[hd].name;
                col.caption = list_columns[hd].caption;
                col.visible = true;
                col.sortable = true;
                col.width = list_columns[hd].css.width;
                col.align = list_columns[hd].css["text-align"]
                col.key = list_columns[hd].valueIndex;
                col.allowFilter = list_columns[hd].allowFilter;
                if (col.name === "Edit") {
                    col.isurl = true;
                    col.text = "\uf044";
                    col.events = {
                        onclick: function () {
                            OnEdit(0);
                        }
                    };
                    col.classFilter = function (e) {
                        return "icon-col";
                    }
                    col.attrs = { 'title': GetTextByKey("P_MD_EDIT", 'Edit') };
                }
                else if (col.name === "ONotes") {
                    col.isurl = true;
                    col.text = "\uf075";
                    col.events = {
                        onclick: function () {
                            OnEdit(1);
                        }
                    };
                    col.classFilter = function (e) {
                        return "icon-col";
                    }
                    col.attrs = { 'title': GetTextByKey("P_MD_NOTES", 'Notes') };
                }
                else if (col.name === "ChangeContractor") {
                    if (!IsDealer)
                        continue;
                    col.isurl = true;
                    col.text = "\uf0ec";
                    col.events = {
                        onclick: function () {
                            OnChangeContractor(1);
                        }
                    };
                    col.classFilter = function (e) {
                        return "icon-col";
                    }
                    col.attrs = { 'title': GetTextByKey("P_MD_CHANGECONTRACTOR", 'Change Contractor') };
                }
                else if (col.name === "FIInstalltion" || col.name === "Installer" || col.name === "SalesOrderNumber") {
                    if (!IsSuperAdmin)
                        continue;
                }
                columns.push(col);
            }
            grid_dt.canMultiSelect = false;
            grid_dt.columns = columns;
            grid_dt.init();
            grid_dt.rowdblclick = function () { OnEdit(0) };

            grid_dt.selectedrowchanged = function (rowindex) {
                var rowdata = grid_dt.source[rowindex];
                if (rowdata) {
                    gpsDeviceID = rowdata.Values.Id;
                }
            }
        }

        function OnChangeContractor() {
            var gps = grid_dt.source[grid_dt.selectedIndex].Values;
            if (!gps) {
                gpsDeviceID = undefined;
                return;
            }
            var sel_con = $("#dialog_contractor").empty();
            //sel_con.append($('<option></option>').val("-1").text(" "));
            for (var i = 0; i < contractors.length; i++) {
                var kv = contractors[i];
                if ($('#sel_contractor').val() != kv.Key) {
                    op_search = $('<option></option>').val(kv.Key).text(kv.Value);
                    sel_con.append(op_search);
                }
            }
            $("#txtChangeConNotes").val("");
            //$("#dialog_contractor").val("");
            showmaskbg(true);
            $('#dialog_changecon').data("gps", gps)
                .css({
                    'top': (document.documentElement.clientHeight - $('#dialog_changecon').height()) / 3,
                    'left': (document.documentElement.clientWidth - $('#dialog_changecon').width()) / 2
                }).showDialogfixed();
        }

        function ChangeContractor() {
            var gps = $('#dialog_changecon').data("gps");
            if (!gps)
                return;
            var ps = [];
            ps.push(gps.Id);
            ps.push($("#dialog_contractor").val());
            ps.push(htmlencode($("#txtChangeConNotes").val()));
            devicerequest('ChangeGPSContractor', JSON.stringify(ps), function (data) {
                if (data !== "OK") {
                    showAlert(data, GetTextByKey("P_MD_ERROR", 'Error'));
                    return;
                }
                $('#dialog_changecon').hideDialog();
                OnRefresh();
            });
        }

        //admin用户 获取所有contractor     
        function getContractors() {
            devicerequest('GetContractors', '', function (data) {
                if (typeof (data) === "string") {
                    showAlert(data, GetTextByKey("P_MD_ERROR", 'Error'));
                    return;
                }
                if (data && data.length > 0) {
                    var sel_search = $('#sel_contractor').empty();
                    var sel_con = $("#dialog_contractor").empty();
                    sel_con.append($('<option></option>').val("-1").text(" "));
                    for (var i = 0; i < data.length; i++) {
                        var kv = data[i];
                        var op_search = $('<option></option>').val(kv.Key).text(kv.Value);
                        sel_search.append(op_search);
                        op_search = $('<option></option>').val(kv.Key).text(kv.Value);
                        sel_con.append(op_search);
                    }
                    contractors = data;
                }
                else
                    contractors = [];

                var contractorid = htmlencode($.trim($('#sel_contractor').val()));
                if (contractorid || contractorid == "")
                    $("#btnAdd").hide();

                OnRefresh();
            });
        }

        //普通用户 获取可操作的contractor     
        function GetContractorsByUser() {
            devicerequest('GetContractorsByUser', '', function (data) {
                if (typeof (data) === "string") {
                    showAlert(data, GetTextByKey("P_MD_ERROR", 'Error'));
                    return;
                }
                if (data && data.length > 0) {
                    var sel_search = $('#sel_contractor').empty();
                    for (var i = 0; i < data.length; i++) {
                        var kv = data[i];
                        var op_search = $('<option></option>').val(kv.Key).text(kv.Value);
                        sel_search.append(op_search);
                    }
                    contractors = data;
                }
                else
                    contractors = [];
                var contractorid = htmlencode($.trim($('#sel_contractor').val()));
                if (contractorid || contractorid == "")
                    $("#btnAdd").hide();

                OnRefresh();
            });
        }


        $(function () {
            setPageTitle(GetTextByKey("P_MANAGEDEVICES", "Manage Devices"), true);
            //$("#iframe_gpsdevice").attr("src", "AddDevice.aspx");
            InitGridData();

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

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

            if (IsDealer == true) {
                $('#span_contractor').css('display', '');
                if (IsAdmin)
                    getContractors();
                else {
                    GetContractorsByUser();
                }
            }
            else {
                OnRefresh();
            }

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

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

            $("#sel_contractor").change(function () {
                OnRefresh();
            });

            $('#searchinputtxt').keydown(searchEnter);

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

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

        function searchEnter(e) {
            if (e.keyCode == 13 || e.keyCode == 9) {
                OnRefresh();
            }
        }

        function OnExport() {
            var cid = $('#sel_contractor').val();
            var searchtxt = "";
            searchtxt = htmlencode($.trim($('#searchinputtxt').val()));

            var p = [cid, searchtxt];
            var param = htmlencode(JSON.stringify(p));
            window.open("../ExportToFile.aspx?type=managedevices&param=" + param);
        }

        function getcolumnsdata() {
            var columnsdata = [];

            columnsdata.push({ Id: "Source", Name: GetTextByKey("P_MD_SOURCE", "Source"), Width: 120, Key: 'SourceName' });
            columnsdata.push({ Id: "SN", Name: GetTextByKey("P_MD_SN", "SN"), Width: 120, Key: 'SerialNumber' });
            columnsdata.push({ Id: "ESN", Name: GetTextByKey("P_MD_ESN", "ESN"), Width: 120, Key: 'AlternativeSerialNumber' });
            columnsdata.push({ Id: "DeviceType", Name: GetTextByKey("P_MD_DEVICETYPE", "Device Type"), Width: 120, Key: 'DeviceType' });
            columnsdata.push({ Id: "Status", Name: GetTextByKey("P_MD_STATUS", "Status"), Width: 50, Key: 'Status' });
            columnsdata.push({ Id: "InvoiceDate", Name: GetTextByKey("P_MD_INVOICEDATE", "Invoice Date"), Width: 120, Key: 'InvoiceDate' });
            columnsdata.push({ Id: "InvoiceNumber", Name: GetTextByKey("P_MD_INVOICENUMBER", "Invoice #"), Width: 120, Key: 'InvoiceNumber' });
            if (IsSuperAdmin) {
                columnsdata.push({ Id: "SalesOrderNumber", Name: GetTextByKey("P_MD_XXXXXX", "Sales Order #"), Width: 120, Key: 'SalesOrderNumber' });
            }
            columnsdata.push({ Id: "ServiceStartDate", Name: GetTextByKey("P_MD_SERVICESTATDATE", "Service Start Date"), Width: 120, Key: 'ServiceStartDate' });
            columnsdata.push({ Id: "VIN/SN", Name: GetTextByKey("P_MA_VINSN", "VIN/SN"), Width: 120, Key: 'VIN' });
            columnsdata.push({ Id: "TamperAlerts", Name: GetTextByKey("P_MD_TAMPERALERTS", "Tamper Alerts"), Width: 120, Key: 'Tamper' });
            columnsdata.push({ Id: "Utilization", Name: GetTextByKey("P_MD_UTILIZATION", "Utilization"), Width: 120, Key: 'Utilization' });
            if (IsSuperAdmin) {
                columnsdata.push({ Id: "FIInstallation", Name: GetTextByKey("P_MD_FIINSTALLATION", "FI Installation"), Width: 120, Key: 'FIInstalltion' });
                columnsdata.push({ Id: "Installer", Name: GetTextByKey("P_MD_INSTALLER", "Installer"), Width: 120, Key: 'Installer' });
            }
            columnsdata.push({ Id: "Notes", Name: GetTextByKey("P_MD_NOTES", "Notes"), Width: 120, Key: 'Notes' });
            return columnsdata;
        }

        function CreateSelect(excelcolumns, colid) {
            var sel = $('<select style="width:180px;" name="sel_import"></select>').data('id', colid);
            sel.append('<option></option>');
            if (excelcolumns && excelcolumns.length > 0) {
                for (var i = 0; i < excelcolumns.length; i++) {
                    var op = $('<option></option>').text(excelcolumns[i]).val(excelcolumns[i]);
                    sel.append(op);
                }
                sel.val(colid);
            }
            return sel;
        }

        function CreateImportColumns(excelcolumns) {
            var tb = $('#tb_import');
            tb.empty();
            var columnsdata = getcolumnsdata();
            for (var i = 0; i < columnsdata.length; i++) {
                var col = columnsdata[i];
                var tr = $('<tr></tr>');
                tb.append(tr);
                var td = $('<td class="label" style="width:150px;">' + col.Name + '</td>');
                if (i < 2) {
                    var sp = $('<span style="color:red;">*</span>');
                    td.append(sp);
                }
                tr.append(td);
                td = $('<td></td>');
                tr.append(td);
                var sel = CreateSelect(excelcolumns, col.Id);
                td.append(sel);
            }
        }
        var grid_import_result = null;
        function CreateImportResultGrid(data, t) {
            if (grid_import_result == null) {
                grid_import_result = new GridView('#div_import_grid');
            }

            if (t == 0 && data.length == 0) {
                $('#btnOk').hide();
            }
            var columnsdata = getcolumnsdata();
            var columns = [];
            if (t == 0) {
                columns.push({
                    type: 3,
                    key: 'checked',
                    allcheck: true,
                    width: 45,
                    align: 'center'
                });
            }
            var styleFilter = function (item) {
                if ($.nullOrEmpty(item.SourceName) || $.nullOrEmpty(item.SerialNumber)) {
                    return { 'color': 'red' };
                }
                if ((item.Source == 'NimbeLink' || item.Source == 'DigitalMatter') && $.nullOrEmpty(item.DeviceType)) {
                    return { 'color': 'red' };
                }
            };
            for (var i = 0; i < columnsdata.length; i++) {
                var col = {};
                col.name = columnsdata[i].Id;
                col.caption = columnsdata[i].Name;
                col.visible = true;
                col.sortable = false;
                col.width = columnsdata[i].Width;
                col.key = columnsdata[i].Key;
                col.allowFilter = false;
                if (t == 0) {
                    col.styleFilter = styleFilter;
                }
                columns.push(col);
            }
            grid_import_result.canMultiSelect = false;
            grid_import_result.columns = columns;
            grid_import_result.init();

            var rows = [];
            for (var i = 0; i < data.length; i++) {
                var r = data[i];
                r.checked = true;
                if (r.PairedAsset) {
                    r.VIN = r.PairedAsset.VIN;
                }

                for (var j in r) {

                    if (j === "Status")
                        r[j] = { DisplayValue: r["Status"] === 1 ? "Active" : "Inactive", Value: r[j] };
                    else if (j === "InvoiceDate")
                        r[j] = { DisplayValue: r["InvoiceDateStr"], Value: r[j] };
                    else if (j === "ServiceStartDate")
                        r[j] = { DisplayValue: r["ServiceStartDateStr"], Value: r[j] };
                    else if (j == "Tamper") {
                        r[j] = { DisplayValue: r[j] == 1 ? "Yes" : "No", Value: r[j] };
                    }
                    else if (j == "FIInstalltion") {
                        r[j] = { DisplayValue: r[j] == 1 ? "Yes" : "No", Value: r[j] };
                    }
                    else if (j == "Utilization") {
                        r[j] = { DisplayValue: r[j] == 1 ? "Yes" : "No", Value: r[j] };
                    }
                }
                var fr = { Values: r };
                rows.push(fr);
            }

            grid_import_result.setData(rows);
            grid_import_result.resize();

        }

        var fildata;
        function OnImport() {
            var file = $('<input type="file" style="display: none;" accept=".xlsx" />');
            file.change(function () {
                fildata = this.files[0];
                var formData = new FormData();
                formData.append("iconFile", fildata);
                formData.append("MethodName", "GetImportDevicesColumns");
                formData.append("ClientData", '');
                showloading(true);
                $.ajax({
                    url: 'ManageGPSDevices.aspx',
                    type: 'POST',
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    data: formData,
                    async: true,
                    success: function (data) {
                        if (typeof (data) === "string") {
                            showAlert(data, GetTextByKey("P_JS_IMPORT", 'Import'));
                            showloading(false);
                        } else {
                            CreateImportColumns(data);
                            $('#dialog_import')
                                .attr('act', 'add')
                                .css({
                                    'top': (document.documentElement.clientHeight - $('#dialog_import').height()) / 3,
                                    'left': (document.documentElement.clientWidth - $('#dialog_import').width()) / 2
                                })
                                .showDialogfixed();
                        }
                    },
                    error: function (err) {
                        showloading(false);
                        showAlert(err.statusText, GetTextByKey("P_JS_IMPORT", 'Import'));
                    }
                });
            }).click();
        }

        var importing = false;
        var importCount = 0;
        function OnImportDevices(t) {
            if (!fildata)
                return;

            if (importing)
                return;
            importing = true;
            var item = [];
            var sels = $("select[name='sel_import']");
            var tmp = '';
            for (var i = 0; i < sels.length; i++) {
                var sel = sels[i];
                var id = $(sel).data('id');
                var value = $(sel).val();
                switch (id) {
                    case "Source":
                        if ($.nullOrEmpty(value)) {
                            tmp += GetTextByKey("P_MD_SOURCE", "Source");
                        }
                        break;
                    case "SN":
                        if ($.nullOrEmpty(value)) {
                            if (tmp.length > 0) {
                                tmp += ('/' + GetTextByKey("P_MD_SN", "SN"));
                            }
                            else {
                                tmp += GetTextByKey("P_MD_SN", "SN");
                            }
                        }
                        break;
                }
                var kv = { Key: id, Value: value };
                item.push(kv);
            }
            if (tmp.length > 0) {
                var s = GetTextByKey("P_MA_NOTBEEMPTY", "{0} cannot be empty.").replace('{0}', tmp);
                showAlert(s, GetTextByKey("P_JS_IMPORT", 'Import'));
                importing = false;
                return;
            }
            var selected = [];
            if (t == 1) {
                for (var i in grid_import_result.source) {
                    selected.push(grid_import_result.source[i].Values.checked);
                }
                grid_import_result.setData([]);
            }
            $('#dialog_import_result').hideDialog();
            var param = JSON.stringify(item);
            param = htmlencode(param);
            var contractorid = htmlencode($.trim($('#sel_contractor').val()));
            var formData = new FormData();
            formData.append("iconFile", fildata);
            formData.append("MethodName", "ImportDevices");
            formData.append("ContractorID", contractorid);
            formData.append("Get", t == 1 ? false : true);
            if (t == 1) {
                formData.append("SelectedData", selected.join(','));
            }
            formData.append("ClientData", param);
            showloading(true);
            $.ajax({
                url: 'ManageGPSDevices.aspx',
                type: 'POST',
                dataType: 'json',
                processData: false,
                contentType: false,
                data: formData,
                async: true,
                success: function (data) {
                    importing = false;
                    try {
                        var d = JSON.parse(data);
                        $('#dialog_import').hideDialog();
                        errordata = [];
                        if (d.Count != -1) {
                            grid_import_result.setData([]);
                            $('#sp_import_result').show();
                            $('#sp_import_f').show();
                            $('#btnClose').show();
                            $('#btnOk').hide();
                            $('#btnCancel').hide();
                            var str = d.Count + GetTextByKey("P_MD_DEVICESIMPORTEDSUCCESSFULLY", ' Device(s) imported successfully.');
                            if (d.Datas.length > 0 || (d.Count == 0 && d.Datas.length == 0)) {
                                importCount = d.Count;
                                if (d.Datas.length > 0) {
                                    errordata = $.cloneObject(d.Datas);
                                    $('#div_import_export').show();
                                }
                                else {
                                    $('#div_import_export').hide();
                                }
                                $('#sp_import_result').text(str);
                                $('#sp_import_f').text(d.Datas.length + " Failed.");
                                $('#dialog_import_result')
                                    .css({
                                        'top': (document.documentElement.clientHeight - $('#dialog_import_result').height()) / 3,
                                        'left': (document.documentElement.clientWidth - $('#dialog_import_result').width()) / 2
                                    })
                                    .showDialogfixed();
                                CreateImportResultGrid(d.Datas, t);
                            }
                            else {
                                showAlert(str, GetTextByKey("P_JS_IMPORT", 'Import'), null, function () {
                                    if (d.Count > 0) {
                                        window.location.reload();
                                    }
                                });
                                showloading(false);
                            }
                        }
                        else {
                            $('#dialog_import_result')
                                .css({
                                    'top': (document.documentElement.clientHeight - $('#dialog_import_result').height()) / 3,
                                    'left': (document.documentElement.clientWidth - $('#dialog_import_result').width()) / 2
                                })
                                .showDialogfixed();
                            $('#sp_import_result').hide();
                            $('#div_import_export').hide();
                            $('#sp_import_f').show();
                            $('#btnClose').hide();
                            $('#btnOk').show();
                            $('#btnCancel').show();
                            CreateImportResultGrid(d.Datas, t);
                            $('#sp_import_f').text(GetTextByKey("P_WO_COUNT", 'Count') + ": " + d.Datas.length);
                        }

                    }
                    catch (e) {
                        showAlert(data, GetTextByKey("P_JS_IMPORT", 'Import'));
                        showloading(false);
                    }
                },
                error: function (err) {
                    importing = false;
                    showloading(false);
                    showAlert(err.statusText, GetTextByKey("P_JS_IMPORT", 'Import'));
                }
            });

        }



        function EndImportDevices() {
            $('#dialog_import_result').hideDialog();
            if (importCount > 0) {
                window.location.reload();
            }
            showloading(false);
        }

    </script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div id="recordcontent" style="padding: 0px; margin: 0px;">
        <div class="page_title" data-lgid="P_MANAGEDEVICES">Manage Devices</div>
        <div class="search_bar">
            <input type="password" autocomplete="new-password" style="display: none" />
            <span id="span_contractor" style="display: none;">
                <span data-lgid="P_MD_CONTRACTOR_COLON">Contractor:</span>
                <select id="sel_contractor"></select></span>
            <input type="text" id="searchinputtxt" autocomplete="off" />
            <input class="search" type="button" onclick="OnRefresh();" value="Search" data-lgid="P_MD_SEARCH" style="margin-left: 5px;" />
        </div>
        <div class="function_title">
            <span class="sbutton iconadd" onclick="OnAdd();" data-lgid="P_MD_ADD">Add</span>
            <span class="sbutton iconrefresh" onclick="OnRefresh();" data-lgid="P_MD_REFRESH">Refresh</span>
            <span id="spExport" class="sbutton iconexport" onclick="OnExport();" data-lgid="P_UTILITY_EXPORTTOEXCEL">Export to Excel</span>
            <span class="sbutton iconimport" onclick="OnImport();" data-lgid="P_JS_IMPORT">Import</span>
        </div>
        <div class="clear"></div>
        <div id="devicelist"></div>
    </div>
    <div id="mask_bg" style="display: none;"><div class="loading c-spin"></div></div>
    <div class="dialog" id="dialog_gpsdevice1" style="display: none; height: 100%; border-bottom: 0; border-top: 0; z-index: 2">
        <iframe id="iframe_gpsdevice" style="width: 100%; height: 100%; display: block; border: none" src="AddDevice.aspx"></iframe>
        <div class="maskbg" style="display: none"></div>
    </div>

    <div class="dialog" id="dialog_changecon" style="display: none; width: 360px;">
        <div class="dialog-title"><span class="title" data-lgid="P_MD_CHANGECONTRACTOR">Change Contractor</span><em class="dialog-close"></em></div>
        <div class="dialog-content">
            <table style="line-height: 25px; width: 100%;">
                <tr>
                    <td class="label" data-lgid="P_MD_CONTRACTOR_COLON">Contractor:</td>
                    <td>
                        <select id="dialog_contractor" tabindex="1" style="width: 204px;"></select></td>
                </tr>
                <tr>
                    <td class="label" data-lgid="P_MD_NOTES_COLON">Notes:</td>
                    <td>
                        <textarea id="txtChangeConNotes" style="display: block; width: 240px; box-sizing: border-box; margin-top: 5px; height: 80px"></textarea></td>
                </tr>
            </table>
        </div>
        <div class="dialog-func">
            <input type="button" value="Cancel" class="dialog-close" tabindex="5" data-lgid="P_MD_CANCEL" />
            <input type="button" onclick="ChangeContractor();" value="OK" tabindex="4" data-lgid="P_MD_OK" />
            <div class="clear"></div>
        </div>
    </div>

    <div class="dialog" id="dialog_import" style="display: none;">
        <div class="dialog-title"><span class="title" data-lgid="P_MD_IMPORTDEVICEFIELDMAPPING"></span><em class="dialog-close"></em></div>

        <div class="machine_filter" style="margin: 9px 6px 7px; display: none;">
            <span class="sbutton iconimport" onclick="OnImport()" data-lgid="P_JS_IMPORT">Add</span>
        </div>
        <div class="dialog-content adjust-content" style="overflow: auto;">
            <table id="tb_import" class="table_holder">
            </table>
        </div>

        <div class="dialog-func">
            <input type="button" value="Close" data-lgid="P_JS_CANCEL" class="dialog-close" tabindex="28" />
            <input type="button" onclick="OnImportDevices(0);" value="OK" tabindex="27" />
            <div class="clear"></div>
        </div>
    </div>
    <div class="dialog" id="dialog_import_result" style="display: none;">
        <div class="dialog-title"><span class="title" data-lgid="P_JS_IMPORT"></span></div>

        <div id="div_import_export" class="machine_filter" style="margin: 9px 6px 7px; display: none;">
            <span class="sbutton iconexport" onclick="OnExportInImport()" data-lgid="P_UTILITY_EXPORTTOEXCEL">Export to Excel</span>
        </div>
        <div style="margin: 9px 6px 7px; padding-left: 20px">
            <div id="sp_import_result" style="font-weight: bold;"></div>
        </div>
        <div id="sp_import_f" style="margin: 9px 6px 7px; padding-left: 20px; font-weight: bold;">Failed</div>
        <div id="div_import_grid" style="padding-left: 20px; padding-right: 20px; height: 400px; width: 700px">
        </div>
        <div class="dialog-func">
            <input id="btnCancel" type="button" value="Close" data-lgid="P_JS_CANCEL" class="dialog-close" tabindex="28" />
            <input id="btnOk" type="button" onclick="OnImportDevices(1);" data-lgid="P_JS_IMPORT" tabindex="27" />
            <input id="btnClose" type="button" onclick="EndImportDevices();" data-lgid="P_FR_CLOSE" tabindex="27" />
            <div class="clear"></div>
        </div>
    </div>
</asp:Content>