function startLoading(container) {
    var content = '<div class="sync-loader"></div>';
    var mainContainer = $("#" + container);
    mainContainer.html(content);
}

function dateTimePicker() {
    $('.datetimepicker').datetimepicker({
        format: 'DD.MM.YYYY HH:mm'
    });

    $(function () {
        $.validator.methods.date = function (value, element) {
            return this.optional(element) || moment(value, "DD.MM.YYYY HH:mm", true).isValid();
        }
    });
}

$('#checkAll').click(function (e) {
    var table = $(e.target).closest('table');
    $('td input:checkbox', table).prop('checked', this.checked);
});

$(document).on('click', '.add-tables', function () {

    var selected = [];
    var scheduleId = $(this).attr("data-schedule-id");
    var url = $(this).attr("data-url");

    $('.table-checked:checkbox:checked').each(function () {
        var Id = $(this).val();
        selected.push(Id);
    });

    $.ajax({
        cache: false,
        type: "post",
        url: url,
        data: {
            selectedTables: selected,
            scheduleId: scheduleId
        },
        success: function (result) {
            console.log("success");
            location.reload();
        },
        error: function () {
            console.log("Something went wrong");
        }
    });

});

$('#SegmentTable input[type=checkbox]').on('change', function () {
    var len = $('#SegmentTable input[type=checkbox]:checked').length;
    if (len > 0) {
        $(".add-tables").show();
    } else if (len === 0) {
        $(".add-tables").hide();
    }
}).trigger('change');

$(function () {
    $(document).on('click', '.open-modal', function () {
        $.fn.modal.Constructor.prototype.enforceFocus = function () { };
        $('#ModalId').modal('show');
        var $buttonClicked = $(this);
        //var id = $buttonClicked.attr('data-id');
        var url = $buttonClicked.attr('data-url');
        var title = $buttonClicked.attr('data-modal-title');

        var options = { "backdrop": "true", keyboard: true };
        $.ajax({
            type: "GET",
            url: url,
            contentType: "application/json; charset=utf-8",
            // data: { "Id": id },
            datatype: "json",
            success: function (data) {

                $('#ModalContent').html(data);

                $('#ModalTitle').html(title);

                $('#ModalId').modal(options);
            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    });
});

$('#abIsDefault').on('change', function () {
    if ($('#abIsDefault').is(":checked")) {
        $('.default-schedule').show();
    } else {
        $('.default-schedule').hide();
    }
}).trigger('change');

function scheduleType() {
    var value = $("[name='ScheduleType']:checked").val();
    console.log(value);
    if (value === "Manual") {
        $('.manual-schedule').show();
    } else {
        $('.manual-schedule').hide();
    }
}

$(document).ready(function () {
    dateTimePicker();
});

function disconnectDevice(id, docType) {
    $('#ModalId').modal('show');

    $("#ModalTitle").text("Warning!");
    $("#ModalContent").text("Are you sure you want to disconnect device?");
    if (!$("#confirmButton").length) {
        $("#ModalFooter").prepend('<input type="button" id="confirmButton" class="btn btn-default" value="Confirm" onclick="confirmDisconnectDevice(' + id + ', ' + docType + ')" />')
    }
}

function confirmDisconnectDevice(id, docType) {
    var url = $("#DisconnectDeviceUrl").val();
    var redirectUrl = $("#ConnectedDevicesUrl").val();

     $.ajax({
        type: "POST",
        url: url,
        data: {
            deviceId: id,
            docType: docType
        },
         success: function (response) {
             if (response.success == true) {
                 window.location.href = redirectUrl + "?message=" + response.message;
             }
        },
        error: function () {
            console.log("Something went wrong");
        }
    });
}

function deleteColumnValue(id, tableName) {
    $('#ModalId').modal('show');
    $("#ModalTitle").text("Warning!");
    $("#ModalContent").text("Are you sure you want to delete this?");
    if (!$("#confirmButton").length) {
        $("#ModalFooter")
            .prepend("<input type='button' id='confirmButton' class='btn btn-default' value='Confirm' onclick=confirmDeleteColumnValue(" + id + ",'" + tableName + "') />")
    }
}

function confirmDeleteColumnValue(id, tableName) {

    var url = $("#DeleteColumnValueUrl").val();
    var redirectUrl = $("#RedirectUrl").val();
    

    $.ajax({
        type: "POST",
        url: url,
        data: {
            id: id,
            tableName: tableName
        },
        success: function (response) {
            if (response.success == true) {
                window.location.href = redirectUrl + "?tableName=" + response.tableName + "&message=" + response.message;
            }
        },
        error: function () {
            console.log("Something went wrong");
        }
    });
}

function deleteReferencedTable(id, tableName) {
    $('#ModalId').modal('show');
    $("#ModalTitle").text("Warning!");
    $("#ModalContent").text("Are you sure you want to delete this?");
    if (!$("#confirmButton").length) {
        $("#ModalFooter")
            .prepend("<input type='button' id='confirmButton' class='btn btn-default' value='Confirm' onclick=confirmDeleteReferencedTable(" + id + ",'" + tableName + "') />")
    }
}

function confirmDeleteReferencedTable(id, tableName) {

    var url = $("#DeleteReferencedTableUrl").val();
    var redirectUrl = $("#RedirectUrl").val();

    $.ajax({
        type: "POST",
        url: url,
        data: {
            id: id,
            tableName: tableName
        },
        success: function (response) {
            if (response.success == true) {
                window.location.href = redirectUrl + "?tableName=" + response.tableName + "&message=" + response.message;
            }
        },
        error: function () {
            console.log("Something went wrong");
        }
    });
}

var $rows = $("#partial-sync-tbody tr");
$("#search-partial-sync").keyup(function () {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

    $rows.show().filter(function () {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
    }).hide();
});

function openColumnValueModal(id, tableName, edit) {
    var url = $("#EditColumnValueUrl").val();

    $.ajax({
        type: "GET",
        url: url,
        data: {
            id: id,
            tableName: tableName
        },
        success: function (data) {
            if (edit) {
                $("#column-value-div .modal-title").text("Edit column value");
            } else {
                $("#column-value-div .modal-title").text("Add new column value");
            }
            $("#column-value-div").html(data);
            $("#column-value-modal").modal("show");
        },
        error: function () {
            console.log("Something went wrong");
        }
    })
}

function openReferencedTableModal(id, tableName, edit) {
    var url = $("#EditReferencedTableUrl").val();

    $.ajax({
        type: "GET",
        url: url,
        data: {
            id: id,
            tableName: tableName
        },
        success: function (data) {
            if (edit) {
                $("#referenced-table-div .modal-title").text("Edit column value");
            } else {
                $("#referenced-table-div .modal-title").text("Add new column value");
            }
            $("#referenced-table-div").html(data);
            $("#referenced-table-modal").modal("show");
        },
        error: function () {
            console.log("Something went wrong");
        }
    })
}