﻿(function ($) {
    "use strict";

    $(window).on('load', function () {
        $(".spinner").hide();
        $(".hidden-onpage-load").show();
    });

    // Add active state to sidbar nav links
    var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
    $("#layoutSidenav_nav .sb-sidenav a.nav-link").each(function () {
        if (this.href === path) {
            $(this).addClass("active");
        }
    });

    // Toggle the side navigation
    $("#sidebarToggle").on("click", function (e) {
        e.preventDefault();
        $("body").toggleClass("sb-sidenav-toggled");
    });
})(jQuery);

// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.

// Write your JavaScript code.
var addRegistration = false;
var requireCAMAPropertyIDandOwnerID = false;
var count = 0;

function addProperty(el) {
    count = $(".property-data-input") !== null ? $(".property-data-input").length : 0;
    var addedProperty = $('#property');
    var addedPin = $('#pin');

    if (restrictToPrincipalResidence && $(".property-data-input") !== null && $(".property-data-input").length >= 1) {
        return;
    }

    var propertyData = addedProperty.val();
    var pinData = addedPin.val();
    var propertyTable = $('#properties');

    if (addRegistration) {
        addRegistrationProperties(propertyData, propertyTable, count);
    } else if (!addRegistration && addedProperty.val().length > 0 && addedPin.val().length > 0) {
        $('#noPropertiesAddedPlaceholder').addClass('d-none');
        $("#processing").modal('show');
        $.ajax({
            type: 'GET',
            url: '/validate-property-pin?propertyId=' + addedProperty.val() + '&pin=' + addedPin.val(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                if (result) {
                    propertyTable.append('<tr><td><span class="added-properties">' + propertyData + '</span><input class="property-data-input" type=\'hidden\' name=\'PropertyItem[' + count + ']\' value="' + propertyData + '" /></td>' +
                    '<td class="text-center"><buttom class="remove-property-btn" type="button"><i class="fa fa-window-close"></i></buttom></td>');

                    $('#property').val('');
                    $('#pin').val('');
                    count++;

                    if (restrictToPrincipalResidence && $(".property-data-input") !== null && $(".property-data-input").length >= 1) {
                        $(el).prop('disabled', true);
                        $('.add-registration-input').attr('readonly', true);
                    }
                    $("#processing").modal('hide');
                    showSnackBar("Property Verified!", true);
                } else {
                    $("#processing").modal('hide');
                    showSnackBar("Invalid Property and PIN Combination!", false);
                }
            },
            error: function (result) {
                $("#processing").modal('hide');
                showSnackBar("Invalid Property and PIN Combination!", false);
            },
        });
    }
}

function submitProperty() {
    if (count < 1) {
        $("#confirmSubmit").dialog({
            autoOpen: false,
            modal: true,
            dialogClass: 'confirmation-dialog',
            resizable: false,
            buttons: {
                'Yes': function () {
                    $(this).dialog('close');
                    $('#submit').click();
                },
                'No': function () {
                    $(this).dialog('close')
                }
            },
            create: function () {
                $(this).closest('.ui-dialog')
                    .find('.ui-dialog-buttonset').find('button').each(function () {
                    $(this).addClass('btn btn-dark confirmation-button')
                        .removeClass('ui-button');
                });
            }
        });
        $('#confirmSubmit').dialog('open');
    }
    else {
        $('#submit').click();
    }
}

$(document).delegate(".remove-property-btn", "click", function () {
    $(this).parent().parent().remove();
    count --;
    recalcIndexes();

    if ($(".property-data-input") !== null && $(".property-data-input").length < 1) {
        if (restrictToPrincipalResidence) {
            $('.add-registration-btn').prop('disabled', false);
            $('.add-registration-input').attr('readonly', false);
        } else {
            $('#noPropertiesAddedPlaceholder').removeClass('d-none');
        }
    }
});

function recalcIndexes() {
    if (addRegistration) {
        $('.property-data-input').each(function (index, el) {
            $(el).attr('name', 'Input.PropertyOwnerDetails[' + index + '].PropertyDetails');
        });
        $('.cama-property-input').each(function (index, el) {
            $(el).attr('name', 'Input.PropertyOwnerDetails[' + index + '].CamaPropertyId');
        });
        $('.cama-owner-input').each(function (index, el) {
            $(el).attr('name', 'Input.PropertyOwnerDetails[' + index + '].CamaOwnerId');
        });
    } else {
        $('.property-data-input').each(function (index, el) {
            $(el).attr('name', 'PropertyItem[' + index + ']');
        });
    }
}

// Admin


$('.unsubscribed').each(function (index, value) {
    const rowElement = $(this).parent().parent().parent();

    if (value.checked && $(this).hasClass('unsubscribed')) {
        rowElement.children('.cama-info').addClass('d-none');
    }
});

function addRegistrationProperties(propertyData, propertyTable, count) {
    if ($('#property').val() === '') {
        $('#property').addClass('input-validation-error');
        $('#property').parent().find('.requiredMessage').removeClass('d-none');
    }

    if (requireCAMAPropertyIdOwnerID === 'True') {
        if ($('#camaPropertyID').val() === '') {
            $('#camaPropertyID').addClass('input-validation-error');
            $('#camaPropertyID').parent().find('.requiredMessage').removeClass('d-none');
        }

        if ($('#camaOwnerId').val() === '') {
            $('#camaOwnerId').addClass('input-validation-error');
            $('#camaOwnerId').parent().find('.requiredMessage').removeClass('d-none');
        }
    }

    if ($('.cama-info').find('.input-validation-error').length < 1) {
        var addedCamaPropertyId = $('#camaPropertyID').val();
        var addedCamaOwnerId = $('#camaOwnerId').val();

        $('#noPropertiesAddedPlaceholder').addClass('d-none');

        propertyTable.append(
            `<tr class="d-flex">
                        <td class="col-5">
                            <span>${propertyData}</span>
                            <input class="property-data-input" type="hidden" name="Input.PropertyOwnerDetails[${count}].PropertyDetails" value="${propertyData}" />
                        </td>
                        <td class="col-3">
                            <span>${addedCamaPropertyId}</span>
                            <input type="hidden" class="cama-data-input cama-property-input" name="Input.PropertyOwnerDetails[${count}].CamaPropertyId" value="${addedCamaPropertyId}" />
                        </td>
                        <td class="col-3">
                            <span>${addedCamaOwnerId}</span>
                            <input type="hidden" class="cama-data-input cama-owner-input" name="Input.PropertyOwnerDetails[${count}].CamaOwnerId" value="${addedCamaOwnerId}" />
                        </td>
                        <td class="col-1">
                            <buttom class="remove-property-btn" type="button">
                                <i class="fa fa-window-close"></i>
                            </buttom>
                        </td >
                     </tr>`);

        $('#camaPropertyID').val('');
        $('#camaOwnerId').val('');
        $('#property').val('');
        count++;

        if (!$('.requiredMessage').hasClass('d-none')) {
            $('.requiredMessage').addClass('d-none');
        }
    }
}

$(document).ready(function () {
    count = $('.added-properties').length;

    $('.state-select').change(function () {
        var selected = $(this).children("option:selected").val();
        $('form').validate({
            ignore: "#Zip"
        });

        if (selected === 'NA') {
            $('.province-control').prop('disabled', false)
                .prop('readonly', false)
                .prop('required', true);
            $('.country-control').prop('disabled', false);
        } else {
            $('.province-control').prop('disabled', true)
                .prop('readonly', true)
                .prop('required', false);
            $('.country-control').prop('disabled', true);
        }
    });
});