<script src="/js/plugins/tabledit/tabledit.js"></script>
<script src="/js/plugins/chosen/chosen.jquery.js"></script>
<script src="/js/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="/js/plugins/dataTables/datatables.min.js"></script>
<script src="/js/plugins/dataTables/dataTables.fixedHeader.min.js"></script>
<script src="/js/plugins/chosen/chosen.ajaxaddition.jquery.js"></script>
<link href="/css/plugins/dataTables/fixedHeader.dataTables.min.css" rel="stylesheet">
<script src="/js/hardware-filter.js"></script>
<script>

    @if ($errors->count() > 0)
        $("#addAsnMapping").modal({ show: true });
    @endif

    $('.select2').select2();
    $(document).ready(function () {
        $.fn.serializeObject = function () {
            var obj = {};
            $.each(this.serializeArray(), function (i, o) {
                var n = o.name, v = o.value;
                obj[n] = obj[n] === undefined ? v
                    : $.isArray(obj[n]) ? obj[n].concat(v)
                        : [obj[n], v];
            });

            return obj;
        };
        $('.chosen-select').chosen({ width: "100%" });
        $('.make_model').chosen({ width: "100%" });

        var table = $('#receive-connection-assets-table').DataTable({
            scrollX: true,
            scrollY: '400px',
            scrollCollapse: true,
            "processing": true,
            "serverSide": true,
            paging: true,
            "pageLength": 50,
            lengthMenu: [
                [50, 100, 200],
                ['50', '100', '200']
            ],
            columnDefs: [
                { orderable: false, targets: '_all' },
            ],
            "aaSorting": [],
            "dom": '<"top"i>rt<"bottom"flp><"clear">',
            "bAutoWidth": true,
            "bFilter": true,
            "bLengthChange": false,
            "searching": false,
            "fnDrawCallback": function() {
                $('[data-tooltip="tooltip"]').tooltip({
                    container: "body"
                });

            },
            "fnInitComplete": function (oSettings, json) {
                $("#receive-connection-assets-table_paginate").children().before("<p style='float:left; margin-top: 8px'>Last Sync: {{ $lastSyncDate ?? '' }}</p>")
            },
            "ajax": {
                "url": "{{ route('connection-data') }}",
                "dataType": "json",
                "type": "POST",
                "data": function (result) {
                    result.form = $('#connection-filter-form').serializeObject();
                }
            },
            "columns": [
                { "data": "id" },
                { "data": "checkbox" },
                { "data": "asset_tag" },
                { "data": "serial_no" },
                { "data": "po_no" },
                { "data": "asset_type" },
                { "data": "part_no" },
                { "data": "hardware" },
                { "data": "tech_spec" },
                { "data": "tracking_number" },
                { "data": "shipment_status" },
                { "data": "edit" },
            ]
        });

        $('#export-connection-asset-csv').on('click', function (e) {
            e.preventDefault();
            $('.ajax-loader').show();
            $.ajax({
                type: "POST",
                url: "/connection-asset-export",
                data: $('#connection-filter-form').serializeObject(),
                dataType: 'text',
                success: function (result) {
                    var blob = new Blob([result]);
                    if (window.navigator.msSaveOrOpenBlob)  // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
                        window.navigator.msSaveBlob(blob, "connection-asset.csv");
                    else {
                        var a = window.document.createElement("a");
                        a.href = window.URL.createObjectURL(blob, { type: "text/plain" });
                        a.download = "connection-asset.csv.csv";
                        document.body.appendChild(a);
                        a.click();  // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
                        document.body.removeChild(a);
                    }
                    $('.ajax-loader').hide();
                }
            })
        });

        $("#checkedAll").change(function () {
            if (this.checked) {
                $(".checkSingle").each(function () {
                    if (!$(this).is(':disabled')) {
                        this.checked = true;
                    }
                })
            } else {
                $(".checkSingle").each(function () {
                    if (!$(this).is(':disabled')) {
                        this.checked = false;
                    }
                })
            }
        });

        $(document).on("click", ".checkSingle", function (e) {
            if ($(this).is(":checked")) {
                var isAllChecked = 0;
                $(".checkSingle").each(function () {
                    if (!this.checked)
                        isAllChecked = 1;
                })
                if (isAllChecked == 0) { $("#checkedAll").prop("checked", true); }
            } else {
                $("#checkedAll").prop("checked", false);
            }
        });


        $('#manual-sync').on('click', function (e) {
            e.preventDefault();
            $('.ajax-loader').show();
            $(".sync-msg").hide();
            $('#manual-sync').hide();
            $('#manual-sync-load').show();
            $("#sync-success-msg").html('Manual sync started.');
            $("#sync-success").show();
            $.ajax({
                type: "POST",
                url: "/connection-asset-sync",
                data: $('#connection-filter-form').serializeObject(),
                dataType: 'json',
                success: function (data) {
                    $('.ajax-loader').hide();
                    $(".sync-msg").hide();
                    $("#sync-success-msg").html('');
                    $('#manual-sync-load').hide();
                    if (data.status == 'success') {
                        $("#sync-success-msg").html(data.message);
                        $("#sync-success").show();
                        $('#connection-filter-form').submit();
                    } else {
                        $("#sync-error-msg").html(data.message);
                        $("#connectionErrorDetail").html(data.errors);
                        $("#sync-error").show();
                    }
                    $('#manual-sync').show();
                    $('html, body').animate({
                        scrollTop: $("#error").offset().top
                    }, 3000);
                }
            }).fail(function(jqXHR, textStatus, error){
                $('.ajax-loader').hide();
                $(".sync-msg").hide();
                $("#sync-success-msg").html('');
                $('#manual-sync-load').hide();
                $("#sync-error-msg").html("Some error occured.");
                $("#sync-error").show();
            })
        });

        $('#mapping-submit').click(function () {
            $('#connection-mapping-form').submit();
        });

        $('#markReceived').click(function () {
            var location = $("#location_id").val();
            var ticket = $("#ticket").val();
            var received = [];
            $("input:checkbox[name=receiveAsset]:checked").each(function () {
                received.push($(this).val());
            });
            if (location == '') {
                $('#error').show();
                $('#error p').text("A location must be selected.");
                $('html, body').animate({
                    scrollTop: $("#error").offset().top
                }, 1000);
            }
            if (ticket == '') {
                $('#error').show();
                $('#error p').text("Ticket is required.");
                $('html, body').animate({
                    scrollTop: $("#error").offset().top
                }, 1000);
            }
            else if (received.length == 0) {
                $('#error').show();
                $('#error p').text("At least one asset must be selected.");
                $('html, body').animate({
                    scrollTop: $("#error").offset().top
                }, 1000);
            }

            else {
                $('.ajax-loader').show();
                $.ajax({
                    type: 'POST',
                    url: "{{ url('/receive-connection-asset/mark-as-received') }}",
                    data: { location: location, received: received, ticket: ticket, "_token": "{{ csrf_token() }}" },
                    success: function (data) {

                        if (data != 'Success') {
                            $('#error').show();
                            $('#error p').text(data);
                            $('html, body').animate({
                                scrollTop: $("#error").offset().top
                            }, 3000);
                        } else {
                            $('#sync-success').show();
                            $('#sync-success-msg').text("Asset(s) recieved to the selected location.");
                            $('html, body').animate({
                                scrollTop: $("#error").offset().top
                            }, 1000);
                        }
                        $('#connection-filter-form').submit();
                        $('.ajax-loader').hide();
                    },
                    error: function (data) {
                    }
                });
            }
        });

        $(".filter-field-location").each(function () {
            var name = $(this).attr('key');
            $(this).select2({
                minimumInputLength: 1,
                ajax: {
                    url: '/get-filter-fields-location',
                    dataType: "json",
                    data: function (params) {
                        var query = {
                            search: params.term,
                            type: name
                        }

                        // Query parameters will be ?search=[term]&type=public
                        return query;
                    },
                    processResults: function (data) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        return {
                            results: data
                        };
                    },

                }
            });
        });


        var delay = (function () {
            var timer = 0;
            return function (callback, ms) {
                clearTimeout(timer);
                timer = setTimeout(callback, ms);
            };
        })();


        $("#asset_tag, #serial_no, #logged_in, #shipment_status, #searchText").on('change', function () {
            $('#connection-filter-form').submit();
        })

        $("#email").on('keyup change', function () {
            delay(function () {
                $('#connection-filter-form').submit();
            }, 200);
        });

        $('#connection-filter-form').submit(function (e) {
            e.preventDefault();
            table.draw();
        });

        $(".filter-field").each(function () {
            var name = $(this).attr('key');
            $(this).select2({
                tokenizer: function (input, s2, callback) {
                    var term = input.term;
                    if (term.indexOf(',') < 0)
                        return input; // Exit if no tokens

                    var parts = term.split(",");
                    for (var i = 0; i < parts.length; i++) {
                        var part = parts[i].trim();
                        if (part.length > 2) {
                            $.ajax({
                                url: s2.options.ajax.url,
                                dataType: s2.options.ajax.dataType,
                                data: s2.options.ajax.data({ term: part }),
                                async: false, // If async then unable to return unmatched tokens
                                success: function (data) {
                                    var pr = s2.options.ajax.processResults(data, { term: part });
                                    if (pr.results[0].value != 0) {
                                        callback(pr.results[0]);
                                        parts.splice(i--, 1);
                                    }
                                }
                            });
                        }
                    }
                    return { term: parts.join(',') }; // Rejoin unmatched tokens
                },
                minimumInputLength: 1,
                multiple: true,
                ajax: {
                    url: '/get-filter-fields',
                    dataType: "json",
                    data: function (params) {
                        var query = {
                            search: params.term,
                            type: name
                        }
                        return query;
                    },
                    processResults: function (data) {
                        return {
                            results: data
                        };
                    },

                }
            });
        });

        $('#deleteAssetModal').on('show.bs.modal', function (e) {
            var id = $(e.relatedTarget).data('id');
            $('#delete-asset-id').val(id);

        });


        $('#delete-asset-form').submit(function (e) {
            e.preventDefault();
            var id = $('#delete-asset-id').val();
            $.ajax({
                type: "POST",
                url: "/connection-asset-delete/" + id,
                success: function (value) {
                    $('#sync-success').show();
                    $('#sync-success-msg').text("Deleted Successfully");
                    $('html, body').animate({
                        scrollTop: $("#error").offset().top
                    }, 1000);
                    table.draw();

                }
            });
            $('#deleteAssetModal').modal('toggle');


            table.draw();
        });


        $('#editModal').on('show.bs.modal', function (e) {
            var id = $(e.relatedTarget).data('asset-id');
            $.ajax({
                type: "POST",
                url: "connection-asset-get/" + id,
                success: function (value) {
                    $('#modal_asset_id').val(id);
                    $('#asset_serial_no').val(value['serial_no']);
                    $('#asset_asset_tag').val(value['asset_tag']);
                    $('#asset_description').html(value['part_no']);
                    $('#asset_po_no').val(value['po']);
                    $('#modal_asset_type').val(value['assettype']);
                    $('#modal_asset_type').trigger("chosen:updated");
                    $('#modal_hardware').val(value['hardware']);
                    $('#modal_tech').val(value['techspec']);

                    getHardwareStandards(value['hardware'], value['assettype']);
                    getTechSpecs(value['techspec'], value['hardware']);

                }
            });
        });

        $('#modal_asset_type').change(function (e) {
            var assettype = this.value;
            getHardwareStandards(0, assettype);
        });

        $('#modal_hardware').change(function (e) {
            getTechSpecs(0, this.value);
        });
        $('#submit').click(function () {
            $('#edit-asset').submit();
        });
        $('#edit-asset').submit(function (e) {
            e.preventDefault();

            $.ajax({
                type: "POST",
                url: "/connection-asset-update",
                data: $('#edit-asset').serializeObject(),
                dataType: 'text',
                success: function (data) {
                    $('#editModal').modal('hide')
                    if (data != 'success') {
                        $('#error').show();
                        $('#error p').text(data);
                        $('html, body').animate({
                            scrollTop: $("#error").offset().top
                        }, 3000);
                    }
                    else {
                        $("#sync-success-msg").html("Updated Successfully");
                        $("#sync-success").show();
                        $('html, body').animate({
                            scrollTop: $("#error").offset().top
                        }, 1000);
                    }
                    $('#connection-filter-form').submit();


                }
            });

            table.draw();
        });

    });
    function selectAll() {
        var selectAll = $('.selectAll').text();
        if (selectAll == 'Select All') {
            $(".receiveAsset").not(":disabled").prop('checked', true);;
            $('.selectAll').text("Deselect All");
        }
        if (selectAll == 'Deselect All') {
            $(".receiveAsset").prop('checked', false);
            $('.selectAll').text("Select All");
        }

    }

    function getHardwareStandards(currentHardware, assettype) {
        $.ajax({
            type: "POST",
            url: "/connection-asset-get-hardware",
            dataType: 'json',
            data: { assettype: assettype, "_token": "{{ csrf_token() }}" },
            dataType: 'text',
            success: function (outputfromserver) {
                var data = JSON.parse(outputfromserver);
                $('#modal_hardware').empty();
                $.each(data, function (key, value) {
                    $('#modal_hardware')
                        .append($("<option></option>")
                            .attr("value", key)
                            .text(value));
                });
                if (currentHardware != 0) {
                    $('#modal_hardware').val(currentHardware);
                }
                $('#modal_hardware').trigger("chosen:updated");

            }
        });


    }

    function getTechSpecs(currentTechSpec, techSpec) {
        $.ajax({
            type: "POST",
            url: "/connection-asset-get-tech-spec",
            dataType: 'json',
            data: { techSpec: techSpec, "_token": "{{ csrf_token() }}" },
            dataType: 'text',
            success: function (outputfromserver) {
                var data = JSON.parse(outputfromserver);
                $('#modal_tech').empty();
                $.each(data, function (key, value) {
                    $('#modal_tech')
                        .append($("<option></option>")
                            .attr("value", key)
                            .text(value));
                });
                if (currentTechSpec != 0) {
                    $('#modal_tech').val(currentTechSpec);
                }
                $('#modal_tech').trigger("chosen:updated");

            }
        });
    }

    /**
     * Fill the hardware mapping part no in hw mapping modal
     * @param mixed description
     *
     * @return
     */
    function addAsnMapping(description) {
        // $("#addshiMapping").modal({ show: true });
        $("#manf-part").val('').prop('readonly', false);
        if (description) {
            $('#sync_now').val(1);
            $("#manf-part").val(description).prop('readonly', true);
        }
    }

</script>