'use strict';
$(document).ready(function () {
    initEditor();
    $.ajaxSetup({

        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        error: function (jqXHR) {
            if (globalErrorHandler(jqXHR.responseJSON))
                return false
        }

    });

    $('input[id="files"]').fileuploader({
        limit: 1,
        dialogs: {
            alert: function (text) {
                Swal.fire({
                    icon: 'error',
                    title: '',
                    text: text,
                    position: 'bottom'
                })
            },
            // confirm dialog
            confirm: function (text, callback) {
                Swal.fire({
                    title: 'Are you sure?',
                    text: text,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, delete it!',
                    position: 'bottom',
                }).then((result) => {
                    if (result.isConfirmed) {
                        callback()
                    }
                })

            }
        }
    });
});

function doAccountLoginContactFrom() {
    let email = $("#email").val();
    let name = $("#name").val();
    let message = $("#message").val();
    let description = $('#description').summernote('isEmpty');
    if (typeof description != "object") {
        description = description
    } else {
        if (message == '') {

            description = true;
        } else {
            description = false;
        }
    }
    let category = $('#category').val()
    let emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    $("#email").removeClass("border-danger");
    $("#subject").removeClass("border-danger");
    $("#name").removeClass("border-danger");
    $("#country").removeClass("border-danger");
    $("#message").removeClass("border-danger");
    $("#description").removeClass("border-danger");
    $('#category').removeClass("border-danger");
    $(".error-email").slideUp();
    $(".error-subject").slideUp();
    $(".error-name").slideUp();
    $(".error-country").slideUp();
    $(".error-message").slideUp();
    $(".error-email-vaild").slideUp();
    $(".error-recaptcha").slideUp();
    $('.error-category').slideUp();
    if (category != "Choose Category") {

        if (name != "") {
            if (email != "") {
                if (description == false) {
                    if (emailReg.test(email)) {
                        $(".send-msg").attr("disabled", true);
                        let form_data = new FormData($("#enquiries")[0]);
                        if ($("div").hasClass("recaptcha")) {
                            let rcres = grecaptcha.getResponse();
                            if (rcres.length) {

                                submitForm(form_data);
                            } else {
                                $(".error-recaptcha").slideDown();
                                $(".send-msg").attr("disabled", false);
                            }
                        } else {
                            submitForm(form_data);
                        }
                    } else {
                        $("#email").addClass("border-danger");
                        $(".error-email-vaild").slideDown();
                    }
                } else {
                    $("#message").addClass("border-danger");
                    $(".error-message").slideDown();
                    $('#message').focus()
                }
            } else {
                $("#email").addClass("border-danger");
                $(".error-email").slideDown();
                $('#email').focus()
            }
        } else {
            $("#name").addClass("border-danger");
            $(".error-name").slideDown();
            $('#name').focus()
        }
    } else {
        $("#category").addClass("border-danger");
        $(".error-category").slideDown();
        $('#category').focus()
    }
}

function submitForm(form_data) {
    $(".btn-submit-ticket").attr("disabled", true);
    $(".btn-submit-ticket").html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
    let sendUrl = $("#enquiries").attr("action")
    $.ajax({
        url: sendUrl,
        type: "POST",
        data: form_data,
        processData: false,
        contentType: false,
        success: function (data) {
            if ($("div").hasClass("recaptcha")) {
                grecaptcha.reset();
            }
            $(".send-msg").attr("disabled", false);
            $(".btn-submit-ticket").attr("disabled", false);
            $(".btn-submit-ticket").html('Submit Ticket');
            clearEditor();
            if (data.status == true) {
                $("#enquiries").trigger("reset");
                showConfirmationModal('Thank you for contacting us!','We have received your message, please allow 48 hours to receive a reply.' ,'' , function() {
                });
            } else {
                swalMsg("something went wrong.","error");
            }
        },
        error: function (jqXHR) {
            grecaptcha.reset();

            $(".send-msg").attr("disabled", false);
            if (globalErrorHandler(jqXHR.responseJSON))
                return false
        },
    });
}

function initEditor() {
    if ($('#description').length) {
        $('#description').summernote({
            height: 300,
            dialogsInBody: true,
            codeviewFilter: false,
            codeviewIframeFilter: true,
            callbacks: {
                onImageUpload: function (image) {
                    uploadImage(image[0]);
                },
                onImageUploadError: function (msg) {
                    Swal.fire({
                        icon: 'error',
                        title: '',
                        text: msg + " (" + fileSizeLimit + " MB)",
                        position: 'bottom'
                    })
                }
            },
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline', 'clear']],
                ['fontname', ['fontname']],
                ['fontsize', ['fontsize']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['height', ['height']],
                ['table', ['table']],
                ['insert', ['link', 'picture', 'video', 'hr']],
                ['view', ['fullscreen']],
                ['help', ['help']]
            ]
        });
    }
}

function uploadImage(image) {
    let data = new FormData();
    data.append("image", image);
    let uploadUrl = $("#uploadUrl").val();
    $.ajax({
        url: uploadUrl,
        cache: false,
        contentType: false,
        processData: false,
        data: data,
        type: "post",
        success: function (url) {
            let image = $('<img>').attr('src', url);
            $('#description').summernote("insertNode", image[0]);
        },

    });
}

function clearEditor() {
    $('#description').summernote('code', '');
}
