function submitProductSearch(form) {
	var input = $(form).find('input[name="search"]');
	var search = $.trim(input.val());

	if (!search) {
		input.trigger('focus');
		return false;
	}

	var url = $(form).data('search-url');
	var separator = url.indexOf('?') === -1 ? '?' : '&';

	window.location.href = url + separator + 'search=' + encodeURIComponent(search);

	return false;
}

function openSearch(el) {
	var form = $('<form>').addClass('search-modal__form').attr('data-search-url', $(el).data('search-url'));
	var intro = $('<div class="search-modal__intro">').append(
		'<span class="search-modal__eyebrow">Каталог Dominik</span>',
		'<h2>Найти платье</h2>',
		'<p>Введите название, модель или характеристику.</p>'
	);
	var field = $('<div class="search-modal__field">').append(
		'<input type="search" name="search" placeholder="Например: кружево или длинный рукав" autocomplete="off" aria-label="Поиск">',
		'<button type="submit" aria-label="Найти"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="11" cy="11" r="6.5" stroke="currentColor" stroke-width="1.5"/><path d="M16 16L21 21" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg></button>'
	);

	form.append(intro, field);
	form.on('submit', function() {
		return submitProductSearch(this);
	});

	modal.create({
		modal: form,
		width: 760,
		class: {
			'modal-body': 'search-modal__body'
		},
		callback: {
			show: function() {
				setTimeout(function() {
					form.find('input[name="search"]').trigger('focus');
				}, 200);
			}
		}
	});
}

function NextPage(page, elem, btn){
	console.log(page);
	
	/*if(elem){
		if($.isArray(elem)){
			$(elem).each(function(a,e){
				
				$(e).addClass('position-relative').append('<div class="abs-loading"><div class="spinner-border text-primary avatar-xs" role="status"><span class="visually-hidden">Loading...</span></div></div>');
			})
		} else {
			$(elem).addClass('position-relative').append('<div class="abs-loading"><div class="spinner-border text-primary avatar-xs" role="status"><span class="visually-hidden">Loading...</span></div></div>');
			
		}
		
	}*/
	
	var currentUrl = window.location.href;
	var hasPageParam = currentUrl.indexOf('page=') !== -1;
	if (hasPageParam) {
	  // изменяем значение параметра page на 2
	  currentUrl = currentUrl.replace(/page=\d+/, 'page=' + page);
	} else {
	  // добавляем параметр page со значением 1
	  currentUrl += (currentUrl.indexOf('?') === -1 ? '?' : '&') + 'page=' + page;
	}
	
	$.ajax({			
		url: currentUrl,
		type: 'get',
		dataType: 'html',
		success: function(html) {
			history.pushState(null, null, currentUrl);
			if(elem){
				
			
				if($.isArray(elem)){
					$(elem).each(function(a,e){
						
						$(e).append($(html).find(e).html());
					})
				} else {
					$(elem).append($(html).find(elem).html());
				}
			}	
			//$(btn).remove();
			$(".pagination").html($(html).find('.pagination').html())
			$(elem).find('.abs-loading').remove();
			
			if(!parseInt($('.pagination').find('.active').next().text())){
				$(btn).remove();
			}
		},
		error: function(xhr, ajaxOptions, thrownError) {
			alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
		}
	});
	
	
}



