var core = {
"popupHtml" : `
`,
"closeMobileMenu" : function(){
$(".mobile-menu").remove();
},
"sendRemindPass" : function(){
$(".main-popup .error-text").hide();
var email = $("#remindPass #email").val();
$.ajax({
url: "/forgot-password",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{email:email},
success: function (data) {
let response = JSON.parse(data)
if(response.status == 'error'){
$(".main-popup .error-text").show();
$(".main-popup .error-text").text(response.message);
}else{
core.openPopup(
'Электронное письмо Отправлено!',
'На ваш адрес электронной почты было отправлено электронное письмо с инструкциями о том, как сбросить пароль. Если вы не получите его в течение нескольких минут, пожалуйста, проверьте, что вы использовали адрес электронной почты для своей учетной записи IziBuy, и повторите попытку или обратитесь к нам за помощью.'
);
}
}
});
},
"openRemindPassPopup":function(){
let body = `
`;
let footer = `Отправить Электронное письмо `;
core.openPopup('Forgot your password?',body,footer);
},
"addQty":function(cart_id,add=true){
var num = $("#cart_item_"+cart_id+" .item_qty input").val();
var action = 'add';
let counter = $(".cart-count").text();
if(add){
num++;
counter = parseInt(counter) + 1;
$(".cart-count").text(counter);
}else{
num--;
action = 'sub';
counter = parseInt(counter) - 1;
$(".cart-count").text(counter);
}
if(num < 1){
$("#cart_item_"+cart_id+"").fadeOut();
}
$.ajax({
url: "/cart/qty/"+cart_id,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: "POST",
data: {func:action},
success: function (data) {
let response = JSON.parse(data)
$("#cart_item_"+cart_id+" .item_qty input").val(num);
if(typeof response.price !== "undefined"){
$('.cart_item_price_'+cart_id).text(response.price)
}
}
});
},
"openMobileMenu" : function(){
var currency = $(".currency-select").clone();
var currency_div = $("
").append(currency);
var lang = $(".language-select").clone();
var list = $("li",lang);
var lang_select = $(' ',{onchange:'TranslateSetCookie($(this).val());window.location.reload();'})
$.each(list,(i,v)=>{
var lang = $(v).attr("data-google-lang");
if($(".language__active--"+lang).length) lang_select.append(""+lang+" ")
else lang_select.append(""+lang+" ")
})
$(lang).find(".dropdown-toggle").remove()
$(lang).find(".dropdown").remove()
$(lang).append(lang_select)
var lang_div = $("
").append(lang);
$('body').prepend(
``
);
setTimeout(function(){
$('.mobile-menu-wrapper').addClass('show')
},50)
// Lang dropdown toggle
$('.dropdown-toggle').click(function () {
$(this).next('.dropdown').slideToggle();
});
$(document).click(function (e) {
var target = e.target;
if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
$('.dropdown').slideUp();
}
});
},
"removeCategoryTree" : function(ref){
$(ref).parent().removeClass("show");
setTimeout(function(){
$(ref).parent().remove();
if(!$(".slide-category").length){
$("details.catalog").removeClass("open");
}
},200);
},
"getCategoryTree" : function(ref,marketplace,category, path = []){
/*
if(marketplace == 'yahooshopping'){
let list = $(ref).parent().parent().find('.sub-category a:not(.subsub_item)');
let zindex = $(".slide-category").length;
zindex+=100;
let ul = $("
",{class:"slide-category",style:"z-index:"+zindex+";"});
ul.append(
$("
",{text:"Назад",style:"padding:10px;cursor:pointer;font-size: 24px;",onclick:"core.removeCategoryTree(this)"}).prepend(
` `
)
);
ul.append($(""));
$(ul).find("ul").append(
`
`
);
$.each(list,(i,v)=>{
let href = $(v).attr('href');
let name = $(v).text();
if( !$('.sub-list-item[data-id="'+v.id+'"]').length){
console.log(list);
var spanSvg = '';
var subonclick = '';
if ($(v).hasClass('btn_subsub')) {
spanSvg = ' ';
subonclick = 'onclick="core.getCategoryTree(this,\'yahooshopping\',\'\');return false;"';
}
var subsub = '';
if ($(v).next().hasClass('wrp_subsub')) {
subsub += '';
}
$(ul).find("ul").append(
`
`+subsub+`
`
);
}
})
$("details.catalog").prepend(ul)
$("details.catalog").addClass('open');
setTimeout(function(){
$("details.catalog .slide-category").addClass("show");
},50)
}
*/
//if(marketplace == 'yahooauctions'){
$.ajax({
url: "/marketplace/"+marketplace+"/categoryTree/"+category,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: "GET",
data: null,
success: function (data) {
let response = JSON.parse(data)
if(!response.length){
window.location.href = "/marketplace/"+marketplace+"/search/?c="+ category +"&l=" + category;
}
let zindex = $(".slide-category").length;
zindex+=100;
let ul = $("
",{class:"slide-category",style:"z-index:"+zindex+";"});
ul.append(
$("
",{text:"Назад",style:"padding:10px;cursor:pointer;font-size: 24px;",onclick:"core.removeCategoryTree(this)"}).prepend(
` `
)
);
// ul.append($(""));
ul.append($(""));
$(ul).find("ul").append(
`
`
);
$.each(response,(i,v)=>{
if( !$('.sub-list-item[data-id="'+v.id+'"]').length){
var input = '';
var checked = (v.checked) ? 'checked' : '';
if (v.admin) {
input = ' ';
}
$(ul).find("ul").append(
`
`
);
}
})
if(response.length){
$("details.catalog").prepend(ul)
$("details.catalog").addClass('open');
setTimeout(function(){
$("details.catalog .slide-category").addClass("show");
},50)
}
$.getScript("//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit");
path.shift();
if (path[0]) {
core.getCategoryTree($('#_aid_' + path[0].parent_id), marketplace, path[0].parent_id, path);
}
}
});
//}
},
"submitUpdateBet" : function(auction_id){
$(".main-popup .error-text").hide();
event.stopPropagation();
event.preventDefault();
let bet = $('#makeBet-form input[name="bet"]').val();
$.ajax({
url: "/cart/bet/"+auction_id+"/update",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: "POST",
data: {id:auction_id,bet:bet},
success: function (data) {
let response = JSON.parse(data)
if(response.status == "funds"){
let balance = response.balance;
let body = `Не хватает баланса (¥`+balance+`). Пожалуйста, пополните счет
`;
let footer = `Добавить Средства `;
core.openPopup('Уведомление',body,footer);
}else if(response.status == "success"){
location.href="/cart";
}else{
$(".main-popup .error-text").show();
$(".main-popup .error-text").text(response.message);
}
}
});
},
"updateBet" : function(auction_id,price){
let body = `
`;
let footer = `Обновите ставку `;
core.openPopup('Обновите Свою Ставку',body,footer);
},
"submitShipping" : function(){
$(".popup-body .error-text").empty();
var items = []
var list = $(".products-wrapper li");
var address_id = $("#addresses").val();
$.each(list,function(i,v){
var id = $(v).attr("data-id");
var type = $(v).attr("data-type");
items.push({id:id,type:type})
})
$.ajax({
url: "/shipping/add",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {address_id:address_id,items:items},
success: function (data) {
var response = JSON.parse(data);
if(response.status == "error"){
$(".popup-body .error-text").text(response.message);
$(".popup-body .error-text").show();
}else{
let body = `Вы успешно создали пакет доставки. Мы обновим цену доставки и проинформируем вас.
`;
let footer = `Закрывать `;
core.openPopup('Спасибо',body,footer);
$(".main-popup .close-button").attr("onclick","window.location.reload()");
$('.main-popup-fade').click(function(e) {
if ($(e.target).closest('.main-popup').length == 0) {
window.location.reload()
}
});
$.each(list,function(i,v){
var id = $(v).attr("data-id");
$("#cart_item_"+id).fadeOut();
})
}
}
});
},
"createShipping" : function(){
$.ajax({
url: "/shipping/addresses",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: null,
success: function (data) {
var response = JSON.parse(data);
var addresses = response.addresses;
var products = response.products;
var div = $("
");
var select_addresses = $(" ",{id:"addresses",class:"notranslate"});
var products_list = $("",{id:"productsList"});
$.each(addresses,function(i,v){
select_addresses.append(
``+v.country+`,`+v.city+`,`+v.street+`,`+v.house+`,`+v.apartment+` `
)
})
var wrapper = $("
",{class:"addresses-wrapper"});
wrapper.append(
$(' ',{for:"addresses",text:"Выберите Адрес Доставки",style:"font-weight: bold;font-size: 16px;margin: 10px 0;margin-bottom: 20px;"}),
select_addresses
);
$.each(products,function(i,v){
let paramsText = '';
let qtyText = '';
if(typeof v.parameters !== "undefined"){
let params = JSON.parse(v.parameters);
$.each(params,(n,p)=>{
paramsText+=''+p.name+': '+p.value+' ';
})
}
if(typeof v.qty !== "undefined") qtyText = 'Quantity: '+v.qty+' '
else qtyText = 'Quantity: 1 '
products_list.append(
`
`+v.product_title+`
`+paramsText+`
`+qtyText+`
`
)
})
var wrapper2 = $("
",{class:"products-wrapper"});
wrapper2.append(
$('
',{text:"Выберите продукты, которые вы хотели бы получить",style:"font-weight: bold;font-size: 16px;margin: 10px 0;margin-bottom: 20px;"}),
products_list
);
div.append(wrapper);
div.append(wrapper2);
div.append('
');
let body = div.html();
let footer = `Создавать `;
core.openPopup('Создание транспортной посылки',body,footer);
$(".main-popup.popup").addClass("lg")
}
});
},
"removeProduct":function(id){
$("li#product_"+id).remove();
},
"openPopup" : function(title=false,body=false,footer=false,close=true){
core.closePopup();
setTimeout(function(){
let popup = $('.main-popup');
if(title){
popup.find('.popup-header').append('');
}
if(body){
popup.find('.popup-body').append(body);
}
if(footer){
popup.find('.popup-footer').append(footer);
}
$(".main-popup-fade").fadeIn(0);
$(".main-popup").fadeIn(0);
$(".main-popup.popup").addClass("show");
if(close){
$('.main-popup-fade').click(function(e) {
if ($(e.target).closest('.main-popup').length == 0) {
$(this).fadeOut(0);
}
});
}
},100);
},
"closePopup" : function(){
let html = core.popupHtml;
$(".main-popup.popup").removeClass("lg")
$(".main-popup.popup").removeClass("show");
$(".main-popup").hide();
$(".main-popup-fade").hide();
$(".main-popup").html($(html).html());
},
"closeBetPopup" : function(){
$('.popup').removeClass('show');
$('.popup-fade--bet').hide();
$('#popup--bet').hide();
},
"closeAddFundsPopup" : function(){
$('.popup').removeClass('show');
$('.popup-fade--addFunds').hide();
$('#popup--addFunds').hide();
},
"openAddFundsPopup" : function(){
$('.popup').removeClass('show');
$('#popup--registration').hide();
$('.popup-fade--addFunds').fadeIn(0);
$('#popup--addFunds').fadeIn(0);
},
"openRegisterPopup" : function(){
var div = `
`;
core.openPopup('Registration',div);
},
"sendRegister":function(){
event.stopPropagation();
event.preventDefault();
$("#register-form .error-text").hide();
$("#register-form .error-text").text("");
let dataToSend = {
"email" : $("#register-form input[name='email']").val(),
"password" : $("#register-form input[name='password']").val(),
"password_confirmation" : $("#register-form input[name='password_confirmation']").val(),
}
$.ajax({
url: "/register",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {...dataToSend},
success: function (data) {
let response = JSON.parse(data)
if(response.status == "error"){
$("#register-form .error-text").text(response.message);
$("#register-form .error-text").show();
}else{
location.reload();
}
}
});
},
"getProductReviews" : function(id,page=1,isguest=false){
let dataToSend = {};
dataToSend['page'] = page;
$.ajax({
url: "/reviews/"+id,
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: dataToSend,
success: function (data) {
let response = JSON.parse(data)
var target = $('#reviews_list');
target.empty();
$('.product-reviews .pagination').remove();
$('.product-reviews .product-reviews-score').remove();
if(response.status == 'success'){
$.each(response.data,function(i,v){
var li = `
`;
target.append(li);
});
var pages = Math.ceil(parseInt(response.total)/10);
var pagination = $('');
for(var i = 1; i <= pages; i++){
var cls = '';
if(page == i) cls = 'active';
pagination.append(``+i+` `);
}
target.after(pagination);
if(response.total != "0"){
var func = `Оставить отзыв `;
if(isguest) func = `Оставить отзыв `;
target.before(
`
Рейтинг продукта составляет (`+response.rating+`)
основанный на (`+response.total+`) обзоры
`+func+`
`
);
}else{
var func = `Оставить первый отзыв `;
if(isguest) func = `Оставить первый отзыв `;
target.before(`Отзывов об этом продукте не найдено. Будьте первым, кто оставит отзыв.
`+func+`
`);
}
$('.total_product_counter').text(' ('+response.total+')');
}
$([document.documentElement, document.body]).animate({
scrollTop: $("#product_reviews_score").offset().top - 300
}, 300);
}
});
},
"submitReview" : function(id){
$('#reviewPopup .error-text').text();
$('#reviewPopup .error-text').hide();
var text = $('#review_text').val();
var rating = $('input[name="rating"]:checked').data('stars');
if(rating == undefined){
$('#reviewPopup .error-text').text('Пожалуйста, выберите рейтинг');
$('#reviewPopup .error-text').show();
}
let dataToSend = {};
dataToSend['id'] = id;
dataToSend['text'] = text;
dataToSend['rating'] = rating;
$.ajax({
url: "/reviews/"+id+"/add",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {...dataToSend},
success: function (data) {
let response = JSON.parse(data)
if(response.status == 'error'){
$('#reviewPopup .error-text').text(response.message);
$('#reviewPopup .error-text').show();
}else{
core.getProductReviews(id);
core.closePopup();
}
}
});
},
"reviewPopup" : function(id){
var title = 'Оцените свой опыт';
let body = `
`;
let footer = `Оставить отзыв `;
core.openPopup(title,body,footer,false);
},
"googleLogin" : function(){
$.ajax({
url: "/googleCheckLogin",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: null,
success: function (data) {
let response = JSON.parse(data)
if(typeof response.login !== "undefined"){
window.location.href=response.login
}else{
$("#login-form .error-text").text('Произошла ошибка, пожалуйста, попробуйте другой способ входа в систему');
$("#login-form .error-text").show();
}
}
});
},
"fbLogin" : function(){
$.ajax({
url: "/fbloginCheck",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: null,
success: function (data) {
let response = JSON.parse(data)
if(typeof response.login !== "undefined"){
window.location.href=response.login
}else{
$("#login-form .error-text").text('Произошла ошибка, пожалуйста, попробуйте другой способ входа в систему');
$("#login-form .error-text").show();
}
}
});
},
"openLoginPopup" : function(){
var div = `
`;
core.openPopup('Авторизоваться',div);
},
"sendLogin":function(){
event.stopPropagation();
event.preventDefault();
$("#login-form .error-text").hide();
$("#login-form .error-text").text("");
let dataToSend = {
"email" : $("#login-form input[name='email']").val(),
"password" : $("#login-form input[name='password']").val(),
}
$.ajax({
url: "/login",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {...dataToSend},
success: function (data) {
let response = JSON.parse(data)
if(response.status == "error"){
$("#login-form .error-text").text(response.message);
$("#login-form .error-text").show();
}else{
location.reload();
}
}
});
},
"openCatalogMobile" : function() {
$('#sidebar-container').css('display','flex')
$('#main').css('display','none')
},
"closeCatalogMobile" : function() {
$('#sidebar-container').css('display','none')
$('#main').css('display','flex')
},
"setMarketplace": function (id) {
event.preventDefault();
$.ajax({
url: "/marketplace",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {'action': 'setMarketplace', 'id': id},
success: function (data) {
location.href = "/";
}
});
},
"changeCurrency": function () {
var select = event.target;
var currency = $(select).val();
$.ajax({
url: "/marketplace",
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {'action': 'setCurrency', 'id': currency},
success: function (data) {
location.reload();
}
});
},
"scrollUp": function () {
window.scrollTo({top: 0, behavior: 'smooth'});
},
"submitBuyProduct" : function(cart_id){
let dataToSend =
{
'cart_id': cart_id,
};
$.ajax({
url: "/cart/buy/"+cart_id,
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {...dataToSend},
success: function (data) {
let response = JSON.parse(data)
if(response.status == "success"){
let body = `Благодарим вас за оплату, ваш товар будет отправлен на наш склад. Мы сообщим вам об этом, как только оно поступит.
`;
let footer = `Закрывать `;
core.openPopup('Спасибо',body,footer);
$(".main-popup .close-button").attr("onclick","window.location.reload()");
$("#cart_item_"+cart_id).fadeOut();
$('.main-popup-fade').click(function(e) {
if ($(e.target).closest('.main-popup').length == 0) {
window.location.reload()
}
});
}else if(response.status == "funds"){
let notenough = response.notenough;
let notenough_rate = response.notenough_rate;
let body = `Для оплаты товара не хватает `+notenough+` ¥ (`+notenough_rate+`). Пожалуйста, пополните счёт.
`;
let footer = `Пополнить `;
core.openPopup('Уведомление',body,footer);
}
}
});
},
"buyProduct" : function(cart_id,price){
let body = `Пожалуйста, подтвердите, что вы хотите купить этот продукт для (`+price+`)
`;
let footer = `Подтверждать `;
core.openPopup('Подтвердите Покупку',body,footer);
},
"submitPayShipping" : function(order_id){
let dataToSend =
{
'order_id': order_id,
};
$.ajax({
url: "/cart/pay/shipping/"+order_id,
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {...dataToSend},
success: function (data) {
let response = JSON.parse(data)
if(response.status == "success"){
let body = `Спасибо за ваш платеж, отгрузка была оплачена. Ваш заказ будет отправлен как можно скорее.
`;
let footer = `Закрывать `;
core.openPopup('Спасибо',body,footer);
$("#order_item_"+order_id).fadeOut();
$(".main-popup .close-button").attr("onclick","window.location.reload()");
$('.main-popup-fade').click(function(e) {
if ($(e.target).closest('.main-popup').length == 0) {
window.location.reload()
}
});
}else if(response.status == "funds"){
let balance = response.balance;
let body = `Не хватает баланса (¥`+balance+`). Пожалуйста, пополните счет
`;
let footer = `Добавить Средства `;
core.openPopup('Уведомление',body,footer);
}
}
});
},
"payShipping" : function(order_id,price){
let body = `Пожалуйста, подтвердите, что вы хотите оплатить доставку заказа #`+order_id+` за (`+price+`)
`;
let footer = `Подтверждать `;
core.openPopup('Подтвердите Покупку',body,footer);
},
"removeFromCart" : function(cart_id){
let dataToSend =
{
'cart_id': cart_id,
};
$.ajax({
url: "/cart/remove/"+cart_id,
method: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {...dataToSend},
success: function (data) {
$("#cart_item_"+cart_id).fadeOut();
let counter = $(".cart-count").text();
counter = parseInt(counter) - 1;
if(counter < 0) counter = 0;
$(".cart-count").text(counter);
}
});
},
"addToCart" : function(ref){
$('.product-options-notice').remove()
let button = $(ref)
if (button.hasClass("incart")) {
$.ajax({
url: "/cart/" + button.data('cart_id'),
method: "DELETE",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
button.removeClass('incart')
button.text('Добавить в корзину');
let counter = $(".cart-count").text();
counter = parseInt(counter) - 1;
if(counter < 0) counter = 0;
$(".cart-count").text(counter);
}
});
} else {
let error = false
let options = $('.product-options[data-id="'+button.data('product_id')+'"] .product-options-item');
let params = [];
$.each(options,function(i,v){
let name = $("select",v).attr("name");
let value = $("select",v).val();
if(value == "") error = true;
params.push({name:name,value:value});
});
if(error){
$(".product-options").append("Пожалуйста, выберите необходимые параметры
")
return false;
}
let dataToSend =
{
'product_id': button.data('product_id'),
'price': button.data('price'),
'qty': 1,
'marketplace_id': button.data('marketplace_id'),
'product_type': button.data('product_type'),
'product_title': button.data('product_title'),
'image_url': button.data('image_url'),
'product_url': button.data('product_url'),
'parameters' : JSON.stringify(params),
'csrf-token' : $('meta[name="csrf-token"]').attr('content')
};
$.ajax({
url: "/cart/",
method: "POST",
data: {...dataToSend},
success: function (data) {
let response = JSON.parse(data)
if(response.status == 'success'){
button.attr("data_cart_id",response.data)
// button.addClass('incart');
button.text('Добавлен');
setTimeout(function(){
button.text('Добавить в корзину');
},2000);
let counter = $(".cart-count").text();
counter = parseInt(counter) + 1;
if(counter < 0) counter = 0;
$(".cart-count").text(counter);
}
}
});
}
},
"submitBet" : function(){
$(".main-popup .error-text").hide();
event.stopPropagation();
event.preventDefault();
let dataToSend = JSON.parse($('#makeBet-form input[name="data"]').val());
let bet = $('#makeBet-form input[name="bet"]').val();
let bidOrBuy = $("#makeBet-form #bidOrBuy").prop("checked");
dataToSend['bet'] = bet;
dataToSend['bidOrBuy'] = bidOrBuy;
$.ajax({
url: "/cart/bet",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: "POST",
data: {...dataToSend},
success: function (data) {
let response = JSON.parse(data)
if(response.status == "funds"){
let balance = response.balance;
let body = `Не хватает баланса (¥`+balance+`). Пожалуйста, пополните счет
`;
let footer = `Добавить Средства `;
core.openPopup('Уведомление',body,footer);
}else if(response.status == "success"){
location.href="/cart";
}else{
$(".main-popup .error-text").show();
$(".main-popup .error-text").text(response.message);
}
}
});
},
"bidOrBuy" : function(price){
$("#makeBet-form input[name='bet']").val(price)
},
"makeBet" : function(ref) {
let button = $(ref)
let dataToSend =
{
'product_id': button.data('product_id'),
'price': button.data('price'),
'buy_price': button.data('buy_price'),
'qty': 1,
'marketplace_id': button.data('marketplace_id'),
'marketplace_id': button.data('marketplace_id'),
'auction_start': button.data('auction_start'),
'auction_end': button.data('auction_end'),
'product_type': button.data('product_type'),
'product_title': button.data('product_title'),
'image_url': button.data('image_url'),
'product_url': button.data('product_url'),
};
var minValue = parseFloat(dataToSend.price);
let bidOrBuy = ``;
if(dataToSend.buy_price > 0){
bidOrBuy = ``;
}
let body = `
`;
let footer = `Сделайте ставку `;
core.openPopup('Сделайте ставку',body,footer);
},
"updateNumbers": function () {
document.getElementById('number-max').value = document.getElementById('range-max').value
document.getElementById('number-min').value = document.getElementById('range-min').value
},
"updateRange": function () {
document.getElementById('range-max').value = document.getElementById('number-max').value
document.getElementById('range-min').value = document.getElementById('number-min').value
},
"toggleAccordion" : function() {
event.currentTarget.nextElementSibling.classList.toggle('faq__list--open');
},
"makeMaxBet" : function() {
$('.popup-fade--max-bet').fadeIn(0);
},
"makeSnipeBet" : function() {
$('.popup-fade--snipe-bet').fadeIn(0);
},
"searchCategory": function () {
var value = $('#searchinput').val().toLowerCase();
$(".category").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
},
"toggleAnswer" : function() {
event.currentTarget.nextElementSibling.classList.toggle('faq__answer--open');
},
"toggleTrackList" : function() {
$('.dropdown-list').toggleClass('dropdown-list--open')
},
};
var userLang = navigator.language || navigator.userLanguage;
if (userLang != 'zh-CN') {
userLang = userLang.substr(0, 2).toLowerCase();
}
window.googleTranslateConfig = {
lang: userLang,
};
window.TranslateInit = function () {
let code = TranslateGetCode();
var cookie = getCookie('googtrans');
if (cookie == undefined || cookie == "null") {
TranslateSetCookie(userLang);
}
$('.language-select').addClass('language__active--' + code);
// Инициализируем виджет с языком по умолчанию
new google.translate.TranslateElement({
multilanguagePage: true,
pageLanguage: googleTranslateConfig.lang,
});
// Вешаем событие клик на флаги
$('[data-google-lang]').click(function () {
TranslateSetCookie($(this).attr("data-google-lang"))
// Перезагружаем страницу
window.location.reload();
});
}
window.TranslateGetCode = function () {
// Если куки нет, то передаем дефолтный язык
let lang = (getCookie('googtrans') != undefined && getCookie('googtrans') != "null") ? getCookie('googtrans') : googleTranslateConfig.lang;
return lang.substr(-2);
}
window.TranslateClearCookie = function () {
eraseCookie('googtrans')
}
window.TranslateSetCookie = function (code) {
// Записываем куки /язык_который_переводим/язык_на_который_переводим
eraseCookie('googtrans');
setCookie('googtrans', "/auto/" + code, 30)
}
window.setCookie = function (name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
window.eraseCookie = function (name) {
document.cookie = name + '=; domain=.izibuy.jp; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
window.getCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
window.core = core;
$(document).ready(function(){
// Lang dropdown toggle
$('.dropdown-toggle').click(function () {
$(this).next('.dropdown').slideToggle();
});
$(document).click(function (e) {
var target = e.target;
if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
$('.dropdown').slideUp();
}
});
});
//Валидация формы в личном кабинете
$(document).ready(function ($) {
const minLenght = 1
const maxLenght = 190
const maxPhoneLenght = 20
$('#last_name').on('keyup',function (e) {
let valueLength = $('#last_name').val().length;
if (valueLength < minLenght) {
e.target.setCustomValidity(`Минимум ${minLenght} символ`);
} else if (valueLength > maxLenght) {
e.target.setCustomValidity(`Максимум ${maxLenght} символов`);
} else {
e.target.setCustomValidity('');
}
e.target.reportValidity();
})
$('#first_name').on('keyup',function (e) {
let valueLength = $('#first_name').val().length;
if (valueLength < minLenght) {
e.target.setCustomValidity(`Минимум 1 символ`);
} else if (valueLength > maxLenght) {
e.target.setCustomValidity(`Максимум 190 символов`);
} else {
e.target.setCustomValidity('');
}
e.target.reportValidity();
})
$('#middle_name').on('keyup',function (e) {
let valueLength = $('#middle_name').val().length;
if (valueLength > maxLenght) {
e.target.setCustomValidity(`Максимум 190 символов`);
} else {
e.target.setCustomValidity('');
}
e.target.reportValidity();
})
$('#email').on('keyup',function (e) {
let valueLength = $('#email').val().length;
if (valueLength < minLenght) {
e.target.setCustomValidity(`Обязательное поле`);
} else if (valueLength > maxLenght) {
e.target.setCustomValidity(`Максимум 190 символов`);
} else {
e.target.setCustomValidity('');
}
e.target.reportValidity();
})
$('#phone').on('keyup',function (e) {
let valueLength = $('#phone').val().length;
if (valueLength > maxPhoneLenght) {
e.target.setCustomValidity(`Максимум 20 символов`);
} else {
e.target.setCustomValidity('');
}
e.target.reportValidity();
})
$('#current_password').on('keyup',function (e) {
let valueLength = $('#current_password').val().length;
e.target.setCustomValidity('');
e.target.reportValidity();
})
$('#new_password').on('keyup',function (e) {
let valueLength = $('#new_password').val().length;
e.target.setCustomValidity('');
e.target.reportValidity();
})
$('#new_password_confirmation').on('keyup',function (e) {
let valueLength = $('#new_password_confirmation').val().length;
e.target.setCustomValidity('');
e.target.reportValidity();
})
$("#new_password_confirmation").on("keyup", function() {
var value_input1 = $("#new_password").val();
var value_input2 = $(this).val();
if(value_input1 != value_input2) {
$("#password-error").css('display','block')
$("#submit").attr("disabled", "disabled");
} else {
$("#submit").removeAttr("disabled");
$("#password-error").css('display','none')
}
});
});
//Валидация формы регистрации
$(document).ready(function ($) {
const minLenght = 1
const maxLenght = 255
const normalLenght = 8
$('#popup--registration input[name=email]').on('keyup',function (e) {
let valueLength = $('#popup--registration input[name=email]').val().length;
if (valueLength < minLenght) {
e.target.setCustomValidity(`Обязательное поле`);
} else if (valueLength > maxLenght) {
e.target.setCustomValidity(`Максимум 190 символов`);
} else {
e.target.setCustomValidity('');
}
e.target.reportValidity();
})
$('#popup--registration input[name=password]').on('keyup',function (e) {
let valueLength = $('#popup--registration input[name=password]').val().length;
if (valueLength < normalLenght) {
e.target.setCustomValidity(`Минимум 8 символов`);
} else {
e.target.setCustomValidity('');
}
e.target.reportValidity();
})
$('#popup--registration input[name=password_confirmation]').on("keyup", function() {
var value_input1 = $('#popup--registration input[name=password]').val();
var value_input2 = $(this).val();
if(value_input1 != value_input2) {
$("#password-error").css('display','block')
$("#submit-button").attr("disabled", "disabled");
} else {
$("#submit-button").removeAttr("disabled");
$("#password-error").css('display','none')
}
});
});
removeFromWishlist = function(product_id){
var button = $(event.target);
$.ajax({
url: "/wishlist/" + product_id,
method: "DELETE",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
let counter = $(".wishlist-count").text();
counter = parseInt(counter) - 1;
if(counter < 0) counter = 0;
$(".wishlist-count").text(counter);
button.closest(".favorite-item").fadeOut();
}
});
}
addToWishlist = function (button) {
button = $(button);
if (button.hasClass("added")) {
$.ajax({
url: "/wishlist/" + button.data('product_id'),
method: "DELETE",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
let counter = $(".wishlist-count").text();
counter = parseInt(counter) - 1;
if(counter < 0) counter = 0;
$(".wishlist-count").text(counter);
if(button.hasClass('add-favs')){
button.text('Добавить в список желаний');
}
button.removeClass('added')
}
});t
} else {
let dataToSend =
{
'product_id': button.data('product_id'),
'marketplace_id': button.data('marketplace_id'),
'product_title': button.data('product_title'),
'price': button.data('price'),
'auction_start': button.data('auction_start'),
'auction_end': button.data('auction_end'),
'image_url': button.data('image_url'),
'product_url': button.data('product_url'),
'csrf-token' : $('meta[name="csrf-token"]').attr('content')
}
$.ajax({
url: "/wishlist",
method: "POST",
data: {...dataToSend},
success: function (data) {
let response = JSON.parse(data)
if(response.status == "success"){
let counter = $(".wishlist-count").text();
counter = parseInt(counter) + 1;
if(counter < 0) counter = 0;
$(".wishlist-count").text(counter);
if(button.hasClass('add-favs')){
button.text('Удалить из списка желаний');
}
button.addClass('added')
}
}
});
}
}