$(document).ready(function () {
    $('#popupShippingAddressError').hide();

    if ($(':radio[name="rblAddress"]').length > 0) {
        $(':radio[name="rblAddress"]:first', this).get(0).checked = true;
    }

    $("#m_rdoUseNewAddress").change(function () {
        var url = "InitializeNewAddressFields";

        $.ajax({
            dataType: "json",
            method: "get",
            cache: false,
            url: url
        }).done(function (result) {
            $("#m_rdoUseSubscriberAddress").prop('checked', false);
            $("#m_rdoUseNewAddress").prop('checked', true);

            $("#m_txtFirstName").val(result.FirstName);
            $("#m_txtLastName").val(result.LastName);
            $("#m_txtAddress").val(result.Address.Address1);
            $("#m_txtAddress2").val(result.Address.Address2);
            $("#m_txtCity").val(result.Address.City);

            $("#m_ddlCountry option").eq(0).prop('selected', true);

            $("#m_ddlState option").eq(0).prop('selected', true);

            $("#m_txtPostalCode").val(result.Address.PostalCode);
            $('input[name=ValidatedAddress]').val(result.ValidatedAddress);
            $('#popupShippingAddress').hide();
        });
    });

    $("#m_rdoUseSubscriberAddress").change(function () {
        var url = "GetSubscriberExisitingAddress";
        $.ajax({
            dataType: "json",
            method: "get",
            cache: false,
            url: url
        }).done(function (result) {
            $("#m_rdoUseSubscriberAddress").prop('checked', true);
            $("#m_rdoUseNewAddress").prop('checked', false);

            $("#m_txtFirstName").val(result.FirstName);
            $("#m_txtLastName").val(result.LastName);
            $("#m_txtAddress").val(result.Address.Address1);
            $("#m_txtAddress2").val(result.Address.Address2);
            $("#m_txtCity").val(result.Address.City);

            $("#m_ddlCountry option").filter(function () {
                return this.text == result.Address.Country;
            }).attr('selected', true);

            $("#m_ddlState option").filter(function () {
                return this.text == result.Address.State;
            }).attr('selected', true);

            $("#m_txtPostalCode").val(result.Address.PostalCode);
            $('input[name=ValidatedAddress]').val(result.ValidatedAddress);
            $('#hdn_Country').val(result.Address.Country);
            $('#hdn_State').val(result.Address.State);
        });
    });

    $("#m_ddlCountry").change(function () {
        var url = "GetStatesInCountry";
        var country = $('#m_ddlCountry :selected').text();
        $.ajax({
            datatype: "json",
            method: "get",
            data: { 'countryID': $(this).val() },
            cache: false,
            url: url
        }).done(
            function (states) {
                $('#hdn_Country').val(country);
                $("#m_ddlState").html("");
                $.each(states, function (key, state) {
                    $("#m_ddlState").append("<option value='" + state.ID + "'>" + state.Name + "</option>");
                });
            }
        );
    });

    $("#m_ddlState").change(function () {
        var state = $('#m_ddlState :selected').text();
        $('#hdn_State').val(state);
    });

    $(".rbl").change(function () {
        // Get the total number of addresse returned by validation
        var totalNumberOfAddresses = $(':radio[name="rblAddress"]').length;

        // Get the index of the radio button clicked
        var indexSelectedAddress = $(':radio[name="rblAddress"]:checked').index(':radio[name="rblAddress"]');

        var error = 'This address is NOT validated. Press "Cancel" and edit the address or "Continue" to use the selected address.';

        // If the address selected is the same as the one entered
        if (indexSelectedAddress == (totalNumberOfAddresses - 1)) {
            // Display the warning message
            $('#popupShippingAddressError').text(error);
            $('#popupShippingAddressError').show();
        } else {
            // Hide the warning message
            $('#popupShippingAddressError').text('');
            $('#popupShippingAddressError').hide();
        }
    });

    $("#m_btnSelectMatchingAddress").click(function () {
        // Create a JSON address
        var shpAddressVM = new Object();

        // Get which radio button "Use Subscriber Address" or "Use a New Address" is clicked
        var isExisting = $(':radio[name="IsExistingAddress"]:checked').index(':radio[name="IsExistingAddress"]');

        // If selected index is 0 set to use the existing address as true else false
        shpAddressVM.IsExistingAddress = isExisting == 0 ? 'true' : 'false';

        // Get the various field values and set object properties
        shpAddressVM.FirstName = $('#m_txtFirstName').val();
        shpAddressVM.LastName = $('#m_txtLastName').val();

        // Get the total number of addresse returned by validation
        var totalNumberOfAddresses = $(':radio[name="rblAddress"]').length;

        // Get the index of the radio button clicked
        var indexSelectedAddress = $(':radio[name="rblAddress"]:checked').index(':radio[name="rblAddress"]');

        // If the address selected is the same as the one entered, mark the adress as NOT VALIDATED
        if (indexSelectedAddress == (totalNumberOfAddresses - 1)) {
            shpAddressVM.AddressIsValidated = 0;
        } else
            shpAddressVM.AddressIsValidated = 1;

        var arr = $('input[name="rblAddress"]:checked').val().split('+');

        shpAddressVM.Address1 = arr[0];
        shpAddressVM.Address2 = arr[1];
        shpAddressVM.City = arr[2];
        shpAddressVM.Country = arr[3];
        shpAddressVM.CountryID = $('#m_ddlCountry :selected').val();
        shpAddressVM.State = arr[4];
        shpAddressVM.StateID = $('#m_ddlState :selected').val();
        shpAddressVM.PostalCode = arr[5];

        // Store the stringified JSON object into a hidden field
        $("#hdn_SelectedAddress").val(JSON.stringify(shpAddressVM));
    });

   
});
function closePopup() {
    $('#popupShippingAddress').hide();
}