var modal = {
	'load': function(url, data = {}){
		send.post(url, data, function(json){
			modal.create(json);
		}, function(json){
			ShowToast('Не могу продолжить - не получил контент окна', 'warning', 'Предупреждение');
		})
	},
	'create': function(json){
		if(!json['modal']){
			ShowToast('Контент не задан','danger', 'Ошибка');
		} else {
			if(!json['random']){
				json['random'] = token(32);
			}
			var html = $("<div>").addClass('modal fade').attr({
				
				'id': 'modal-' + json['random'],
				'tabindex': '-1',
				'data-bs-backdrop': 'false',
			});
			
			var dialog = $("<div>").addClass('modal-dialog modal-dialog-centered');
			if(json['align']){
				if(json['align'] == 'top'){
					dialog.removeClass('modal-dialog-centered');
				}
			}
			if(json['width']){
				dialog.css('width', json['width']);
				dialog.css('max-width', '100%');
			}
			var content = $('<div>').addClass('modal-content');
			if(json['title']){
				content.append('<div class="modal-header"><h5 class="modal-title heading text-center w-100 pt-4" id="'+json['random']+'ModalLabel">' + json['title'] + '</h5><button type="button" class="btn-close position-absolute end-0 top-0 pe-5 pt-5" data-bs-dismiss="modal" aria-label="Close"></button></div>');
			} else {
				content.addClass('position-relative');
				content.append('<button type="button" style="z-index: 1" class="btn-close end-0 position-absolute top-0 p-3" data-bs-dismiss="modal" aria-label="Close"></button>');
			}
			var body = $('<div>').addClass('modal-body');
			if(json['class']){
				if(json['class']['modal-body']){
					body.addClass(json['class']['modal-body']);
				}
				if(json['class']['modal-title']){
					content.find('.modal-title').addClass(json['class']['modal-title']);
				}
				
			}
			
			
			body.html(json['modal']);
			content.append(body);
			dialog.append(content);
			html.append(dialog);
			
			var wrap = $("<div class='offcanvas-wrap'>");
			var backdrop = $("<div class='modal-backdrop fade'>");
			
			wrap.append(html);
			wrap.append(backdrop);
			$("body").append(wrap);
			
			html.click(function(e){
				
				if($(e.target).hasClass('modal')){
					html.addClass('modal-static');
					setTimeout(function(){
						
						html.removeClass('modal-static');
					}, 250);
				}
				
				
			})
			
			$(html).on('show.bs.modal', function (event) {
				if(json['callback'] && json['callback']['show']){
					json.callback.show()
				}
				
				setTimeout(function(){
					backdrop.addClass('show');
				}, 1);
				
			})
			$(html).on('shown.bs.modal', function (event) {
				
			})	
			$(html).on('hide.bs.modal', function (event) {
				backdrop.removeClass('show');
			})
			$(html).on('hidden.bs.modal', function (event) {
				$(wrap).remove();
			})
			$(html).modal('show');
			return html;
		}
	}
}
function mobilemenu(){
	
	var params = {};
	params['title'] = $('header .logo')[0].outerHTML;
	
	var content = $("<div>");
	
	content.append($($("header .left-menu")[0].outerHTML));
	
	content.append($("<div>").addClass('text-end').html($("footer .container-fluid").html()).find('.text-center').removeClass('text-center').addClass('text-end'))
	params['offcanvas'] = content;
	params['width'] = 320;
	
	
	offcanvas.create(params);
	
	
}

var offcanvas = {
	'load': function(url, data = {}){
		send.post(url, data, function(json){
			offcanvas.create(json);
		}, function(json){
			ShowToast('Не могу продолжить - не получил контент окна', 'warning', 'Предупреждение');
		})
	},
	'create': function(json){
		
		
		$("body>.abs-loading").remove();
		if(!json['random']){
			json['random'] = token(32);
		}
		if(!json['offcanvas']){
			ShowToast('Контент не задан','danger', 'Ошибка');
		} else {
			if(json['js']){
				$(json['js']).each(function(i,e){
					if(!$("head script[src='"+e+"']").length && !$("body script[src='"+e+"']").length){
						$('head').append('<script src="'+e+'"></script>');
					}
				})
			}
			var html = $("<div>").addClass('offcanvas offcanvas-end');
			if(json['class'] && json['class']['offcanvas']){
				html.addClass(json['class']['offcanvas'])
			}
			if(json['width']){
				html.css('width', json['width'])
			}
			html.attr({
				'tabindex': '-1',
				'id': 'offcanvas-' + json['random'],
				'data-bs-backdrop': 'true',
				'data-bs-keyboard': 'false',
			})
			
			
			var header = $("<div>").addClass('offcanvas-header');
			if(json['title']){
				header.append('<h5 class="offcanvas-title">' + json['title'] + '</h5>');
			}
			var btn_close = $('<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Закрыть"></button>');
			header.append(btn_close);
			
			html.append(header);
			
			var body = $("<div>").addClass('offcanvas-body');
			if(json['class'] && json['class']['offcanvas-body']){
				body.addClass(json['class']['offcanvas-body']);
			}
			if(json['offcanvas']){
				body.html(json['offcanvas']);
			}
			html.append(body);
			var wrap = $("<div>").addClass('offcanvas-wrap');
			wrap.attr({
				'id': 'offcanvas-wrap-'+json['random'],
				'data-random': json['random'],
			})
			wrap.append(html);
			$("body").append(wrap);
			html.offcanvas('show');
			
			if(html.find('.offcanvas-buttons').length){
				html.find('.offcanvas-buttons').addClass('position-absolute border-1 border-top bottom-0 start-0 w-100 p-3');
			}
			
			html.on('shown.bs.offcanvas', function (event) {
				
				if(html.find('.offcanvas-buttons').length){
					
					body.css({
						'margin-bottom': $('#offcanvas-' + json['random']).find('.offcanvas-buttons').outerHeight() - 1,
					})
				}
			})
			html.on('hide.bs.offcanvas', function (event) {
				if(json['confirm_close'] && !html.hasClass('allow-hide')){
					event.preventDefault();
					ShowConfirm('Действительно закрыть это окно? Все несохранённые данные будут потеряны', function(){
						json['confirm_close'] = null;
						html.offcanvas('hide');
					});
				}
			})
			html.on('hidden.bs.offcanvas', function (event) {
				wrap.remove();
			})	
			
		}
		
	
		
		
	}
	
}

