bongzilla

Untitled

Dec 7th, 2020 (edited)
473
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 6.08 KB | None | 0 0
  1. // рабочая версия до добавления интернациональной версии
  2. const API_KEY = "37f3cb2a937f495ca93b3c4ae1b62ad4";
  3. const API_URL = "https://ipgeolocation.abstractapi.com/v1/";
  4. const RESERVE_API_URL = "https://ipapi.co/json/";
  5.  
  6. // список стран с переводом названий
  7. const COUNTRIES = [{"code":"ru","translation":"Россия"},{"code":"ua","translation":"Украина"},{"code":"ge","translation":"Грузия"},{"code":"tm","translation":"Туркменистан"},{"code":"am","translation":"Армения"},{"code":"by","translation":"Белоруссия"},{"code":"uz","translation":"Узбекистан"},{"code":"az","translation":"Азербайджан"},{"code":"kz","translation":"Казахстан"},{"code":"md","translation":"Молдавия"},{"code":"tj","translation":"Таджикистан"},{"code":"kg","translation":"Киргизия"}];
  8.  
  9. // локализация стран
  10. const LOCALIZED_COUNTRIES = COUNTRIES.reduce((cv, pv) => { cv[pv["code"]] = pv["translation"]; return cv }, {});
  11. // показывать только эти страны
  12. const ONLY_COUNTRIES = COUNTRIES.map(country => country.code);
  13. // вынос некоторых стран вверх списка
  14. const PREFFERED_COUNTRIES = ["ru", "ua"];
  15.  
  16. // селекторы для привязки к ним событий дропдауна (PHONEINPUTS) и заполнения поля полного телефона при отправке (FULLPHONES / SENDBUTTONS)
  17. const PHONEINPUTS = ["#phone-input-1", "#phone-input-2", "#phone-input-3", "#phone-input-4", "#phone-input-5", "#phone-input-6"];
  18. const FULLPHONES = ["#phone-full-1", "#phone-full-2", "#phone-full-3", "#phone-full-4", "#phone-full-5", "#phone-full-6"];
  19. const SENDBUTTONS = ["#send-button-1", "#send-button-2", "#send-button-3", "#send-button-4", "#send-button-5", "#send-button-6"];
  20.  
  21. // настройки
  22. const PLUGIN_PROPERTIES = {
  23.     initialCountry: "auto",
  24.     onlyCountries: ONLY_COUNTRIES,
  25.     localizedCountries: LOCALIZED_COUNTRIES,
  26.     preferredCountries: PREFFERED_COUNTRIES,
  27.     separateDialCode: true,
  28.     geoIpLookup: geoIpLookup
  29. };
  30.  
  31. const PLUGIN_INSTANCES = {
  32.     "1": null,
  33.     "2": null,
  34.     "3": null,
  35.     "4": null,
  36.     "5": null,
  37.     "6": null
  38. }
  39.  
  40. PHONEINPUTS.forEach((input, idx) => {
  41.     // hack for maskedinput and cursor disabling can work :(
  42.     const _PHONEINPUT_ = $(input);
  43.     const PHONEINPUT = document.querySelector(input);
  44.     const SENDBUTTON = document.querySelector(SENDBUTTONS[idx]);
  45.  
  46.     // ставим маску на все поля
  47.     _PHONEINPUT_.mask("(999) 999-99-99?");
  48.     // отключаем курсор во всех полях
  49.     disableCursorInInput(_PHONEINPUT_);
  50.  
  51.     // инициализируем плагин на каждом из input'ов
  52.     PLUGIN_INSTANCES[idx + 1] = window.intlTelInput(PHONEINPUT, PLUGIN_PROPERTIES);
  53.  
  54.     // вешаем обработчик события смены страны на каждый input
  55.     PHONEINPUT.addEventListener("countrychange", function() {
  56.         const countryCode = PLUGIN_INSTANCES[idx + 1].getSelectedCountryData().iso2;
  57.         const dialCode = PLUGIN_INSTANCES[idx + 1].getSelectedCountryData().dialCode;
  58.  
  59.         setCookie("clientcountry", countryCode);
  60.         changeCountryInAllForms(PLUGIN_INSTANCES, idx + 1, countryCode, PHONEINPUT);
  61.     });
  62.  
  63.     // вешаем обработчик на каждую кнопку каждой формы для собирания
  64.     // в кучу кода страны + номера (чтобы убрать лишнее скрытое поле)
  65.     SENDBUTTON.addEventListener("click", function(e) {
  66.         // TODO: REMOVE (FOR DEVELOPMENT NEEDS)
  67.         e.preventDefault();
  68.         console.log("SENDBUTTON clicked");
  69.         //
  70.         PHONEINPUT.value = "+" + PLUGIN_INSTANCES[idx + 1].getSelectedCountryData().dialCode + " " + PHONEINPUT.value, "PHONEINPUT value";
  71.     });
  72. });
  73.  
  74. // функция отвечающая за отключение курсора
  75. function disableCursorInInput(selector) {
  76.     $(selector).click(function() {
  77.         $(this)[0].selectionStart = $(this)[0].selectionEnd = 0;
  78.     });
  79. }
  80.  
  81. // функция для получения куки
  82. function getCookie() {
  83.     const cookie = document.cookie.split("; ").map(cookie => ({ "name": cookie.split("=")[0], "value": cookie.split("=")[1] })).filter(cookie => cookie.name === "clientcountry");
  84.     return cookie.length > 0 ? cookie[0].value : null
  85. }
  86.  
  87. // функция для установки куки
  88. function setCookie(name, value) {
  89.     document.cookie = `${name}=${value}`;
  90.     return true;
  91. }
  92.  
  93. // функция отвечающая в плагине за автоматическое определение страны
  94. function geoIpLookup(success, failure) {
  95.     const clientCountryCookie = getCookie("clientcountry");
  96.  
  97.     if(clientCountryCookie !== null) {
  98.         success(clientCountryCookie);
  99.         // TODO: check number of  requests before cookie used
  100.         // console.log("country defined by cookie");
  101.     } else {
  102.         fetch(API_URL + "?&api_key=" + API_KEY)
  103.             .then(r => r.json())
  104.             .then(info => {
  105.                 var countryCode = info && info.country_code ? info.country_code.toLowerCase() : "ru";
  106.                 setCookie("clientcountry", countryCode);
  107.                 success(countryCode);
  108.             })
  109.             .catch(e => {
  110.                 console.log("error getting ip adress by main API --> trying to get from reserve API");
  111.                 reserveGeoIpLookup(success, failure);
  112.             })
  113.     }
  114. }
  115.  
  116. // функция для резервного определения страны по IP
  117. function reserveGeoIpLookup(success, failure) {
  118.     fetch(RESERVE_API_URL)
  119.         .then(r => r.json())
  120.         .then(info => {
  121.             var countryCode = info && info.country_code ? info.country_code.toLowerCase() : "ru";
  122.             setCookie("clientcountry", countryCode);
  123.             success(countryCode);
  124.         })
  125.         .catch(e => {
  126.             console.log("error getting ip adress by reserve API --> setting defaults to 'ru'");
  127.             success("ru");
  128.         })
  129. }
  130.  
  131. // смена страны во всех инпутах
  132. function changeCountryInAllForms(pluginInstancesObject, currentInstanceIdx, countryCode) {
  133.     for (instance in pluginInstancesObject) {
  134.         pluginInstancesObject[instance].setCountry(countryCode);
  135.     }
  136. }
Advertisement
Add Comment
Please, Sign In to add comment