function ajax(action, data, success_f, error_f) { data["ajax"] = action; $.ajax({ data: data, type: 'POST', dataType: "json", url: "/index.php" }).done(function(data) { if (data.success) { success_f(data); } else { error_f(data); } }).error(function (jqXHR, textStatus, errorThrown) { console.log(jqXHR.responseText); }); } function change_keys_layout(str) { replacer = { "q":"й", "w":"ц", "e":"у", "r":"к", "t":"е", "y":"н", "u":"г", "i":"ш", "o":"щ", "p":"з", "[":"х", "]":"ъ", "a":"ф", "s":"ы", "d":"в", "f":"а", "g":"п", "h":"р", "j":"о", "k":"л", "l":"д", ";":"ж", "'":"э", "z":"я", "x":"ч", "c":"с", "v":"м", "b":"и", "n":"т", "m":"ь", ",":"б", ".":"ю", "/":"." }; return str.replace(/[A-z/,.;\'\]\[]/g, function ( x ){ return x == x.toLowerCase() ? replacer[ x ] : replacer[ x.toLowerCase() ].toUpperCase(); }); } function generate_password(length = 15) { let symbset = "!@#$%^&*", charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", retVal = ""; for (let i = 0, n = charset.length; i < length; ++i) { if (i === 5 || i === 10) { retVal += symbset.charAt(Math.floor(Math.random() * symbset.length)); } else { retVal += charset.charAt(Math.floor(Math.random() * n)); } } return retVal; }$(function () { $(document) // Пагинация каталога - вперед и назад .on("click", ".page_go_left", function() { if (!$(this).hasClass("disabled")) { var page_link = $(".paginator").find(".active").prev("a").attr("href"); location.href = page_link; } }) .on("click", ".page_go_right", function() { if (!$(this).hasClass("disabled")) { var page_link = $(".paginator").find(".active").next("a").attr("href"); location.href = page_link; } }) // Пагинация каталога - показать еще .on("click", ".load_next_stack", function() { if ($(this).find("b").is(":visible")) { $.ajax({ type: 'POST', dataType: "json", url: "/index.php", data: { ajax: "catalog.get_page", mpath: $("#c_mpath").val(), filter: $("#filter").val(), load_page: $("#next_page_n").val() } }).done(function(data) { if (data.success) { $("#catalog_output").find(".empty-block").remove(); $("#catalog_output").html( $("#catalog_output").html() + data['html'] + '
' + '
' + '
' ); $("#next_page_n").val( parseInt($("#next_page_n").val(), 10) + 1 ); $(".goods_showed").html( parseInt($(".goods_showed").html(), 10) + data['loaded'] ); if (data['loaded_w_offset'] >= data['total']) { $(".load_next_stack").find("b").hide(); } } else console.log(data); }); } }) // Каталог продукции - Сменить сортировку .on("change", "#catalog_sort", function() { $.ajax({ type: 'POST', dataType: "json", url: "/index.php", data: { ajax: "catalog.change_sort", sort: $(this).find(":selected").val(), url: window.location.pathname } }).done(function(data) { if (data.success) { location.href = data.url; //load_page(data.url) } else console.log(data); }); }) // Каталог продукции - Сменить количество товаров на странице .on("change", "#rests_output", function() { $.ajax({ type: 'POST', dataType: "json", url: "/index.php", data: { ajax: "catalog.change_rests_output", rests_output: $(this).find(":selected").val(), url: window.location.pathname } }).done(function(data) { if (data.success) { location.href = data.url; //load_page(data.url) } else console.log(data); }); }) // Каталог продукции - Сменить отображение остатков .on("change", "#goods_per_page", function() { $.ajax({ type: 'POST', dataType: "json", url: "/index.php", data: { ajax: "catalog.change_per_page", per_page: $(this).find(":selected").val(), url: window.location.pathname } }).done(function(data) { if (data.success) { location.href = data.url; //load_page(data.url) } else console.log(data); }); }) // Каталог продукции - Переключение вида .on("click", ".switch-view", function() { $(".switch-view").removeClass("active"); $(this).addClass("active"); //$(".product").removeClass("product-block").removeClass("product-line").removeClass("product-row").addClass($(this).data('type')); $.ajax({ type: 'POST', dataType: "json", url: "/index.php", data: { ajax: "catalog.catalog_style", data: $(this).data('type') } }).done(function(data) { if (data.success === true) { location.href = window.location.pathname; //load_page(window.location.pathname) } else console.log(data); }); }) // Каталог продукции - Сколько добавить в корзину .on("click", ".to_cart_count_plus", function() { change_to_cart_count($(this).parent(), 1); }) .on("click", ".to_cart_count_minus", function() { change_to_cart_count($(this).parent(), -1); }) // Каталог продукции - Добавить к сравнению .on("click", ".act-add_to_comparison", function() { var $element = $(this); var data = { price_id: $(this).attr("data-price_id"), price_uid: $(this).attr("data-price_uid"), offer_id: $(this).attr("data-offer_id"), offer_uid: $(this).attr("data-offer_uid") }; ajax("catalog.add_to_comparison", data, function (callback) { if (callback['action'] == "added") { $element.addClass("current").find(".text").html("В сравнении"); } else { $element.removeClass("current").find(".text").html("Сравнить"); } }, function (callback) { } ); }) // Каталог продукции - Добавить к отложенному .on("click", ".act-add_to_favorite", function() { var $element = $(this); var data = { price_id: $(this).attr("data-price_id"), price_uid: $(this).attr("data-price_uid"), offer_id: $(this).attr("data-offer_id"), offer_uid: $(this).attr("data-offer_uid") }; ajax("catalog.add_to_favorite", data, function (callback) { console.log(callback['action']); if (callback['action'] == "added") { $element.addClass("current").find(".text").html("Отложено"); } else { $element.removeClass("current").find(".text").html("Отложить"); } }, function (callback) { } ); }); // Несколько предложений для одного товара - переключение цены $(document).on("change", ".offer_select", function() { var offer = $(this).find(':selected'); var $product = $(this).closest(".product"); $product.find(".price_val").html(offer.data("offer-price")); $product.find(".button_add_to_cart").attr("data-offer-id", offer.data("offer-id")); $product.find(".button_add_to_cart").attr("data-offer-uid", offer.data("offer-uid")); $product.find(".button_add_to_cart").attr("data-value", offer.data("offer-price")); if (offer.attr("data-cart-count") > 0) { $product.find(".button_add_to_cart").addClass("has_in_cart").html("В корзине"); } else { $product.find(".button_add_to_cart").removeClass("has_in_cart").html("В корзину"); } }) });var catalog; var slide_banner_started = false; var mobile = false; window.addEventListener("popstate", function(e) { location.reload(); }, false); function load_page(link) { $("#ajax_loader").fadeIn(100); if (link[0] !== "#") { $.ajax({ type: 'POST', dataType: "json", url: "/index.php", data: { ajax: "system.load_page", href: link } }).done(function(data) { if (data.success) { $("#ajax_loader").stop().hide(); history.pushState("", "", link); $("main").html(data['html']); console.log(data['page']); /*if ($("#ap_redactor_check").val() == true) { console.log(data.redactor); $("#admin_redactor_panel").find(".ap_wrapper").html(data.redactor); }*/ apply_events(); } else { window.location.href = link; } }).error(function (jqXHR, textStatus, errorThrown) { console.log(jqXHR.responseText); notification(element, "error", "Получен неверный ответ сервера"); }); } } function ajax(action, data, success_f, error_f) { data["ajax"] = action; $.ajax({ data: data, type: 'POST', dataType: "json", url: "/index.php" }).done(function(data) { if (data.success) { success_f(data); } else { error_f(data); } }).error(function (jqXHR, textStatus, errorThrown) { console.log(jqXHR.responseText); }); } function apply_events() { if (!mobile) //$(".product").first().addClass("focus").find("input").focusWithoutScrolling().select(); $(".select").select2({ minimumResultsForSearch: Infinity }); } $(function() { $(".banner_slide_left").click(function () { banner_slide("next"); }); $(".banner_slide_right").click(function () { banner_slide("prev"); }); function banner_slide(dir) { var $current = $(".banner_container").find(".banner_active"); var $next = ""; if (dir == "next") { if ($current.next(".banner").length) $next = $current.next(".banner"); else $next = $(".banner_container").find(".banner").first(); } if (dir == "prev") { if ($current.prev(".banner").length) $next = $current.prev(".banner"); else $next = $(".banner_container").find(".banner").last(); } $current.removeClass("banner_active"); $next.addClass("banner_active"); } if ($("#mobile").length) mobile = true; $("body") // ajax навигация /*.on("click", "a", function(e) { $("header").find("a.active").removeClass("active"); $(this).addClass("active"); if (!$(this).parents("#admin_panel").length && !$(this).parents("#admin_redactor_panel").length && !$(this).parents(".cke_dialog_body").length) { var link = $(this).attr("href"); if (link[0] != "/") link = $("#page_url").val() + link; if (link.indexOf("admin") == -1 && link.indexOf("callto") == -1 && link[1] != "#" && link[0] != "#") { //$("#search_result").hide(); //$("#catalog_search").val(""); e.preventDefault(); load_page(link); } } })*/ // Закрыть попапы при клике вне попапа .on("click", function(e) { if (!$(e.target).closest(".popup").length) { $(".popup").fadeOut(100); $("#popup_overlay").fadeOut(150); $("#login").removeClass("active"); } if (!$(e.target).closest(".m_header_menu").length && !$(e.target).closest(".m_menu_button").length ) { $(".m_header_menu").removeClass("snow"); } }) .on("click", "#overlay", function(e) { if(e.target != this) return; $("#overlay").fadeOut(100); }) .on("click", ".filter_main_title", function() { $(".filter_main_content").toggle() }) .on("click", ".filter_title", function() { $(this).parent().toggleClass("collapsed"); }) // Снять выделение красным при фокусе на инпуте с ошибкой .on("focus", ".inp_error", function() { $(this).removeClass("inp_error"); }); $("#login").click(function (e) { e.preventDefault(); e.stopPropagation(); $("#login_form").stop().fadeToggle(100); $(this).toggleClass("active"); }); // Вход в систему и регистрация $(".act-show_form_sign-in").click(function(e) { e.preventDefault(); e.stopPropagation(); $("#login_form").stop().fadeToggle(100); }); // Регистрация $(".act-show_form_sign-up").click(function(e) { e.preventDefault(); e.stopPropagation(); $("#register_form").stop().fadeToggle(100); }); $("form[name='form-sign_in']").submit(function(e) { e.preventDefault(); var el = $(this); el.find(".form_notification").hide().html("Загрузка...").slideDown(100); var remembered = 0; if (el.find("input[name='remembered']").is(":checked")) remembered = 1; var data = { "login": el.find("input[name='email']").val(), "password": el.find("input[name='password']").val(), "remembered": remembered }; ajax("system.sign_in", data, function (callback) { location.reload(); }, function () { el.find(".form_notification").html("Введен неверный логин или пароль"); console.log(data.error); } ); }); $(".act-log_in").click(function () { $(this).closest(("form[name='form-sign_in']")).submit(); }); // Выход из системы $(".act-sign_out").click(function() { $.ajax({ type: 'POST', dataType: "json", url: '/index.php', data: { ajax: "system.sign_out" } }).done(function(data) { if (data.success) { location.reload(); } }); }); $(".register_button").click(function() { var notification = $("#register_form").find(".form_notification"); notification.hide(); var error = ''; if ($(".inp_r_password").val() != $(".inp_r_password_repeat").val()) { error = 'Пароль не совпадает с подтверждением пароля'; $(".inp_r_password").addClass("inp_error"); $(".inp_r_password_repeat").addClass("inp_error"); } if ($(".inp_r_password").val().length < 5) { error = 'Минимальная длина пароля 5 символов'; $(".inp_r_password").addClass("inp_error"); $(".inp_r_password_repeat").addClass("inp_error"); } if (error == "") { notification.html("Загрузка...").slideDown(100); $.ajax({ type: 'POST', dataType: "json", url: "/index.php", data: { ajax: "system.registration", name: $(".inp_r_name").val(), email: $(".inp_r_email").val(), password: $(".inp_r_password").val() } }).done(function(data) { if (data.success) { location.reload(); } else { $(".inp_email").addClass("inp_error"); notification.html(data.errorinfo).slideDown(100); } }); } else { notification.html(error).slideDown(100); } }); // Функция применяет все динамичные вызовы. Нужна для повторного вызова при ajax навигации для тех моментов, когда .on не актуален или неприменим apply_events(); $("main") // Меню навигации по каталогу .on("click", ".root_category", function() { var el = $(this).index(); $(".root_category").each(function () { if ($(this).index() != el) $(this).removeClass("hover"); }); $(this).toggleClass("hover"); }).on("mouseleave", ".menu_catalog", function() { $(".root_category").removeClass("hover"); }); function activateSubmenu(row) { var row = $(row); row.addClass("hover"); } function deactivateSubmenu(row) { var row = $(row); row.removeClass("hover"); } /* ========== Попапы / Popups ========== */ $(".popup-close").click(function() { $(this).parent().fadeOut(100); }); // ================================================================================================================= // =============================================== Каталог продукции =============================================== // ================================================================================================================= // Навигация по каталогу продукции $(".catalog_header_button").click(function(e) { e.stopPropagation(); if ($(".content").css("padding-left") == "0px") { $(".menu_catalog").toggleClass("showed"); } }); $(".menu_catalog").mouseleave(function() { if ($(".content").css("padding-left") == "0px") $(".menu_catalog").removeClass("showed"); }); // События всех страниц /* Каталог продукции - Навигация с клавиатуры */ // Фокус на первый продукт в списке var prev_searched = ""; $("#catalog_search").keyup(function(e){ if(e.keyCode == 13) { $("#search_result").hide(); location.href = "/&search=" + $("#catalog_search").val(); //load_page("/&search=" + $("#catalog_search").val()); $("#catalog_search").val(""); } }); $(document) .on("click", ".catalog_search_button", function() { $("#search_result").hide(); location.href = "/&search=" + $("#catalog_search").val(); //load_page("/&search=" + $("#catalog_search").val()); $("#catalog_search").val(""); }) .on("click", function() { $("#search_result").hide(); }).on("click", "#search_result", function(e) { e.stopPropagation(); }).on("keyup", "#catalog_search", function(e) { if (e.keyCode === 27) { $("#search_result").hide(); } else if (e.keyCode === 13) { if ($("#search_result").find(".focus").length) { // Перейти на продукт //catalog_load_product($("#search_result").find(".focus").attr("href"),null,null); } else { $("#search_result").hide(); //reload_catalog("search",0,-1,"",$("#catalog_search").val()); } } else { var search = $("#catalog_search").val(); if (search.length > 2) { if (prev_searched != search) { $("#search_result").find(".focus").removeClass("focus"); prev_searched = search; $.ajax({ type: 'POST', dataType: "json", url: "/index.php", data: { ajax: "catalog.live_search", search: search } }).done(function(data) { if (data.success) { if (data.result.length > 0) { $("#search_result").show(); $("#search_result").html(data.result); } else { $("#search_result").hide(); } } else console.log(data); }); } } else { $("#search_result").hide(); } } }).keydown(function(e) { if ($("#catalog_search").is(':focus')) { // Стрелка вниз if (e.keyCode == 40) { if ($("#search_result").find(".focus").length) { if ($("#search_result").find(".focus").next().length) $("#search_result").find(".focus").removeClass("focus").next().addClass("focus"); } else { $("#search_result a").first().addClass("focus"); } } // Стрелка вверх if (e.keyCode == 38) { if ($("#search_result").find(".focus").prev().length) $("#search_result").find(".focus").removeClass("focus").prev().addClass("focus"); } } else { if ($(".count").is(":focus")) { // Стрелка вниз if (e.keyCode == 40) { e.preventDefault(); if ($(".product.focus").next(".product").length) $(".product.focus").removeClass("focus").next().addClass("focus").find("input").focus().select(); } // Стрелка вверх if (e.keyCode == 38) { e.preventDefault(); if ($(".product.focus").prev(".product").length) $(".product.focus").removeClass("focus").prev().addClass("focus").find("input").focus().select(); } // Стрелка вправо if (e.keyCode == 39) { e.preventDefault(); $(".product.focus").find(".to_cart_count_plus").click(); } // Стрелка влево if (e.keyCode == 37) { e.preventDefault(); $(".product.focus").find(".to_cart_count_minus").click(); } } } }).on("focus", ".count", function() { $(".product.focus").removeClass("focus"); $(this).closest(".product").addClass("focus"); }).on("mouseenter", ".product", function() { $(".product.focus").removeClass("focus"); if (!mobile) $(this).addClass("focus").find("input").focusWithoutScrolling().select(); }).on("keydown", ".count", function(e) { if (e.keyCode == 13) { add_to_cart($(this).parent().parent().find("button")); } }); $("#search_result").on("mouseover", "a", function() { $("#search_result").find(".focus").removeClass("focus"); $(this).addClass("focus"); }); /* Каталог продукции - Добавить в корзину */ $(document).on("click", ".act-add_to_cart", function() { add_to_cart($(this)); }); function add_to_cart(target) { if (!target.hasClass("has_in_cart")) { if (target.prev().find(".count").length) var count = target.prev().find(".count").val(); else count = 1; update_cart_widget(1, target.data("value"), count); $.ajax({ type: "POST", dataType: "json", url: "/index.php", data: { ajax: "cart.add_to_cart", price_id: target.attr("data-id"), price_uid: target.attr("data-uid"), offer_id: target.attr("data-offer-id"), offer_uid: target.attr("data-offer-uid"), count: count } }).done(function(data) { if (data.success) { target.addClass("has_in_cart").find(".text").html("В корзине"); $(".cart_widget").html(data['cart_widget_content']); } else { console.log(data.error); } }).error(function (jqXHR, textStatus, errorThrown) { console.log(jqXHR.responseText); }); } else { window.location = "/cart/"; } } /* Каталог продукции - корзина - Оформить заказ */ $("#send_order").click(function() { $.ajax({ type: 'POST', dataType: "json", url: '/index.php', data: { ajax: "send_order", name: $("#inp_name").val(), email: $("#inp_email").val(), phone: $("#inp_phone").val(), buyer: $("input[name=buyer]:checked").val(), delivery_method: $("input[name=delivery_method]:checked").val(), payment_method: $("input[name=payment_method]:checked").val(), organ: $("#inp_organ").val(), inn: $("#inp_inn").val(), city: $("#inp_city").val(), address: $("#inp_address").val(), comment: $("#inp_comment").val() } }).done(function(data) { if (data.success) { if ($("input[name=payment_method]:checked").val() == 'online' && $("input[name=buyer]:checked").val() == 'ph') { $("#pf_sum").val($(".cart_total").html()); $("#pf_customer").val($(".inp_email").val()); $("#pf_email").val($(".inp_email").val()); $("#pf_phone").val($(".inp_phone").val()); $("#pf_orderid").val(data.id); $("#payform").submit(); } else { $("#ordering_form").hide(); $("#ordering_success").show(); $(".order_number").html(data.id); if (data.hash != '') { $("#ordering_success").find('a').show().attr('href', '/print.php?order='+data.hash); } } } }); }); // Выбор заранее введенного адреса $("select[name=saved_address]").change(function() { $("input[type=text]").val(""); var val = $("select[name=saved_address] option:selected").val(); if (val == "select" || val == "none") { $(".address_form").hide(); } else { $.ajax({ type: "POST", dataType: "json", url: "/index.php", data: { ajax: "user_delivery.get_saved_address", id: val } }).done(function(data) { if (data.success) { $("input[name=buyer]").attr("checked", false); $("input[name=delivery]").attr("checked", false); if (data.delivery == "delivery") { $(".input_section-deliver").show(); $("input[value='delivery']").attr("checked", true); } else { $("input[value='manual']").attr("checked", true); $(".input_section-deliver").hide(); } if (data.buyer == "ph") { $(".input_section-ur").hide(); $(".input_section-ph").show(); $("input[value='ph']").attr("checked", true); } else { $(".input_section-ur").show(); $(".input_section-ph").hide(); $("input[value='ur']").attr("checked", true); } $("#inp_title").val(data.title); $("#inp_name").val(data.name); $("#inp_email").val(data.email); $("#inp_phone").val(data.phone); $("#inp_organ").val(data.organ); $("#inp_inn").val(data.inn); $("#inp_city").val(data.city); $("#inp_address").val(data.address); } else { console.log(data.error); } }); $(".address_form").show(); $("#inp_action").val(val); } }); $(document).on("change", ".offer_select", function() { var val = $(this).val(); $(this).closest(".product").find('.price_val').html(val.split('#')[1]); $(this).closest(".product").find('.act-add_to_cart').attr('data-offer', val.split('#')[0]); }) .on("click", ".second_img img", function() { var src = $(this).attr('src'); $(".second_img").find('.active').removeClass('active'); $(this).addClass('active').parent().prev().find('img').attr('src', src); }); // Переход наверх if ($('#go_up').length) { var scrollTrigger = 300, // px backToTop = function () { var scrollTop = $(window).scrollTop(); if (scrollTop > scrollTrigger) { $('#go_up').addClass('show'); } else { $('#go_up').removeClass('show'); } }; backToTop(); $(window).on('scroll', function () { backToTop(); }); $('#go_up').on('click', function (e) { e.preventDefault(); $('html,body').animate({ scrollTop: 0 }, 700); }); } }); function change_to_cart_count(target, value) { var current = parseInt(target.find("input").val(), 10); current = current + value; if (current > 0 && current < 10000) { target.find("input").val(current); } } function update_cart_widget(count, price, add_count) { var cart_count = $("#cart").find(".count").html(); cart_count = parseInt(cart_count, 10) + count; $("#cart").find(".count").html(cart_count); } function isInt(n) { return n % 1 === 0; } $.fn.focusWithoutScrolling = function(){ var x = $(document).scrollLeft(), y = $(document).scrollTop(); this.focus(); window.scrollTo(x, y); return this; //chainability };