function token(length) {
  var result = '';
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var charactersLength = characters.length;
  
  for (var i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  
  return result;
}
function ShowConfirm(confirmation, func, defunc = false){
	
	var params = {};
	

	params['title'] = 'Подтверждение';
	params['width'] = 360;
	var body = $("<div>");
	
	var text = $("<div>").html(confirmation).addClass('mb-3');
	body.append(text);
	var btn_confirm = $("<button type='button'>").text('Продолжить').addClass('btn btn-success');
	var btn_cancel = $("<button type='button'>").text('Отмена').addClass('btn btn-text');
	
	var flex = $("<div>").addClass('hstack gap-2');
	flex.append(btn_confirm)
	flex.append(btn_cancel)
	
	body.append(flex);
	params['class'] = {};
	params['class']['modal-title'] = 'w-100 pe-4 text-start';
	params['modal'] = body;
	
	
	var mm = modal.create(params);
	
	// 
	
	btn_confirm.click(function(){
		mm.modal('hide');
		func % func();
	})
	btn_cancel.click(function(){
		mm.modal('hide');
		if(defunc){
			defunc % defunc();
		}
	})
}
var send = {
	'post': function(url, data, callback = false, error_callback = false){
		$.ajax({			
			url: url,
			type: 'post',
			data: data,
			dataType: 'json',
			success: function(json) {
				
				if(json['error'] && json['error'].length){
					$(json['error']).each(function(i,e){
						ShowToast(e,'danger','Ошибка');
					})
					
					if(error_callback){
						error_callback(json);
					}
					
				}
				
				if(json['success']){
					if(json['redirect']){
						window.location.href = json['redirect'];
						return;
					}
					if(json['redirect_blank']){
						window.open(json['redirect_blank'], '_blank');
					}
					if(callback){
						callback(json);
					}
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				
				$(".abs-loading").remove();
				ShowToast(xhr.statusText +'<br>Отправьте эту информацию разработчику<br>' + JSON.stringify(data), 'danger', 'Ошибка ' + xhr.status, 30000)
			}
		});
			
		
	}
	
}


function ShowToast(html, background = 'primary', title = 'Уведомление', timeout = 3000){
	
	if(!$(".toast-container").length){
		$("body").append($("<div>").addClass('toast-container top-0 end-0 position-fixed p-3'));
	}
	
	
	var t = $("<div>").addClass('toast').attr({
		'role': 'alert',
		'aria-live': 'assertive',
		'aria-atomic': 'true',
	})
	
	var t_header = $("<div>").addClass('toast-header')
	
	t_header.append('<svg class="bd-placeholder-img rounded me-2" width="20" height="20" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" preserveAspectRatio="xMidYMid slice" focusable="false"><rect width="100%" height="100%" fill="var(--bs-'+background+')"></rect></svg>');
	t_header.append('<strong class="me-auto">'+title+'</strong>');
	t_header.append('<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Закрыть"></button>');
	t.append(t_header)
	
	t.append($('<div>').addClass('toast-body').html(html));
	
	
	$(".toast-container").append(t);
	
	t.toast('show');
	
	
	
	t.on('hidden.bs.toast', function (event) {
		t.remove();
		if($(".toast-container").children('.toast').length == 0){
			$(".toast-container").remove();
		}
	});
	
}


$(document).on("keydown", function (e){
	
	switch(e.key){
		case "Escape":
			var last_elem = $(".offcanvas-wrap:last-child");
			if(last_elem.length){
				if(last_elem.children('.offcanvas').length){
					last_elem.children('.offcanvas').offcanvas('hide');
				} else if(last_elem.children('.modal').length){
					last_elem.children('.modal').modal('hide');
				}
			}
			return;
		break;
	}
	
});

function addLoading(elem){
	$(".loading").remove();
	$elem = $(elem);
	$elem.addClass('position-relative');
	//$elem.attr('data-old-class', $elem.attr('class'));
	$elem.append($('<div class="loading">').append('<div class="spinner-border text-success" role="status"><span class="visually-hidden">Загрузка...</span></div>'));
	
}


function citySelect(el){
	var url = $(el).data('city-url');

	$.get(url, function(html){
		modal.create({
			modal: html,
			title: 'Выберите город',
			width: 400,
		});

		$('.city-item').click(function(e){
			e.preventDefault();
			var cityId = $(this).data('city-id');
			var saveUrl = $('.city-grid').data('save-url');
			send.post(saveUrl, {city_id: cityId, redirect: window.location.href}, function(json){
				if (json.success) {
					window.location.href = json.redirect;
				}
			});
		});
	});
}

function SendRequest(product_id = 0, request_type = ''){

	var params = {};
	var isFittingRoom = request_type == 'fitting_room';
	params['title'] = isFittingRoom ? 'Записаться на примерку' : (product_id ? 'Оставьте заявку' : 'Отправить сообщение');
	params['width'] = 420;
	var form = $("<form>");
	form.append($(isFittingRoom ? '<p>Оставьте номер телефона. Мы получим список выбранных платьев и свяжемся с вами, чтобы назначить время примерки.</p>' : (product_id ? '<p>И мы свяжемся с вами, чтобы назначить время примерки платья</p>' : '<p>Оставьте своё сообщение и мы свяжемся с Вами для консультации</p>')).addClass('text-center'));
	if(isFittingRoom){
		form.append('<input type="hidden" name="request_type" value="fitting_room">');
	}
	if(product_id){
		form.append($("<div>").text($(".product-title").text()).addClass('text-center heading mb-4'))

		form.append('<input type="hidden" name="product_id" value="'+product_id+'">');
	}
	
	form.append('<div class="form-wrap mb-3"><label>Ваше имя</label><input type="text" class="form-control" name="name"></div>');
	form.append('<div class="form-wrap mb-3"><label>Номер телефона</label><input type="tel" class="form-control" name="telephone" required ></div>');
	form.append('<div class="form-wrap mb-3"><label>Комментарий</label><textarea rows="2" class="form-control" name="comment"></textarea></div>');
	form.append('<button type="submit" class="btn btn-dark w-100 d-block">'+(isFittingRoom ? 'ОТПРАВИТЬ ЗАЯВКУ' : 'ЗАПИСАТЬСЯ на ПРИМЕРКУ')+'</button>')
	params['modal'] = form;
	
	
	var mm = modal.create(params);
	
	form.submit(function(e){
		
		e.preventDefault();
		
		send.post('index.php?route=tool/callback', $(this).serialize(), function(json){
			
			form.html('<h3>Заявка отправлена</h3><p>Мы уже получили Вашу заявку и в скором времени свяжемся с Вами!</p>').addClass('text-center');
			form.append($('<button type="button" class="btn btn-dark w-100 d-block mt-3">Продолжить выбор</button>').click(function(){
				mm.modal('hide');
				
			}));
			setTimeout(function(){
				mm.modal('hide');
				
			}, 5000);
		})
		
	})
	
}


var wishlist = {
	
	'add': function(product_id){
		
		send.post('index.php?route=account/wishlist/add', {product_id: product_id}, function(json){
			
			ShowToast(json['success'], 'bg-success');
			
			$(".text-wishlist").text(json['total']);
			
			
			if($(".section-wishlist").length){
				UpdatePage(['#section-wishlist']);
			} else {
				UpdatePage(['[data-product-id="'+product_id+'"]']);
			}
			
		})
	}
	
}



function UpdatePage(elem, data = false, callback = false, url = '', anim = true){
	
	
	if(elem && anim){
		if($.isArray(elem)){
			$(elem).each(function(a,e){
				$(e).attr('data-old-class', $(e).attr('class'));
				$(e).addClass('position-relative').append('<div class="abs-loading"><div class="spinner-border text-primary avatar-xs" role="status"><span class="visually-hidden">Loading...</span></div></div>');
			})
		} else {
			$(elem).addClass('position-relative').append('<div class="abs-loading"><div class="spinner-border text-primary avatar-xs" role="status"><span class="visually-hidden">Loading...</span></div></div>');
			$(elem).attr('data-old-class', $(elem).attr('class'));
		}
		
	}
	
	$.ajax({			
		url: url ? url : $(location).attr('href'),
		type: data ? 'post' : 'get',
		data: data,
		dataType: 'html',
		success: function(html) {
			html = $.trim(html);
			if(elem){
				
			
				if($.isArray(elem)){
					$(elem).each(function(a,e){
						
						$(e).html($(html).find(e).html());
						if(anim){
							$(e).attr('class', $(e).attr('data-old-class'));
						}
						
					})
				} else {
					$(elem).html($(html).find(elem).html());
					if(anim){
						$(elem).attr('class', $(elem).attr('data-old-class'));
					}
				}
				
			}	
			if(callback){
				callback & callback();
			}
			if(url){
				history.pushState(null, null, url);
			}
			
		},
		error: function(xhr, ajaxOptions, thrownError) {
			alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
		}
	});
	
	
	
	
	
	
}
