function displayErrors(response, id) {
    console.log(response, 1);
    var errorsHtml = '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
    $.each(response.errors, function (key, value) {
        errorsHtml += '<p class="mb-0" >' + value + '</p>'; //showing only the first error.
    });
    errorsHtml += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true"><i class="feather icon-x-circle"></i></span></button></div>';
    $('#' + id).html(errorsHtml).show();
}

function ajaxRequest(url, type, dataType, data, callBack, errorCallBack) {

    $.ajax({
        url: url,
        type: type,
        data: data,
        dataType: dataType,
        cache: false,
        success: function (result) {
            callBack(result);
        },
        error: function (jqXHR, error, errorThrown) {
            if (dataType == "json") {
                displayErrors(jqXHR.responseJSON, "errors");
                //  alert(jqXHR.responseText);
            } else {
                errorCallBack(jqXHR, error, errorThrown);
            }
        }
    });
}

$(document).ready(function () {


    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $(document).on("click", ".excesses", function () {

        var excess_id = $(this).data("excess-id");
        var excessCategoryId = $(this).data("category-id");
        $(".excess-" + excessCategoryId).removeClass("active");
        type = $('#type').val();
        $(this).addClass("active");
        $('#excess_id').val(excess_id);

        if ($('#category_id').length > 0) {

            var category_id = $('#category_id').val();

            packages = JSON.parse($('#packages_' + category_id).val());
            $.each(packages, function (key, value) {
                $('#price_' + key).html(value.prices[type][excess_id]["total_price"]);
                setPrices(value)
            });
        } else {
            packages = JSON.parse($('#package').val());
            $('.package-price').html(packages.prices[type][excess_id]["total_price"]);
            setPrices(packages)
        }
    });

    $(document).on("click", ".types", function () {
        type = $(this).data("type-id");
        var typeCategoryId = $(this).data("category-id");
        $(".type-" + typeCategoryId).removeClass("active");
        var excess_id = $('#excess_id').val();
        $('#type').val($(this).data("type-id"));
        $(this).addClass("active");

        $(".timeperiod").html(type);

        if ($('#category_id').length > 0) {

            var category_id = $('#category_id').val();
            packages = JSON.parse($('#packages_' + category_id).val());

            $.each(packages, function (key, value) {
                $('#price_' + key).html(value.prices[type][excess_id]["total_price"]);
                setPrices(value)
            });
        } else {
            packages = JSON.parse($('#package').val());
            $('.package-price').html(packages.prices[type][excess_id]["total_price"]);
            setPrices(packages);
        }

    });

    $(document).on("click", ".apply-now", function () {
        var package = $(this).data("package");
        type = $('#type').val();
        excess_id = $('#excess_id').val();
        var dataType = "json";
        var facilities = $('.package-' + package + ':checkbox:checked').map(function () {
            var fid = this.value;
            return fid;
        }).get();

        var data = { type: type, excess_id: excess_id, package: package, facilities: facilities };
        var callBack = function (response) {
            if (response.error === 1 || response.error === true) {
                displayErrors(response, "errors");
            } else if (response.status == true) {
                window.location.href = response.url;
            }
        };

        var errorCallBack = function (response) {
            alertMessage('success');
        };

        ajaxRequest(url + "/applynow", "POST", dataType, data, callBack, errorCallBack);

    });

    $(document).on("click", ".service-switch", function () {

        var package_id = $(this).data("package");

        if ($('#category_id').length > 0) {
            var category_id = $('#category_id').val();

            packages = JSON.parse($('#packages_' + category_id).val());
            setPrices(packages[package_id])

        } else {
            packages = JSON.parse($('#package').val());
            setPrices(packages)
        }
    });

    if ($('.request_callback_btn').length > 0) {
        $(document).on("click", ".request_callback_btn", function () {
            $('html, body').animate({
                scrollTop: $(".request_callback").offset().top
            }, 1000);
        });
    }

});

function log(str) {
    console.log(str)
}

function setPrices(package) {

    var excess_id = $('#excess_id').val();
    var type = $('#type').val();

    log(package.prices)
    var price = package.prices[type][excess_id]["total_price"];
    price = parseFloat(price);
    var package_id = package.id;

    if (!isNaN(price)) {

        var total = 0;

        var checkedVals = $('.package-' + package_id + ':checkbox:checked').map(function () {
            var fid = this.value;
            var p = $("#customSwitch" + package_id + "_" + fid).data("price");
            total += parseFloat(p);
            return fid;
        }).get();
        if (checkedVals != "") {
            price = price + total;
        }

        if (package.customizable == true && type == "yearly") {
            //price = price * 12;
            //$("#price_" + package_id).text(parseFloat(price).toFixed(2));
            $("#price_" + package_id).parent().next(".timeperiod").text("monthly")
        }

        $("#price_" + package_id).text(parseFloat(price).toFixed(2));
    }
}


