Your IP : 18.188.175.197


Current Path : /home/bitrix/ext_www/coffe.land/ru/club/utils/zip/
Upload File :
Current File : /home/bitrix/ext_www/coffe.land/ru/club/utils/zip/getpostalcode-prod.js

jQuery(document).ready(function ($) {

    /* подстановка данных из dadata, определение zip, добавление кастомных надписей к полям */
    var serviceUrl = 'https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address';
    var token = 'Token 1cd019f1665b386f02a0600160644e502e380009';
    var city, street, house, zip, region, area;
    var pageLang = $('html').attr('lang');
    var customLabels = {
      city: {
        en: 'Start entering & choose from the list below.',
        ru: 'Введите первые 3 символа и выберите из списка.'
      },
      street1: {
        en: 'Start entering & choose from the list below.',
        ru: 'Введите первые 3 символа и выберите из списка.'
      },
      street2: {
        en: 'Start entering & choose from the list below.',
        ru: 'Введите первые несколько символов и выберите из списка.'
      },
      suggest: {
        en: 'Please choose from the suggested results after filling the field above.',
        ru: 'Пожалуйста, выберите вариант из предложенных подсказок после заполнения поля выше.'
      },
      postcode_found: {
        en: 'Correct postal code for your address was added automatically.',
        ru: 'Корректный индекс для Вашего адреса добавлен автоматически.'
      },
      postcode_notfound: {
        en: 'Postal code for your address wasn\'t found, please enter it manually.',
        ru: 'Почтовый индекс для Вашего адрес не найден, пожалуйста, введите его вручную.'
      }
    }

    $('#city, #billing\\:city, #shipping\\:city, #street_1, #shipping\\:street1, #shipping\\:street_1, #billing\\:street1, #street_2, #billing\\:street2, #shipping\\:street2, #shipping\\:street_2')
            .after('<p class="suggest-info" style="display:none; padding: 0px 10px; margin: 0px; font-size: 11px; color: #9A0A1D;">' + customLabels.suggest[pageLang] + '</p>');

    $('#postcode, #billing\\:postcode, #shipping\\:postcode').parents('.input-box')
            .prepend('<p class="zip-info" style="display:none; padding: 0 10px;margin: 0;font-size: 11px;color: #0c61fc;"></p>');

    try {
        ddListener.push(['on', 'define:context.location.city', function (geoCity) {
                $('#city, #billing\\:city, #shipping\\:city').val(geoCity);
            }]);
    } catch (e) {
        console.log(e.message);
    }

    var urlPath = window.location.pathname;
    if (urlPath.search('customer/address') != -1) {
        // for customer account
        getPostalCode('#city', '#street_1', '#street_2', '#postcode', '#region_name', '#area_name');
    } else if (urlPath.search('checkout') != -1) {
        // for checkout 'billing'
        getPostalCode('#billing\\:city', '#billing\\:street1', '#billing\\:street2', '#billing\\:postcode', '#billing\\:region_name', '#billing\\:area_name');
        // for checkout 'shipping'
        getPostalCode('#shipping\\:city', '#shipping\\:street1', '#shipping\\:street2', '#shipping\\:postcode', '#shipping\\:region_name', '#shipping\\:area_name');
    } else if (urlPath.search('customer/account/create') != -1) {
        // for registration 'billing'
        getPostalCode('#billing\\:city', '#billing\\:street_1', '#billing\\:street_2', '#billing\\:postcode', '#billing\\:region', '#billing\\:area');
        // for registration 'shipping'
        getPostalCode('#shipping\\:city', '#shipping\\:street_1', '#shipping\\:street_2', '#shipping\\:postcode', '#shipping\\:region', '#shipping\\:area');
    }

    function getPostalCode(city, street, house, zip, region, area) {
        city = $(city);
        street = $(street);
        house = $(house);
        zip = $(zip);
        region = $(region);
        area = $(area);
        var emptyResponse = null;

        zip.prop('readonly', true).css('background', '#e6e6e6');

        $(city).on('input', function () {
          if ($(this).val() === '') {
            street.val('');
            house.val('');
            zip.val('');
            region.val('');
            area.val('');
            $('.input-box .zip-info').hide();
            $('.input-box .suggest-info').hide();
          }
        });

        $(region).autocomplete({
            minLength: 3,
            source: function (request, response) {
                $.ajax({
                    url: serviceUrl,
                    type: 'POST',
                    dataType: 'json',
                    headers: {
                        'Authorization': token,
                        'Content-Type': 'application/json; charset=UTF-8',
                        'Accept': 'application/json'
                    },
                    data: JSON.stringify({'query': region.val(), 'from_bound':{'value':'region'}, 'to_bound':{'value':'region'}}),
                    success: function (data) {
                      response($.map(data.suggestions, function (item) {
                        return {
                          value: item.data.region_with_type,
                          label: item.data.region_with_type
                        };
                      }));
                    }
                });
            },
            select: function (event, ui) {
            },
            change: function(event, ui) {
            }
        });

        $(area).autocomplete({
            minLength: 3,
            source: function (request, response) {
                $.ajax({
                    url: serviceUrl,
                    type: 'POST',
                    dataType: 'json',
                    headers: {
                        'Authorization': token,
                        'Content-Type': 'application/json; charset=UTF-8',
                        'Accept': 'application/json'
                    },
                    data: JSON.stringify({'query': region.val() + ' ' + area.val(), 'from_bound':{'value':'area'}, 'to_bound':{'value':'area'}}),
                    success: function (data) {
                      response($.map(data.suggestions, function (item) {
                        return {
                          value: item.data.area_with_type,
                          label: item.data.area_with_type
                        };
                      }));
                    }
                });
            },
            select: function (event, ui) {
            },
            change: function(event, ui) {
            }
        });

        $(city).autocomplete({
            minLength: 3,
            source: function (request, response) {
                $.ajax({
                    url: serviceUrl,
                    type: 'POST',
                    dataType: 'json',
                    headers: {
                        'Authorization': token,
                        'Content-Type': 'application/json; charset=UTF-8',
                        'Accept': 'application/json'
                    },
                    data: JSON.stringify({'query': region.val() + ' ' + area.val() + ' ' + city.val(),'from_bound':{'value':'city'},'to_bound':{'value':'settlement'}}),
                    success: function (data) {
                      emptyResponse = data.suggestions.length == 0 ? true : false;
                      zip.prop('readonly', false).css('background', '#fff');
                      response($.map(data.suggestions, function (item) {
                        var settlement = item.data.settlement
                          ? (item.data.region_with_type + ', ' + item.data.settlement_with_type)
                          : item.data.city;
                        return {
                          value: item.data.settlement ? item.data.settlement_with_type : item.data.city,
                          label: settlement,
                          postalCode: item.data.postal_code,
                          region: item.data.region_with_type,
                          area: item.data.area_with_type
                        };
                      }));
                    }
                });
            },
            select: function (event, ui) {
                dataLayer.push({'event': 'zip_address'});
                city.parents('.input-box').find('.suggest-info').hide();
                if (ui.item.region) {
                    region.val(ui.item.region);
                }
                if (ui.item.area) {
                    area.val(ui.item.area);
                }
                if (ui.item.postalCode) {
                    zip.val(ui.item.postalCode).prop('readonly', true).css('background', '#e6e6e6');
                } else {
                    dataLayer.push({'event': 'zip_error'});
                }
            },
            change: function(event, ui) {
              if (ui.item === null && !emptyResponse) {
                $(this).val('');
                city.parents('.input-box').find('.suggest-info').show();
              }
            }
        });

        $(street).autocomplete({
            minLength: 3,
            source: function (request, response) {
                $.ajax({
                    url: serviceUrl,
                    type: 'POST',
                    dataType: 'json',
                    headers: {
                        'Authorization': token,
                        'Content-Type': 'application/json; charset=UTF-8',
                        'Accept': 'application/json'
                    },
                    data: JSON.stringify({'query': region.val() + ' ' + area.val() + ' ' + city.val() + ' ' + street.val()}),
                    success: function (data) {
                        emptyResponse = data.suggestions.length == 0 ? true : false;
                        // отфильтровываем варианты с домом
                        var filterData = data.suggestions.filter(function (item) {
                            return !item.data.house;
                        });
                        response($.map(filterData, function (item) {
                            return {
                                value: item.data.street_with_type,
                                label: item.data.street_with_type,
                                postalCode: item.data.postal_code,
                                city: item.data.city,
                                region: item.data.region_with_type,
                                area: item.data.area_with_type,
                                settlement: item.data.settlement_with_type
                            };
                        }));
                    }
                });
            },
            select: function (event, ui) {
                street.parents('.input-box').find('.suggest-info').hide();
                dataLayer.push({'event': 'zip_address'});
                house.val('');
                zip.val('');

                if (ui.item.postalCode) {
                    zip.val(ui.item.postalCode);
                } else {
                    dataLayer.push({'event': 'zip_error'});
                }
            },
            change: function(event, ui) {
              if (ui.item === null && !emptyResponse) {
                $(this).val('');
                street.parents('.input-box').find('.suggest-info').show();
              }
            }
        });

        $(house).autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: serviceUrl,
                    type: 'POST',
                    dataType: 'json',
                    headers: {
                        'Authorization': token,
                        'Content-Type': 'application/json; charset=UTF-8',
                        'Accept': 'application/json'
                    },
                    data: JSON.stringify({'query': region.val() + ' ' + area.val() + ' ' + city.val() + ' ' + street.val() + ' ' + house.val()}),
                    success: function (data) {
                        emptyResponse = data.suggestions.length == 0 ? true : false;
                        zip.prop('readonly', false).css('background', '#fff');
                        response($.map(data.suggestions, function (item) {
                            var resultHouse = (item.data.house ? (item.data.house_type + ' ' + item.data.house) : '') +
                                    (item.data.block ? (', ' + item.data.block_type + ' ' + item.data.block) : '') +
                                    (item.data.flat ? (', ' + item.data.flat_type + ' ' + item.data.flat) : '');
                            return {
                                value: resultHouse,
                                label: resultHouse,
                                postalCode: item.data.postal_code
                            };
                        }));
                    }
                });
            },
            select: function (event, ui) {
                house.parents('.input-box').find('.suggest-info').hide();

                if (ui.item.postalCode) {
                    zip.val(ui.item.postalCode).prop('readonly', true).css('background', '#e6e6e6');

                    $('.input-box .zip-info').text(customLabels.postcode_found[pageLang]).show();
                } else {
                    zip.val(ui.item.postalCode).prop('readonly', false).css('background', '#fff');
                    dataLayer.push({'event': 'zip_error'});

                    $('.input-box .zip-info').text(customLabels.postcode_notfound[pageLang]).show();
                }
            },
            change: function(event, ui) {
              if (ui.item === null && !emptyResponse) {
                $(this).val('');
                house.parents('.input-box').find('.suggest-info').show();
              }
            }
        });
    }

    /* ограничение длины полей */
    $('#billing\\:firstname, #shipping\\:firstname, #billing\\:lastname, #shipping\\:lastname').attr('maxlength', '35');

    $('#checkoutSteps').on('focus', '#remark', function () {
        $(this).attr('maxlength', '70');
    });

    // Кастомные label для полей
    $('.placeHolder[for="city"], .placeHolder[for="billing\\:city"], .placeHolder[for="shipping\\:city"]').text(customLabels.city[pageLang]);
    $('.placeHolder[for="street_1"], .placeHolder[for="billing\\:street1"], .placeHolder[for="shipping\\:street1"], .placeHolder[for="shipping\\:street_1"]').text(customLabels.street1[pageLang]);
    $('.placeHolder[for="street_2"], .placeHolder[for="billing\\:street2"], .placeHolder[for="shipping\\:street2"], .placeHolder[for="shipping\\:street_2"]').text(customLabels.street2[pageLang]);
});