Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- jQuery.fn.shake = function () {
- this.each(function (i) {
- $(this).css({
- "position": "relative"
- });
- for (var x = 1; x <= 2; x++) {
- $(this).animate({
- left: -6
- }, 12).animate({
- left: 0
- }, 12).animate({
- left: 6
- }, 12).animate({
- left: 0
- }, 12);
- }
- });
- return this;
- };
- $(function () {
- var OTHER_SALES_CLASS = '6400';
- var $surname = $('#surname'),
- $name = $('#name'),
- $patronymic = $('#patronymic'),
- $email = $('#contact'),
- $password = $('#password'),
- $passwordConfirm = $('#password-confirm'),
- $quest = $('.js-radio-quest'),
- $questContainer = $('.quest-container'),
- $phone = $("#phone"),
- $agree = $("#agree"),
- $agreeToSend = $("#agreeToSend"),
- $submit = $('.js-reg-submit'),
- $currentCity = $('#location-selection__current-city'),
- $currentLookupCode = $('#location-selection__city-lookup-code'),
- $openCitySelectionPopup = $('#open-city-selection-popup'),
- $otherInput = $('.input-other'),
- emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
- requiredMsg = 'Поле не должно быть пустым',
- shopCitiesJson = $('#shopCitiesJson').val();
- function capitalize(string) {
- return string.charAt(0).toUpperCase() + string.slice(1)
- }
- function checkPatronimic(value, name, required, minLength) {
- value.trim();
- var ret = [];
- if (required && !value.length) {
- ret.push(requiredMsg)
- }
- if (minLength > value.length) {
- ret.push(capitalize(name) + ' должно содержать более ' + (minLength - 1) + ' символов');
- }
- return ret;
- }
- function checkSurName(value, name, required, minLength) {
- value.trim();
- var ret = [];
- if (minLength > value.length) {
- ret.push('Поле "' + capitalize(name) + '" не должно быть пустым и иметь длину более 1 символа');
- }
- return ret;
- }
- function checkName(value, name, required, minLength) {
- value.trim();
- var ret = [];
- if (minLength > value.length) {
- ret.push('Поле "' + capitalize(name) + '" не должно быть пустым и иметь длину более 1 символа');
- }
- return ret;
- }
- function checkEmail(value) {
- value = value.trim();
- var ret = [];
- if (value.length && !value.match(emailRegex)) {
- ret.push('Неверный формат почты')
- }
- if (value.length && !ret.length && !$agreeToSend.prop('checked')) {
- ret.push('Подтвердите согласие на рассылку по email')
- }
- return ret;
- }
- function renderErrors(errors) {
- return errors.map(function (error) {
- return '<span class="help-block form-error ">' + error + '</span>';
- }).join('');
- }
- function showErrors(element, html) {
- element.siblings('.error-block').html(html)
- }
- function checkPassword() {
- var ret = [],
- pass = $password.val().trim(),
- passConfirm = $passwordConfirm.val().trim(),
- username = $phone.val().trim().replace(/(\s|\+|\(|\)|-)/g, ''),
- wrongPassMsg = 'Пароль не соответствует требованиям';
- if (pass !== passConfirm) {
- ret.push('Пароли не совпадают');
- }
- if (pass.length < 8 && ret.length < 1) {
- ret.push(wrongPassMsg);
- }
- if (!(pass.match(/[A-Za-z]+/) && pass.match(/\d+/)) && ret.length < 1) {
- ret.push(wrongPassMsg);
- }
- if ((pass === username || pass === username.split("").reverse().join("") || pass.indexOf(username) !== -1) && ret.length < 1) {
- ret.push(wrongPassMsg);
- }
- if (pass.length > 1) {
- var symb = pass[0];
- for (var charIndex = 1; charIndex < pass.length; charIndex++) {
- var cSymb = pass[charIndex];
- if (symb === cSymb && ret.length < 1) {
- ret.push(wrongPassMsg)
- break;
- } else {
- symb = cSymb;
- }
- }
- }
- return ret;
- }
- function checkAgree() {
- if (!$agree.is(':checked')) {
- return ['Необходимо согласие с условиями']
- }
- return []
- }
- function getStoredData() {
- return JSON.parse(localStorage.getItem('custRegData'))
- }
- function setDataToStore(data) {
- localStorage.setItem('custRegData', JSON.stringify(data))
- }
- function isStoreValid(time) {
- var data = getStoredData();
- if (!data) {
- return false;
- }
- if (Date.now() - data.created > time * 1000) {
- return false
- }
- return true;
- }
- function initStore(liveTime) {
- var data = getStoredData();
- var initialState = {
- created: Date.now(),
- name: null,
- surname: null,
- patronymic: null,
- email: null,
- phone: null,
- quest: null,
- agree: false,
- currentCity: null,
- cityLookupCode: null
- };
- isStoreValid(liveTime) ? persistForm(data) : setDataToStore(initialState)
- }
- function persistForm(data) {
- $name.val(data.name);
- $surname.val(data.surname);
- $patronymic.val(data.patronymic);
- $email.val(data.email);
- $agree.attr('checked', data.agree);
- $phone.val(data.phone);
- if (data.quest) {
- $('input[name="quest"][value="' + data.quest + '"]').click();
- }
- }
- function setField(field, value) {
- var data = getStoredData();
- data[field] = value;
- setDataToStore(data);
- }
- function updateStore() {
- var $self = $(this),
- field = $self.attr('name'),
- value = $self.val();
- if (field === 'phone') {
- if (value === '+7 (' || value === '+7 ' || value === '+7' || value === '+') {
- value = '';
- }
- }
- if ($self.attr('type') === 'checkbox') {
- value = $self.is(':checked');
- }
- if ($self.prop('nodeName') === 'SPAN') {
- if ($self.text() !== '') {
- value = $self.text();
- } else {
- return;
- }
- }
- setField('created', Date.now());
- setField(field, value);
- }
- function getShopCities() {
- createCitiesPopup(JSON.parse(shopCitiesJson));
- }
- function createCitiesPopup(jsonCities) {
- var jsonCitiesObject = jsonCities;
- var innerHtml = [];
- $.each(jsonCitiesObject, function (k, v) {
- innerHtml.push('<div class="city-list-block">');
- innerHtml.push('<div class="capital">');
- innerHtml.push(k);
- innerHtml.push('</div>');
- innerHtml.push('<div class="cities">');
- $.each(v, function (index, cityInfo) {
- innerHtml.push('<span>');
- innerHtml.push('<a class="select_sity" href="javascript:void(0);" data-cityLookupCode="' + cityInfo.lookupCode + '">');
- innerHtml.push(cityInfo.name);
- innerHtml.push('</a>');
- innerHtml.push('</span>');
- });
- innerHtml.push('</div>');
- innerHtml.push('</div>');
- });
- $('#reg_city-block .city-list').html(innerHtml.join(''));
- $(document).on('keyup', '#reg_city-block #city-block-input_reg', function () {
- var phrase = $(this).val();
- $('#reg_city-block .up_res li').remove();
- $('#reg_city-block .up_res').hide();
- if (phrase.length != 0) {
- var match = $("#reg_city-block .city-list a");
- $("#reg_city-block .choose-city-block").hide();
- match.addClass('grey');
- match.each(
- function (id, element) {
- if ($(element).text().toLowerCase().indexOf(phrase.toLowerCase()) != -1) {
- $(element).removeClass('grey');
- $('#reg_city-block .up_res').append('<li>' + $(this).text() + '</li>');
- $('#reg_city-block .up_res').show();
- }
- if ($(this).text().toLowerCase() == phrase.toLowerCase()) {
- $(this).removeClass('grey');
- $("#reg_city-block .choose-city-block").show();
- $('#reg_city-block .up_res li').remove();
- $('#reg_city-block .up_res').hide();
- $('#reg_city-block .js-city-list-conf').show();
- }
- }
- );
- } else {
- var match = $("#reg_city-block .city-list a");
- match.removeClass('grey');
- }
- });
- $(document).on('click', '#reg_city-block .up_res li', function (e) {
- $("#reg_city-block #city-block-input_reg").val($(this).html().toLowerCase());
- $("#reg_city-block #city-block-input_reg").trigger('keyup');
- $("#reg_city-block #city-block-input_reg").focus();
- $('#reg_city-block .js-city-list-conf').show();
- e.preventDefault();
- e.stopPropagation();
- });
- $('#reg_city-block .js-city-list-conf').on('click', function () {
- var links = $("#reg_city-block .city-list a"),
- phrase = $("#reg_city-block #city-block-input_reg").val();
- links.each(function () {
- if ($(this).text().toLowerCase() == phrase.toLowerCase()) {
- setSelectedCityData(this);
- $('#reg_city-block').modal('hide');
- $("#reg_city-block .choose-city-block").hide();
- $("#reg_city-block #city-block-input_reg").val('');
- $('#reg_city-block .js-city-list-conf').hide();
- }
- });
- $("#reg_city-block .city-list a").removeClass('grey');
- });
- $('#reg_city-block .select_sity').on('click', function () {
- setSelectedCityData(this);
- $('#reg_city-block .up_res li').remove();
- $('#reg_city-block .up_res').hide();
- $('#city-block-input_reg').val('');
- $('#reg_city-block').modal('hide');
- $("#reg_city-block .city-list a").removeClass('grey');
- $('#reg_city-block .js-city-list-conf').hide();
- });
- $('[name="user_filial"]').on('click', function () {
- $('#reg_city-block').modal('show');
- });
- $('#reg_city-block').modal('show');
- }
- function showCitySelectionPopupIfNeeded(data) {
- $currentLookupCode.val(data.cityLookupCode);
- $currentCity.text(data.currentCity);
- if ($currentLookupCode.val() === '') {
- getShopCities();
- }
- }
- function setSelectedCityData(city) {
- $('#location-selection__current-city').text($(city).text().toLowerCase());
- $('#location-selection__city-lookup-code').val(($(city).attr('data-cityLookupCode')));
- $('#location-selection__city-lookup-code').trigger('change');
- }
- function getDemandClass() {
- var checkedQuest = $('input[name="quest"]:checked'),
- value = checkedQuest.attr('value');
- return value;
- }
- function collectData() {
- return {
- cityCode: $currentLookupCode.val(),
- name: $name.val(),
- secondName: $surname.val(),
- middleName: $patronymic.val(),
- email: $email.val().trim() === "" ? null : $email.val().trim(),
- emailNotificationConfirm: $agreeToSend.prop('checked') ? "Y" : "N",
- phone: $phone.val().replace(/(\s|\+|\(|\)|-)/g, ''),
- password: $password.val(),
- demandClass: getDemandClass(),
- otherDemandClass: $otherInput.val(),
- pdAgree: 'Y'
- };
- }
- function showPreloader() {
- $('.content').preloader({
- overlayBackground: 'rgba(255, 255, 255, .6)',
- showOverlay: true,
- contentsWidth: '85px',
- contentsHtml: '<img src="' + changeStaticLink($('#constantEndecaPath').val() + '/static/img/assets/product-card/preloader.gif') + '" class="preloader__image" alt="" role="presentation">',
- delay: 0
- });
- }
- function hidePreloader() {
- $('.content').preloader('hide');
- }
- function registerReachGoal() {
- try {
- yaCounterBuyInfo.reachGoal('registration_fiz');
- } catch (e) {
- console.log(e);
- }
- }
- $submit.on('click', function () {
- var surnameErrors = checkSurName($surname.val(), 'фамилия', true, 2),
- nameErrors = checkName($name.val(), 'имя', true, 2),
- patronymicErrors = checkPatronimic($patronymic.val(), 'отчество', false, 0),
- emailErrors = checkEmail($email.val()),
- phoneErrors = checkPhone($phone.val()),
- passErrors = checkPassword(),
- agreeErrors = checkAgree(),
- questErrors = checkQuest(),
- otherInputErrors = checkOtherInput();
- showErrors($surname, renderErrors(surnameErrors));
- showErrors($name, renderErrors(nameErrors));
- showErrors($patronymic, renderErrors(patronymicErrors));
- showErrors($email, renderErrors(emailErrors));
- showErrors($phone, renderErrors(phoneErrors));
- showErrors($password, renderErrors(passErrors));
- showErrors($agree, renderErrors(agreeErrors));
- showErrors($questContainer, renderErrors(questErrors));
- showErrors($otherInput, renderErrors(otherInputErrors));
- var errSum = surnameErrors.length
- + nameErrors.length
- + patronymicErrors.length
- + emailErrors.length
- + phoneErrors.length
- + passErrors.length
- + agreeErrors.length
- + questErrors.length
- + otherInputErrors.length;
- if (!errSum && phoneConfirmFlag) {
- showPreloader();
- var data = collectData(),
- personCandidate = data;
- $.ajax({
- url: $('#pageContextPath').val() + '/jsonRegisterCustomer',
- type: 'POST',
- data: JSON.stringify(data),
- contentType: "application/json; charset=utf-8",
- success: function success(data) {
- getWhIdByCityId(personCandidate.cityCode).then(
- function success(whId) {
- $(".register_page").addClass("hidden");
- if ((data == "SUCCESS") || (data == "AUTHORIZE")) {
- if (personCandidate.emailNotificationConfirm === 'Y' && personCandidate.email) {
- fillEmailRetailRocket(personCandidate.email, whId);
- }
- $agreeToSend.prop('checked') ? $(".success_page_mail").removeClass("hidden") : $(".success_page_no_mail").removeClass("hidden");
- localStorage.setItem('custRegData', null);
- registerReachGoal();
- if (data == "AUTHORIZE") {
- $.ajax({
- url: $('#pageContextPath').val() + '/authorize',
- type: 'POST',
- data: {event: '', isFirstEntry: 'true', targetUrlParameter:'/home.htm',
- userType:'PERSON', authType:'SMS_AUTH', username: $phone.val().replace(/(\s|\+|\(|\)|-)/g, ''),
- password: $password.val(), authCode:''},
- success: function success() {
- window.location.href = $('#pageContextPath').val() + '/cart.htm';
- },
- error: function () {
- window.location.href = $('#pageContextPath').val() + '/cart.htm';
- }
- });
- } else {
- hidePreloader();
- }
- } else {
- $(".error_page_reg").removeClass("hidden");
- hidePreloader();
- }
- },
- function error() {
- }
- );
- },
- error: function () {
- $(".register_page").addClass("hidden");
- $(".error_page_reg").removeClass("hidden");
- hidePreloader();
- }
- });
- }
- });
- function getWhIdByCityId(cityId) {
- return new Promise(function (resolve, reject) {
- $.ajax({
- method: "GET",
- url: '/getWhId?cityId=' + cityId,
- success: function (response) {
- resolve(response);
- },
- error: function (response) {
- reject(response);
- }
- });
- });
- }
- function checkQuest() {
- var ret = [];
- if ($('input[name="quest"]:checked').length === 0) {
- ret.push("Должно быть выбрано значение");
- }
- return ret;
- }
- function checkOtherInput() {
- var ret = [],
- $lengthNotice= $('.input-other-notif');
- if (
- $('input[name="quest"]:checked').val() === OTHER_SALES_CLASS &&
- $otherInput.val().length <= 0
- ) {
- $lengthNotice.hide();
- ret.push("Значение не может быть пустым, его длина не должна превышать 20 символов");
- }else{
- $lengthNotice.show();
- }
- return ret;
- }
- $quest.on('change', updateStore);
- $name.on('change', updateStore);
- $surname.on('change', updateStore);
- $patronymic.on('change', updateStore);
- $email.on('change', updateStore);
- $phone.on('change', updateStore);
- $agree.on('change', updateStore);
- $currentCity.on('DOMSubtreeModified', updateStore);
- $currentLookupCode.on('change', updateStore);
- $openCitySelectionPopup.on('click', getShopCities);
- limitTextFieldLength($otherInput, 20);
- initStore(9000);
- showCitySelectionPopupIfNeeded(getStoredData());
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement