// Нажатие на кнопку поиска в разделе продаж
function product_search() {
	if($('form[name="product_search_form"] input[name="category_id"]').val()>=0) $('form[name="product_search_form"] input[name="category_id"]').val($('#list_category_id').val());
	else $('form[name="product_search_form"] input[name="category_id"]').val(0);
	$('form[name="product_search_form"]').submit();
}

$('body').off('click', 'form[name="product_search_form"] .submit');
$('body').on('click', 'form[name="product_search_form"] .submit', function(){
	// если поле ввода не пустое то отправляем форму поиска
	if($('form[name="product_search_form"] input[name="product_search"]').val()!='') {
		product_search();
	}
	else {
		if($('.show_products_list').length>0 && $('body').width()>=961) return;
		// отображаем список категорий и товаров если поле пустое
		$('#products_list').addClass('show_list');
		// если содержимое списка пустое, то надо туда загрузить категории
		var html=$('#products_list').html();
		if(html=='') {
			$('#products_list').html(loading_txt);
			$('#products_list').load('/products/list');
		}
	}
});

$(document).mouseup(function(e) {
	if($('.show_products_list').length>0 && $('body').width()>=961) return;
	var div=$('#products_list');
	if(!div.is(e.target) && div.has(e.target).length===0) {
		$('#products_list').removeClass('show_list');
	}
});

// Закрыть каталог категорий и товаров
$('body').off('click', '#products_list_close');
$('body').on('click', '#products_list_close', function(){
	$('#products_list').removeClass('show_list');
});

// Навигация в каталоге товаров
$('body').off('click', '.catalog_a');
$('body').on('click', '.catalog_a', function(){
	var href=$(this).attr('href');
	$('#products_list').html(loading_txt);
	$('#products_list').load(href);
});

// Добавление товара из каталога
$('body').off('click', '.catalog_product');
$('body').on('click', '.catalog_product', function(){
	$(this).removeClass('success_complete');
	$(this).removeClass('error_complete');
	var href=$(this).attr('href');
	//show_window('loading', loading_txt);
	load_ajax(href, false);
});

// Сброс формы поиска товаров
function reset_product_search_form() {
	if($('form[name="add_marking_form"] .marking_input').length>0) {
		$('form[name="add_marking_form"] .marking_input').eq(0).focus();
		return;
	}
	$('form[name="product_search_form"]').trigger("reset");
}

$('body').off('submit', 'form[name="product_search_form"]');
$('body').on('submit', 'form[name="product_search_form"]', function(){
	$('form[name="product_search_form"] input[type="text"]').val('');
	$('form[name="product_search_form"] input[type="text"]').blur();
});

var line_click=1;
$('body').off('click', '.line');
$('body').on('click', '.line', function(){
	$('input[type="radio"]', this).prop('checked', true);
	var line_id=$('input[type="radio"]', this).val();
	var count=$('input[type="radio"]', this).attr('count');
	var add_time=$('input[type="radio"]', this).attr('data-addtime');
	$('.line_control').each(function(){
		var href=$(this).attr('href');
		if(href) {
			href=href.substr(0, href.indexOf('=')+1)+line_id+'&order_display=0';
			$(this).attr('href', href);
		}
	});
	$('.line').removeClass('select_line');
	$(this).addClass('select_line');
	if($('#buttons_lines_div').length>0 && line_click>0) {
		var html=$('#buttons_lines_div').html();
		show_window('line_button_poopup', html);
		$('#line_button_poopup input[name="line_id"]').val(line_id);
		$('#line_button_poopup .line_count').val(count);
		if(add_time=='0') {
			$('#line_button_poopup .add_line_time').hide();
		}
		else {
			$('#line_button_poopup .add_line_time span').html(add_time);
			$('#line_button_poopup .add_line_time').show();
		}
		$('#line_button_poopup .line_count').addClass('line_count_for_line');
	}
	line_click=1;
});


// изменение количества товара
function change_count(count=-1) {
	var radio=$('.line input[type="radio"]:checked');
	var line_id=radio.val();
	if(count<0) count=Number(radio.attr('count'));
	load_ajax('/receipts/change_line?line_id='+line_id+'&count='+count);
	reset_product_search_form();
}

function check_coeff() {
	var elem=$('input[name="coeff"]');
	var coeff=elem.val().toString();
	coeff=coeff.replace(',','.');
	var coeff=coeff.split('.')[1] || '';
	var l=coeff.length;
	if(l>3) {
		coeff=elem.val().toString();
		elem.val(coeff.substr(0,coeff.length-1));
	}
}

$('body').off('change', 'input[name="coeff"]');
$('body').on('change', 'input[name="coeff"]', function() {
	check_coeff();
});

$('body').off('keyup', 'input[name="coeff"]');
$('body').on('keyup', 'input[name="coeff"]', function() {
	check_coeff();
});

// Кнопка плюс (устанавливает введенное кол-во)
var timerId;
$('body').off('click', '.virtual_key_plus');
$('body').on('click', '.virtual_key_plus', function(){
	//if($('.popup').length>0) return;
	if($('input[name="product_search"]').val()!='' && $('input[name="product_search"]').val()!=0) {
		var count=$('input[name="coeff"]').val();
		if(!count) count=1;
		load_ajax('/receipts/add_line?product_id=0&count='+count+'&price='+$('input[name="product_search"]').val());
		reset_product_search_form();
		return;
	}
	var radio=$('.line input[type="radio"]:checked');
	if(radio.length>0) {
		var c=$('input[name="coeff"]').val().replace(',','.');
		if(c>0) {
			var count=c;
		}
		else {
			var count=radio.attr('count');
			//if(Math.floor(count)<count)return;
			var quantity=Number(radio.attr('quantity'));
			if(!quantity) quantity=1;
			count=Number(count)+quantity;
			count=Math.round(parseFloat(count)*1000)/1000;
		}
		//radio.attr('count', count);
		clearTimeout(timerId);
		timerId=setTimeout(change_count, 500, count);
	}
});

// Кнопка минус (уменьшает на 1 штуку)
$('body').off('click', '.virtual_key_minus');
$('body').on('click', '.virtual_key_minus', function(){
	var radio=$('.line input[type="radio"]:checked');
	if(radio.length>0) {
		var count=radio.attr('count');
		//if(Math.floor(count)<count)return;
		var quantity=Number(radio.attr('quantity'));
		if(!quantity) quantity=1;
		count=Number(count)-quantity;
		count=Math.round(parseFloat(count)*1000)/1000;
		if(count<=0)return;
		//radio.attr('count', count);
		clearTimeout(timerId);
		timerId=setTimeout(change_count, 500, count);
	}
});

// Управление фокусом
$('body').off('focus', 'form[name="product_search_form"] input[name="product_search"]');
$('body').on('focus', 'form[name="product_search_form"] input[name="product_search"]', function(){
	$('form[name="product_search_form"] .virtual_keyboard:not(.virtual_keyboard_hide) .virtual_key').attr('for', 'product_search');
	$('form[name="product_search_form"] .virtual_keyboard:not(.virtual_keyboard_hide) .virtual_key_bks').attr('for', 'product_search');
	$(this).attr('tabindex', 1);
	$('form[name="product_search_form"] input[name="coeff"]').attr('tabindex', 2);
});

$('body').off('focus', 'form[name="product_search_form"] input[name="coeff"]');
$('body').on('focus', 'form[name="product_search_form"] input[name="coeff"]', function(){
	$('form[name="product_search_form"] .virtual_keyboard:not(.virtual_keyboard_hide) .virtual_key').attr('for', 'coeff');
	$('form[name="product_search_form"] .virtual_keyboard:not(.virtual_keyboard_hide) .virtual_key_bks').attr('for', 'coeff');
	$(this).attr('tabindex', 1);
	$('form[name="product_search_form"] input[name="product_search"]').attr('tabindex', 2);
});

$('body').off('focus', 'form[name="receipts_search_form"] input[name="id"]');
$('body').on('focus', 'form[name="receipts_search_form"] input[name="id"]', function(){
	$('form[name="receipts_search_form"] .virtual_key').attr('for', 'receipt_id');
	$('form[name="receipts_search_form"] .virtual_key_bks').attr('for', 'receipt_id');
});

$('body').off('focus', 'form[name="receipts_search_form"] input[name="fd"]');
$('body').on('focus', 'form[name="receipts_search_form"] input[name="fd"]', function(){
	$('form[name="receipts_search_form"] .virtual_key').attr('for', 'receipt_fd');
	$('form[name="receipts_search_form"] .virtual_key_bks').attr('for', 'receipt_fd');
});

$('body').off('focus', 'form[name="receipts_search_form"] input[name="barcode"]');
$('body').on('focus', 'form[name="receipts_search_form"] input[name="barcode"]', function(){
	$('form[name="receipts_search_form"] .virtual_key').attr('for', 'barcode');
	$('form[name="receipts_search_form"] .virtual_key_bks').attr('for', 'barcode');
});

$('body').off('focus', 'form[name="receipts_search_form"] input[name="changes"]');
$('body').on('focus', 'form[name="receipts_search_form"] input[name="changes"]', function(){
	$('form[name="receipts_search_form"] .virtual_key').attr('for', 'changes_id');
	$('form[name="receipts_search_form"] .virtual_key_bks').attr('for', 'changes_id');
});

$('body').off('click', 'form[name="product_search_form"] .virtual_key_delete');
$('body').on('click', 'form[name="product_search_form"] .virtual_key_delete', function(){
	if($(this).closest('.popup_area').length>0)return;
	reset_product_search_form();
});

$('body').on('click', '.close', function(){
	reset_product_search_form();
});

$('body').off('click', '#select_epay .close_button');
$('body').on('click', '#select_epay .close_button', function(){
	$('#select_epay').hide();
});

$('body').off('click', '#select_epay label');
$('body').on('click', '#select_epay label', function(){
	$('.epay_title').html($(this).attr('data-title'));
	$('.receipt_pay_form .epay').val($('#'+$(this).attr('for')).val());
	$('#select_epay').hide();
});

var test_tranzaction=false;
$('body').off('click', '.tabs .tab');
$('body').on('click', '.tabs .tab', function(){
	$('.tabs .tab').removeClass('tab_select');
	$('.tab_page_select').removeClass('tab_page_select');
	$(this).addClass('tab_select');
	var p=$(this).attr('for');
	$(p).addClass('tab_page_select');
	var cash=$(this).attr('cash');
	var el=$('input.client_sum', p).eq(0);
	if(cash==1) {
		if($('body').width()>=961) {
			el.focus();
			el.select();
			el.blur();
		}
	}
	else {
		$('#pay_change').hide();
	}

	if($(this).attr('select-epay')=='1' && $('#select_epay label').length>0) {
		$('#select_epay').show();
		$('.tab_page_select input.client_sum').eq(0).blur();
		if($('#select_epay label').length==1)  {
			$('#select_epay label').trigger('click');
		}
	}
	else {
		$('#select_epay').hide();
	}

	$('label[for="fr_print_0"]').css('opacity', 1);
	$('input[name="fr_print_0"]').prop('disabled', false);
	if($('.tab_page_select .client_sum').length==1 && $(this).attr('cash')=='1') {
		$('#fr_no_0').prop('checked', test_tranzaction);
		if(test_tranzaction===true) {
			var hold=1;
		}
		else {
			var hold=0
		}
		$('.hold').val(hold);
		$('.nofr').val(hold);
		$('label[for="fr_no_0"]').css('opacity', 1);
		$('input[name="fr_no_0"]').prop('disabled', false);
		$('label[for="fr_bt_0"]').css('opacity', 0);
		$('label[for="fr_bt_0"]').css('z-index', -10);
		$('input[name="fr_bt_0"]').prop('disabled', true);
		test_tranzaction=false;
	}
	else {
		if(test_tranzaction===false) {
			test_tranzaction=$('#fr_no_0').prop('checked');
		}
		$('#fr_no_0').prop('checked', false);
		$('.hold').val(0);
		$('.nofr').val(0);
		$('label[for="fr_no_0"]').css('opacity', 0);
		$('input[name="fr_no_0"]').prop('disabled', true);
		$('label[for="fr_bt_0"]').css('opacity', 1);
		$('label[for="fr_bt_0"]').css('z-index', 10);
		$('input[name="fr_bt_0"]').prop('disabled', false);
	}

	if($(this).attr("nobt")=="1") {
		$('label[for="fr_bt_0"]').css('opacity', 0);
		$('label[for="fr_bt_0"]').css('z-index', -10);
		$('input[name="fr_bt_0"]').prop('disabled', true);

	}
	if($(this).attr("hold")=="1") {
		$('label[for="fr_no_0"]').css('opacity', 0);
		$('input[name="fr_no_0"]').prop('disabled', true);
	}
	if($(this).attr("rececipt_sales")=="1") {
		$('label[for="sales_receipts"]').css('opacity', 0);
		$('input[name="sales_receipts"]').prop('disabled', true);
	}
	else {
		$('label[for="sales_receipts"]').css('opacity', 1);
		$('input[name="sales_receipts"]').prop('disabled', false);
	}

	if($(this).attr("nobt")=="1" && $(this).attr("hold")=="1" && $(this).attr("rececipt_sales")=="1") {
		$('label[for="fr_print_0"]').css('opacity', 0);
		$('input[name="fr_print_0"]').prop('disabled', true);
	}

	pay_change(el);
});

// считам сдачу
function pay_change(el) {
	var form=$(el).closest('form');
	var sum=0;
	var mix=0;
	$(form).find('input.client_sum').each(function(){
		sum+=Number($(this).val());
		if($(this).hasClass('mixed_pay')) {
			mix=1;
		}
	});
	sum=Math.round(sum*100)/100;
	var r=sum-receipt_sum;
	if($('input[name="type"]', form).val()==1) {
		$.ajax({
        	url: '/receipts/pay?sum='+receipt_sum+'&pay='+sum,
        	timeout: 3000
 		});
 	}
	$('#mixed_pay_add').hide();
	if(r>=0 && mix==0) {
		if(r>0) {
			$('#pay_change').show();
			$('#pay_change big').html(r.toFixed(2));
		}
		else {
			$('#pay_change').hide();
		}
		if(r<5000) {
			$('#receipt_pay_ok').attr('disabled', false);
		}
		else {
			$('#receipt_pay_ok').attr('disabled', true);
		}
	}
	else {
		$('#pay_change').hide();
		$('#receipt_pay_ok').attr('disabled', true);
		if(mix==1) {
			$('#mixed_pay_add big').html((-r).toFixed(2));
			$('#mixed_pay_add').show();
			if(r==0) {
				$('#receipt_pay_ok').attr('disabled', false);
			}
		}
	}
}

$('body').off('click', '#mixed_pay_add');
$('body').on('click', '#mixed_pay_add', function(){
	var input;
	var val=$('big', this).html();
	$('.mixed_pay').each(function(){
		if(!$(this).val() && input==undefined) {
			input=$(this);
		}
	});
	if(input) {
		input.val(val);
		pay_change(input);
	}
});

$('body').off('change, keyup', '.receipt_pay_form input[type="text"], .cashout_sum, .cashin_sum');
$('body').on('change, keyup', '.receipt_pay_form input[type="text"], .cashout_sum, .cashin_sum', function(e){
	if($('#select_epay').is(':visible')) return;
	var val=$(this).val();
	val=val.replace(/[,]/gim,'.');
	val=val.replace(/[^.0-9]/gim,'');
	$(this).val(val);
	pay_change(this);
});

$('body').off('click', '.receipt_pay_form .virtual_keyboard input[type="button"]');
$('body').on('click', '.receipt_pay_form .virtual_keyboard input[type="button"]', function(){
	var el=$('.'+$(this).attr('for'));
	pay_change(el);
});

$('body').off('click', '.receipt_pay_form .virtual_keyboard button');
$('body').on('click', '.receipt_pay_form .virtual_keyboard button', function(){
	var el=$('.'+$(this).attr('for'));
	pay_change(el);
});

// Считаем сумму возврта
var sum_return=0;
function return_sum() {
	var count=0;
	var sum=0;
	$('.line_return').each(function(){
		count+=Number($('.count', this).val());
		sum+=Number($('.vprice', this).val()*$('.count', this).val());
	});
	$('#return_count').html(count.toFixed(3));
	$('.return_sum').html(sum.toFixed(2));
	sum_return=Math.round(sum*100)/100;
	if($('.mixed_pay').length==1) {
		$('.mixed_pay').val(sum.toFixed(2));
	}
}

// Окно ввода марки при возврате маркированного товара
function return_mark(el, count) {
	var line_id=el.val();
	var mark_code=el.attr('mark_code');
	/*if(el.attr('pg')=='draftbeer') {
		mark_code=el.attr('mark_code');
	}*/
	var html='<h1>Введите код маркированного товара</h1>';
	html+='<h2>'+$('#line_'+line_id+' .product_title').html()+'</h2>';
	html+='<p align="center"><input type="text" name="mark_'+line_id+'" class="mark_return_input" value="'+mark_code+'" ></p>';
	html+='<p align="center"><input type="button" data-line="'+line_id+'" data-count="'+count+'" class="add_return_mark" value="Сохранить"></p>';
	show_window('add_mark_'+line_id, html);
	if(mark_code!='') {
		$('.add_return_mark').trigger('click');
	}
}

$('body').off('keyup, keypress', '.mark_return_input');
$('body').on('keyup, keypress', '.mark_return_input', function(e){
	if(e.which==13) {
		$('.add_return_mark').trigger('click');
	}
});

// Добавляем товар на возврат с указание марки
$('body').off('click', '.add_return_mark');
$('body').on('click', '.add_return_mark', function() {
	var line_id=$(this).attr('data-line');
	var count=$(this).attr('data-count');
	var el=$('#line_'+line_id+' input[type="radio"]');
	var mark=$('input[name="mark_'+line_id+'"]').val();
	if(mark!='') {
		return_line(el, count, mark);
		close_window(this);
	}
});

// Возврат
function return_line(el, count, mark=null) {
	var line_id=el.val();
	if(el.attr('pg')=='draftbeer' || el.attr('unit_okei')!='796') {
		mark=el.attr('mark_code');
	}
	if(el.attr('mark')==1 && !mark) {
		return_mark(el, count);
		return;
	}
	count*=1;
	var tr='<td><span class="small product_title">'+$('#line_'+line_id+' .product_title').html()+'</span><div class="order_show small"><div class="small" align="right">'+el.attr('vprice')+' X '+count.toFixed(3)+' = '+(el.attr('vprice')*count).toFixed(2)+' <i class="fas fa-times remove_return" for="#line_return_'+line_id+'"></i></div></div>';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][id]" value="'+el.attr('product_id')+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][line_id]" value="'+line_id+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][title]" value="'+$('#line_'+line_id+' .product_title').html()+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][product_title]" value="'+$('#line_'+line_id+' .product_title').html()+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][price]" value="'+el.attr('price')+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][vat]" value="'+el.attr('vat')+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][vat_type]" value="'+el.attr('vat_type')+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][loyalty]" value="'+el.attr('loyalty')+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][max_discount]" value="'+el.attr('max_discount')+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][units_fr]" value="'+el.attr('units_fr')+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][unit_okei]" value="'+el.attr('unit_okei')+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][pg]" value="'+el.attr('pg')+'">';
	if(mark) {
		tr+='<input type="hidden" name="receiptlines['+line_id+'][mark]" value="'+mark+'">';
	}
	tr+='<input type="hidden" name="receiptlines['+line_id+'][egais]" value="'+el.attr('egais')+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][barcode]" value="'+el.attr('barcode')+'">';
	tr+='<input type="hidden" class="count" name="receiptlines['+line_id+'][count]" value="'+count+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][discount]" value="'+el.attr('discount')+'">';
	tr+='<input type="hidden" name="receiptlines['+line_id+'][bonus_pay]" value="'+el.attr('bonus-pay')+'">';
	tr+='<input type="hidden" class="vprice" value="'+el.attr('vprice')+'">';
	tr+='</td>';
	tr+='<td width="100" align="center">'+el.attr('vprice')+'</td>';
	tr+='<td width="100" align="center">'+count.toFixed(3)+'</td>';
	tr+='<td width="100" align="center">'+(el.attr('vprice')*count).toFixed(2)+'</td>';
	tr+='<td width="25" align="center"><button type="button" class="line_control remove_return" for="#line_return_'+line_id+'" data-line-id="'+line_id+'"><i class="fas fa-times"></i></button></td>';
	if($('#line_return_'+line_id).length>0) {
		$('#line_return_'+line_id).html(tr);
	}
	else {
		$('#return_add').before('<tr class="line_return" id="line_return_'+line_id+'">'+tr+'</tr>');
	}
	$('.receiptlines_lost_count_'+line_id).val(el.attr('count')-count);

	return_sum();
}

$('body').off('click', '.chpok_barcode');
$('body').on('click', '.chpok_barcode', function(){
	if(show_virtual_keyboard==0) return;
	$('.virtual_keyboard_chpok').show();
});

$('body').off('click', '.marking_input');
$('body').on('click', '.marking_input', function(){
	if(show_virtual_keyboard==0) return;
	$('.virtual_keyboard_marking_input').show();
});

$('body').off('click', '#ticket_description');
$('body').on('click', '#ticket_description', function(){
	if(show_virtual_keyboard==0) return;
	$('.virtual_keyboard_ticket_description').show();
});

$('body').off('click', '.virtual_keyboard_ticket_description *[type="button"]');
$('body').on('click', '.virtual_keyboard_ticket_description *[type="button"]', function() {
	$('#ticket_description').trigger('change');
});

$('body').off('click', '.return_count_input');
$('body').on('click', '.return_count_input', function(){
	if(show_virtual_keyboard==0) return;
	$('.virtual_keyboard_return_count_input').show();
});

/*$('body').off('keydown', '.discount_input');
$('body').on('keydown', '.discount_input', function(e){
	if(add_discount==0 || $('.popup').length>0) {
		e.preventDefault();
		return;
	}
	$(this).trigger('change');
});

$('body').off('keyup', '.discount_input');
$('body').on('keyup', '.discount_input', function(e){
	if(add_discount==0 || $('.popup').length>0) {
		e.preventDefault();
		return;
	}
	$(this).trigger('change');
});*/

$('body').off('click', '.discount_input');
$('body').on('click', '.discount_input', function(){
	if($('.discount_no_input').length>0) return;
	if(!$('.virtual_keyboard_discount_input').is(":visible")) {
		$(this).select();
	}
	if(show_virtual_keyboard==0 && show_discount_keyboard==0) return;
	if(!$(this).is(':focus')) return;
	$('.virtual_keyboard_discount_input').show();
	var h=$('.virtual_keyboard_discount_input').height();
	if($('.virtual_keyboard_discount_input_cafe').length>0) {
		h+=30;
	}
	else {
		h+=88;
	}
	var top=$('.virtual_keyboard_discount_input').position().top;
	if(top-h<0) {
		h-=(h-top);
	}

	$('.virtual_keyboard_discount_input_cafe').css('margin-top', -h);
});

$('body').off('click', '.client_0');
$('body').on('click', '.client_0', function(){
	if(show_virtual_keyboard==0) return;
	$('.virtual_keyboard_client_0').show();
});

$('body').off('click', '.form_product_search');
$('body').on('click', '.form_product_search', function(){
	if($('input[for="form_product_search"]').length>0) {
		$('input[for="form_product_search"]').eq(0).closest('.virtual_keyboard_hide').show();
	}
	else {
		if($('button[for="form_product_search"]').length>0) {
			$('button[for="form_product_search"]').eq(0).closest('.virtual_keyboard_hide').show();
		}
	}
});

$('body').off('click', '.form_product_search_page');
$('body').on('click', '.form_product_search_page', function(){
	if($('input[for="form_product_search_page"]').length>0) {
		$('input[for="form_product_search_page"]').eq(0).closest('.virtual_keyboard_hide').show();
	}
	else {
		if($('button[for="form_product_search_page"]').length>0) {
			$('button[for="form_product_search_page"]').eq(0).closest('.virtual_keyboard_hide').show();
		}
	}
});

if($('.virtual_keyboard_hide').length>0 && typeof hide_virtual_keyboard_function=='undefined') {
	var hide_virtual_keyboard_function=$(document).mouseup(function(e) {
		var div=$('.virtual_keyboard_hide');
		if(!div.is(e.target) && div.has(e.target).length===0 && !$('#line_button_poopup .line_count_for_line').is(e.target) && !$('.with_full_keyboard').is(e.target) && !$('.return_count_input').is(e.target) && !$('.description').is(e.target) && !$('.client_0').is(e.target) && !$('.discount_input').is(e.target) && !$('#ticket_description').is(e.target) && !$('.chpok_barcode').is(e.target) && !$('.marking_input').is(e.target)) {
			div.hide();
		}
	});
}

$('body').off('click', '.virtual_keyboard_hide .virtual_key_ok');
$('body').on('click', '.virtual_keyboard_hide .virtual_key_ok', function() {
	$('.virtual_keyboard_hide').hide();
});

$('body').off('click', '.return_ok');
$('body').on('click', '.return_ok', function(){
	var radio=$('.line input[type="radio"]:checked');
	var count=Number($('.return_count_input').val());
	$('.return_count_input').val('');
	if(count>0) {
		if(count>Number(radio.attr('count'))) {
			false_alarm();
			show_window('error', '<p class="false">Нет такого количества</p>');
			return;
		}

		return_line(radio, count);
	}
});

$('body').off('click', 'input[name="return_1"]');
$('body').on('click', 'input[name="return_1"]', function() {
	var radio=$('.line input[type="radio"]:checked');
	var count=1;
	var line_id=radio.val();
	if($('#line_return_'+line_id).length>0) {
		count=Number($('#line_return_'+line_id+' .count').val())+Number(count);
	}

	if(count>Number(radio.attr('count'))) {
		false_alarm();
		show_window('error', '<p class="false">Нет такого количества</p>');
		return;
	}

	return_line(radio, count);
});

$('body').off('click', 'input[name="return_str"]');
$('body').on('click', 'input[name="return_str"]', function() {
	var radio=$('.line input[type="radio"]:checked');
	if(Number(radio.attr('count')) > 0) return_line(radio, Number(radio.attr('count')));
});

$('body').off('click', 'input[name="return_all"]');
$('body').on('click', 'input[name="return_all"]', function() {
	$('.line').each(function(){
		var radio=$('input[type="radio"]', this);
		if(radio.attr('count')>0) return_line(radio, Number(radio.attr('count')));
	});
});

// Удаляем строку возврата
$('body').off('click', '.remove_return');
$('body').on('click', '.remove_return', function(){
	var el=$(this).attr('for');
	var line_id=$(this).attr('data-line-id');
	$('.receiptlines_lost_count_'+line_id).val($('#line_'+line_id+' input[type="radio"]').attr('count'));
	$(el).remove();
	return_sum();
});

$('body').off('click', 'input[name="save_return"]');
$('body').on('click', 'input[name="save_return"]', function(){
	return_change();
	$('#return_paymentmethods').show();
	if($('.mixed_pay').length>1) {
		$('.mixed_pay').eq(0).focus();
	}
});

$('body').off('click', '#return_paymentmethods .close_button');
$('body').on('click', '#return_paymentmethods .close_button', function(){
	$('#return_paymentmethods').hide();
});

$('body').off('click', '#line_button_poopup .line_control');
$('body').on('click', '#line_button_poopup .line_control', function(){
	close_window(this);
});

$('body').off('click', '#line_button_poopup');
$('body').on('click', '#line_button_poopup', function(e){
	if($(e.target).closest('.popup_area').length>0) return;
	close_window(this);
});


// Считаем введеную сумму возврата
function return_change() {
	var sum=0
	var ok=true;
	var sum0=Number($('input[name="sum0"]').val());
	$('.mixed_pay').each(function(){
		var val=Number($(this).val());
		var max=Number($(this).attr('max'));
		var pid=$(this).attr('pid');
		if(val>max) {
			$('.error_'+pid).addClass('false');
			ok=false;
		}
		else {
			$('.error_'+pid).removeClass('false');
		}
		sum+=Number(val);
		sum=Math.round(sum*100)/100;
		$('#return_add_pay').html((sum_return-sum).toFixed(2));
	});
	if(ok) {
		if(sum==sum_return && (sum_return>0 || (sum0==sum && $('.line_return').length>0))) {
			$('input[type="submit"]').attr('disabled', false);
		}
		else {
			$('input[type="submit"]').attr('disabled', true);
		}
	}
}

$('body').off('change', '#return_paymentmethods input[type="text"]');
$('body').on('change', '#return_paymentmethods input[type="text"]', function(e){
	var val=$(this).val();
	val=val.replace(/[^.0-9]/gim,'');
	$(this).val(val);
	return_change();
});

$('body').off('keyup', '#return_paymentmethods input[type="text"]');
$('body').on('keyup', '#return_paymentmethods input[type="text"]', function(e){
	var val=$(this).val();
	val=val.replace(/[^.0-9]/gim,'');
	$(this).val(val);
	return_change();
});

$('body').off('click', '#return_paymentmethods .virtual_keyboard input[type="button"]');
$('body').on('click', '#return_paymentmethods .virtual_keyboard input[type="button"]', function(){
	return_change();
});

$('body').off('click', '#return_paymentmethods .virtual_keyboard button');
$('body').on('click', '#return_paymentmethods .virtual_keyboard button', function(){
	return_change();
});

function return_reset() {
	$('#return_paymentmethods').hide();
	$('.line_return').remove();
	$('.mixed_pay').val('');
	return_sum();
}

// возвращает cookie с именем name, если есть, если нет, то undefined
function getCookie(name) {
	var matches = document.cookie.match(new RegExp(
		"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
	));
	return matches ? decodeURIComponent(matches[1]) : undefined;
}

// Скидка
var savediscount=null;

function save_discount(discount) {
	if(savediscount!==null) {
		savediscount.abort();
	}
	if($('.discount_no_input').length>0) {
		$('.discount_no_input').val(0);
		return;
	}
	savediscount=$.ajax({
        url: '/receipts/discount?discount='+discount,
        dataType: "html",
        success: function(response) {
       		var isJson = true;
        	var res;
        	try {
    			res=JSON.parse(response);
    			if(res.success) {
    				sum_with_discount(discount);
    			}
    			else {
    				if(res.save_discount!=undefined) {
    					discount=res.save_discount;
    				}
    				else {
    					discount=0;
    				}
    				discount_error(discount);
    				ajax_response(response);
    			}
			} catch(e) {
    			isJson = false;
			}
       		if(!isJson) {
       			show_window(null, response);
       		}
    	},
    	error: function(response) {
    		false_alarm();
    		if(response.abort) return;
    		show_window(null, response.statusText);
    		discount_error();
    	},
    	timeout: 65000
 	});
}

function discount_error(discount=0) {
	$('input[name="discount"]').val(discount);
    save_discount(discount);
}

function sum_with_discount(discount) {
	$('.receiptlines').load(' .receiptlines .reload', function(){
		$('.button_total .receipt_sum').html($('.receiptlines .receipt_sum').html());
    	receiptlines_div_resize();
    });
}

$('body').off('click', '.select_discount');
$('body').on('click', '.select_discount', function(){
	$('input[name="discount"]').val($(this).attr('data-discount'));
	$('input[name="discount"]').trigger('change');
	$('.virtual_keyboard_discount_input').hide();
});

var discount_timer;
$('body').off('change', 'input[name="discount"]');
$('body').on('change', 'input[name="discount"]', function(){
	var discount=$(this).val();
	if(discount=='' || discount=='-' || $('.discount_no_input').length>0) {
		discount=0;
	}
	/*if(discount<0 || discount>100) {
		show_window('error', '<p class="false">Скидка должна быть в промежутке от 0 до 100</p>');
		discount_error();
		return;
	}*/
	clearTimeout(discount_timer);
	discount_timer=setTimeout(save_discount, 500, discount);
});

$('body').off('change', 'input[name="discount_line"]');
$('body').on('change', 'input[name="discount_line"]', function(){
	var d=$(this).val();
	d=d.replace(',','.');
	var max_discount=Number($(this).attr('max'));
	if(d=='.') {
		d='0.';
		$(this).val(d);
	}
	if(d=='-') {
		d=0
	}
	d=Number(d);
	if(d>max_discount) {
		d=max_discount;
		$(this).val(d);
	}
	$('form[name="receipts_change_price_form"] input[type="submit"]').attr("disabled", false);
	var price0=$('input[name="price0"]').val();
	var price=price0;
	price-=price*d/100;
	$('input[name="price"]').val(price.toFixed(2));
	var data_max_discount=Number($(this).attr('data-max'));
	if(data_max_discount<max_discount && price<price0/100*data_max_discount) {
		$('#alert_max_discount').show();
	}
	else {
		$('#alert_max_discount').hide();
	}
});

$('body').off('change', 'input[name="writeoff_bonus"]');
$('body').on('change', 'input[name="writeoff_bonus"]', function(){
	var d=$(this).val();
	d=d.replace(',','.');
	var max_bonus=Number($(this).attr('max'));
	if(d=='.') {
		d='0.';
		$(this).val(d);
	}
	if(d=='-') {
		$(this).val(0);
		d=0
	}
	d=Number(d);

	d=Number(d);
	if(d>max_bonus) {
		d=max_bonus;
		$(this).val(d);
	}
	$('form[name="receipts_change_price_form"] input[type="submit"]').attr("disabled", false);
	var price0=$('input[name="price0"]').val();
	var price=price0;
	price-=d;
	$('input[name="price"]').val(price.toFixed(2));
	var data_max_bonus=Number($(this).attr('data-max'));
	if(data_max_bonus<max_bonus && price<price0-data_max_bonus) {
		$('#alert_max_discount').show();
	}
	else {
		$('#alert_max_discount').hide();
	}
});

$('body').off('change', 'form[name="receipts_change_price_form"] input[name="price"]');
$('body').on('change', 'form[name="receipts_change_price_form"] input[name="price"]', function(){
	var d=Number($(this).val());
	var min_price=Number($(this).attr('min'));
	if(d=='.') {
		d='0.';
		$(this).val(d);
	}
	if(d<min_price) {
		d=min_price;
		$('form[name="receipts_change_price_form"] [type="submit"]').attr('disabled', 'disabled');
	}
	else {
		$('form[name="receipts_change_price_form"] [type="submit"]').removeAttr('disabled');
	}
});

$('body').off('change', '.client_0');
$('body').on('change', '.client_0', function(){
	$('.client').val($(this).val());
});

$('body').off('change', '.executor_0');
$('body').on('change', '.executor_0', function(){
	$('.executor').val($(this).val());
});

$('body').off('change', '.psr_0');
$('body').on('change', '.psr_0', function(){
	$('.psr').val($(this).val());
});


$('body').off('click', '.virtual_keyboard input');
$('body').on('click', '.virtual_keyboard input', function(){
	$('.'+$(this).attr('for')).trigger("change");
});

$('body').off('click', '.virtual_keyboard button');
$('body').on('click', '.virtual_keyboard button', function(){
	$('.'+$(this).attr('for')).trigger("change");
});

$(document).off('keydown', 'body');
$(document).on('keydown', 'body', function(e){
	if($('#search_products_table').length>0) {
		if($('.popup').length>1) return;
		
		if(e.which == 40) { // Нажатие Вниз, перемещение по товарам
			e.preventDefault();
			var l=$('.isfocus').next('.product_line');
			if(l.length==0) {
				l=$('#search_products_table .product_line').eq(0);
			}
			$('#search_products_table .product_line').removeClass('isfocus');
			l.addClass('isfocus');
			$('input[type="button"]', l).focus();
			return;
		}

		if(e.which == 38) { // Нажатие Вверх, перемещение по товарам
			e.preventDefault();
			var l=$('.isfocus').prev('.product_line');
			if(l.length==0) {
				l=$('#search_products_table .product_line').eq($('#search_products_table .product_line').length-1);
			}
			$('#search_products_table .product_line').removeClass('isfocus');
			l.addClass('isfocus');
			$('input[type="button"]', l).focus();
			return;
		}

	}

	if($('form[name="receipts_chpok_form"]').length>0 && $('form[name="receipts_chpok_end_form"]').length==0) {
		$('.chpok_barcode').focus();
	}

	if($('.marking_input').length>0 && $('.marking_input:focus').length==0) {
		$('.marking_input').focus();
	}

	if($('.receipt_pay_form').length>0) {
		if(e.which == 40) { // Нажатие Вниз, перемещение по способам оплаты
			e.preventDefault();
			var m=$('.tab_select').next('.tab');
			if(m.length==0) {
				m=$('.tab').eq(0);
			}
			m.trigger('click');
			return;
		}

		if(e.which == 38) { // Нажатие Вверх, перемещение по способам оплаты
			e.preventDefault();
			var m=$('.tab_select').prev('.tab');
			if(m.length==0) {
				m=$('.tab').eq($('.tab').length-1);
			}
			m.trigger('click');
			return;
		}

		if(e.which == 37) { // Нажатие Влево, выбор способа электронной оплаты
			e.preventDefault();
			if(!$('#select_epay').is(':visible')) return;
			var m=$('#select_epay input[type="radio"]:checked').closest('.epay_span').prev('.epay_span');
			if(m.length==0) {
				m=$('#select_epay .epay_span').eq($('#select_epay .epay_span').length-1);
			}
			$('input[type="radio"]', m).prop('checked', true);
		}

		if(e.which == 39) { // Нажатие Вправо, выбор способа электронной оплаты
			e.preventDefault();
			if(!$('#select_epay').is(':visible')) return;
			var m=$('#select_epay input[type="radio"]:checked').closest('.epay_span').next('.epay_span');
			if(m.length==0) {
				m=$('#select_epay .epay_span').eq(0);
			}
			$('input[type="radio"]', m).prop('checked', true);
		}

		if(e.which==13) { // Нажатие Enter
			e.preventDefault();
			if($('#select_epay').is(':visible')) {
				var id=$('#select_epay input[type="radio"]:checked').attr('id');
				$('label[for="'+id+'"]').trigger('click');
				return;
			}
			if($('.popup').length>1) return;
			$('#receipt_pay_ok').trigger('click');
			return;
		}

		if($('#select_epay').is(':visible')) return;
		if($('.popup').length>1) return;

		if(e.which==111) { // Нажатие /
			e.preventDefault();
			$('label[for="fr_print_0"]').trigger('click');
			return;
		}

		if(e.which==9) { // Нажатие Tab
			e.preventDefault();
			if($('.tab_page_select input[type="text"]:focus').length==0) {
				$('.tab_page_select input[type="text"]').eq(0).focus();
			}
			else {
				var s=false;
				$('.tab_page_select input[type="text"]').each(function(){
					if($(this).is(':focus')) s=true;
					else {
						if(s==true) {
							$(this).focus();
							s=false;
							return;
						}
					}
				});
				if(s==true) {
					$('.tab_page_select input[type="text"]').eq(0).focus();
				}
			}
		}

		if($('.tab_page_select input[type="text"]:focus').length==0 && $('.client_0:focus').length==0) {
			$('.tab_page_select input[type="text"]').eq(0).focus();
		}
	}

	if($('.mark_return_input').length>0 && !$('.mark_return_input').is(':focus')) {
		$('.mark_return_input').focus();
	}

	if($('.popup').length>0) {
		var popup=$(document.activeElement).closest('.popup');
		var popups=$('.popup');
		if($(popup[0]).attr('id')!=$(popups.eq(popups.length-1)[0]).attr('id')) error_click_alarm();
	}

	if($('form[name="product_search_form"] input[name="product_search"]').length>0) {
		if($('.popup').length>0) return;
		if(e.which == 13) { // Нажатие Enter
			$('.virtual_keyboard_hide').hide();
			if($('form[name="product_search_form"] input[name="product_search"]').val()=='') {
				$('form[name="product_search_form"] .virtual_key_total').trigger('click');
			}
			else {
				product_search();
			}
			return;
		};

		if(e.which==45) {
			e.preventDefault();
			var radio=$('.line input[type="radio"]:checked');
			var line_id=radio.val();
			load_window('/receipts/change_count?line_id='+line_id);
		}

		if(e.which==107 && !isNaN($('input[name="product_search"]').val())) { // Нажатие Плюс, добавление 1 штуки
			e.preventDefault();
			$('.virtual_key_plus').trigger('click');
			return;
		}

		if($('input[name="product_search"]').is(":focus") && $('input[name="product_search"]').val()!='') {
			return;
		}

		if(e.which == 106) { // Нажатие *, переключение на поле ввода кол-ва товаров
			e.preventDefault();
			$('form[name="product_search_form"] input[name="coeff"]').focus();
			return;
		}

		if(e.which == 111) { // Нажатие Деление, переключение на поле ввода скидки
			e.preventDefault();
			$('.discount_input').focus();
			return;
		}

		if(e.which == 40) { // Нажатие Вниз, перемещение по товарным позициям
			e.preventDefault();
			if($('.line').length>1) {
				var line=$('.select_line').next('.line');
				if(line.length==0) {
					line=$('.line').eq(0);
				}
				line_click=0;
				line.addClass()
				line.trigger('click');
				$('.receiptlines_div').scrollTop(line.position().top);

			}
			return;
		}

		if(e.which == 38) { // Нажатие Вверх, перемещение по товарным позициям
			e.preventDefault();
			if($('.line').length>1) {
				var line=$('.select_line').prev('.line');
				if(line.length==0) {
					line=$('.line').eq($('.line').length-1);
				}
				line_click=0;
				line.trigger('click');
				$('.receiptlines_div').scrollTop(line.position().top);
			}
			return;
		}

		if(e.which == 39) { // Нажатие Вправо, выбор способа электронной оплаты
			line_click=1;
			$('.select_line').trigger('click');
			return;
		}

		if(e.which==109) { // Нажатие Минус, удаление 1 штуки
			e.preventDefault();
			$('.virtual_key_minus').trigger('click');
			return;
		}

		if(e.which==46) { // Нажатие Delete, удаление товарной позиции
			e.preventDefault();
			$('.line_control_delete').trigger('click');
		}

		// Потому что больше кнопок нет
		/*if(e.which==33) { // Нажатие Page Up, заказ из интернет магазина
			e.preventDefault();
			$('button[name="online_order"]').trigger('click');
			return;
		}*/

		if(e.which==36) { // Нажатие Home, быстрые товары
			e.preventDefault();
			$('input[name="fast_product"]').trigger('click');
			return;
		}

		if(e.which==33) { // Нажатие Page Up, Узнать остатки
			e.preventDefault();
			$('input[name="currentstock"]').trigger('click');
			return;
		}

		if(e.which==35) { // Нажатие End, редактировать товарную позицию
			e.preventDefault();
			$('.line_control_change').trigger('click');
			return;
		}

		if(e.which==34) { // Нажатие Page Down, узнать остатки товарной позиции
			e.preventDefault();
			$('.line_control_currentstock').trigger('click');
			return;
		}

		if(!$('input[type="text"]').is(':focus') && !$('input[type="number"]').is(':focus') && !$('textarea').is(':focus')) {
			$('form[name="product_search_form"] input[name="product_search"]').focus();
		}
	}
});

// Показ клавиатуры для поиска товаров
$('body').off('click', '.virtual_key_key');
$('body').on('click', '.virtual_key_key', function(){
	if(show_virtual_keyboard==0) return;
	$('.virtual_keyboard_product_search').show();
});

$('body').off('click', '#right_td_with_product_menu .coeff');
$('body').on('click', '#right_td_with_product_menu .coeff', function(){
	$('.keyboard_menu_with_product').show();
});

$('body').off('click', '.free_title');
$('body').on('click', '.free_title', function(){
	if(show_virtual_keyboard==0) return;
	$('.virtual_keyboard_free_title').show();
});

$('body').off('focus', 'form[name="receipts_change_price_form"] input[type="text"]');
$('body').on('focus', 'form[name="receipts_change_price_form"] input[type="text"]', function(){
	var c=$(this).attr('class');
	var f=$('form[name="receipts_change_price_form"] .virtual_keyboard input[type="button"]').attr('for');
	if(c!=f) {
		$(this).select();
	}
	$('form[name="receipts_change_price_form"] .virtual_keyboard input[type="button"]').attr('for', c);
	$('form[name="receipts_change_price_form"] .virtual_keyboard button').attr('for', c);
});


$('body').off('click', 'input[name="sales_receipts_0"]');
$('body').on('click', 'input[name="sales_receipts_0"]', function(){
	if($(this).prop("checked")) {
		$('.sales_receipts').val(1);
	}
	else {
		$('.sales_receipts').val(0);
	}
});

$('body').off('click', 'input[name="fr_no_0"]');
$('body').on('click', 'input[name="fr_no_0"]', function(){
	if($(this).prop("checked")) {
		$('.hold').val(1);
		$('.nofr').val(1);
	}
	else {
		$('.hold').val(0);
		$('.nofr').val(0);
	}
});

$('body').off('click', 'input[name="fr_bt_0"]');
$('body').on('click', 'input[name="fr_bt_0"]', function(){
	if($(this).prop("checked")) {
		$('.nobt').val(1);
	}
	else {
		$('.nobt').val(0);
	}
});

$('input[name="description"]').click(function(){
	$('.virtual_keyboard_add_description').show();
});

$('body').on('submit', 'form[name="products_all_search_form"]', function(){
	close_window(this);
});


// Проводка документа, если была ошибка ФР, но чек распечатался
$('body').off('click', '.continue_fr');
$('body').on('click', '.continue_fr', function(){
	// Определяем необходимость отправки формы
	var form, type;
	var continue_print=$(this).attr('continue_print');
	// Чеки оплаты или возрата
	if($('.tab_page_select form').length>0) {
		form=$('.tab_page_select form');
		type="sales";
	}
	else if($('form[name="receipts_return_form"]').length>0) {
		form=$('form[name="receipts_return_form"]');
		type="return";
	}
	else if($('form[name="receipt_cashin_form"]').length>0) {
		form=$('form[name="receipt_cashin_form"]');
		type="cashin";
	}
	else if($('form[name="receipt_cashout_form"]').length>0) {
		form=$('form[name="receipt_cashout_form"]');
		type="cashout";
	}
	else {
		if(continue_print>0) {
			load_ajax($(this).attr('href')+'?continue_print=1');
			close_window($(this));
		}
		return;
	}

	var action=form.attr('action');
	// Отправляем форму на принудительное проведение документа
	form.attr('action', '/receipts/hold?type='+type+'&continue_print='+continue_print);
	form.submit();
	// Возвращаем как было
	form.attr('action', action);
});

$('body').off('blur', '.discount_input');
$('body').on('blur', '.discount_input', function() {
	//$('.virtual_keyboard_discount_input').hide();
});

$('body').off('keydown', '.marking_input');
$('body').on('keydown', '.marking_input', function(e){
	if(e.which==13) {
		if($('.marking_input').length>1) {
			e.preventDefault();
			var input=$('.marking_input', $(this).closest('p').next('p'));
			if(input.length>0) {
				input.focus();
			}
			else {
				$(this).closest('form').submit();
			}
		}
	}
});

function auto_layout_keyboard(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", "б":",",
		"Б":"<", "ю":".", "Ю":">", ".":"/", ",":"?", "ё":"`", "Ё":"~"
	};
	var res='';
	for(var i=0; i<str.length; i++) {
		var s=str[i];
		var a=replacer[s];
		if(!a) {
			a=replacer[s.toLowerCase()];
			if(a)a=a.toUpperCase();
		}
		if(!a) {
			a=s;
		}
		res+=a;
	}
	return res;
}

function is_kyr(str) {
	return /[а-яё]/i.test(str);
}

$('body').off('change', '.marking_input');
$('body').on('change', '.marking_input', function() {
	if(auto_replacekey!=1) return;
	var str=$(this).val();
	if(is_kyr(str)) {
		str=auto_layout_keyboard(str);
		$(this).val(str);
	}
});

$('body').off('submit', 'form[name="add_line_form"]');
$('body').on('submit', 'form[name="add_line_form"]', function(){
	close_window(this);
});

function receiptlines_div_resize() {
	if($('form[name="receipts_return_form"]').length>0) return;
	var scroll_button=0;
	if($('.scroll_button').length>0) {
		scroll_button=$('.scroll_button').height()*$('.scroll_button').length;
	}
	var h=84;
	if($('#right_td_with_product_menu').length>0) {
		h=$('#product_search_form').height()+115;
		if($('#other_prints button').length==0) {
			h-=45;
		}
	}
	if($(document).width()<961) {
		if($('#other_prints .big_button').length>0) h=108;
		else h=60;
	}
	$('.receiptlines_div').height($('body').height()-$('.total_table').height()-h-scroll_button);
	$('#products_list_column').height($('body').height()-60);
	$('.button_total .receipt_sum').html($('.total_table .receipt_sum').html());
	if($('#max_bonus_pay').length>0) {
		$('.max_bonus_pay_txt').html($('#max_bonus_pay').val());
		$('.partner_all_bonus_txt').html($('#partner_all_bonus').val());
	}
	if($('#select_room').length>0) {
  		resize_rooms();
	}

	var getType = {};
	if(getType.toString.call(window['kiosk_buy_control']) === '[object Function]') {
		kiosk_buy_control();
	}
}

if($('.receiptlines_div').length>0) {
	receiptlines_div_resize();
	$(window).resize(function(){
		receiptlines_div_resize();
	});
}

function receiptlines_div_scroll(k) {
	$('.receiptlines_div').scrollTop($('.receiptlines_div').scrollTop()-(k*$('.receiptlines ').height()/2));
}

$('body').off('click', '#scroll_button_up');
$('body').on('click', '#scroll_button_up', function(){
	receiptlines_div_scroll(1);
});

$('body').off('click', '#scroll_button_down');
$('body').on('click', '#scroll_button_down', function(){
	receiptlines_div_scroll(-1);
});

// Изменить кол-во добавляемых модификаторов
function modifiers_count(elem) {
	$(elem).removeClass('modifiers_count_-1');
	$(elem).removeClass('modifiers_count_1');
	var val=$(elem).val();
	if(val<0) {
		val=0;
		$(elem).val(0);
	}
	var product_id=$(elem).attr('data-product');
	var parent_id=$(elem).attr('data-parent');
	var href='/receipts/add_line?product_id='+product_id+'&parent_id='+parent_id+'&count='+val;
	load_ajax(href);
}

$('body').off('click', '.count_minus');
$('body').on('click', '.count_minus', function() {
	var elem=$('input[name="count"]', $(this).closest('.modifiers_count'));
	var val=elem.val();
	var step=Number(elem.attr('step'));
	val-=step;
	if(val<0) {
		val=0;
		elem.val(0);
	}
	else if(val%step>0) {
		false_alarm();
		show_window('error', '<p class="false">Количество должно быть кратно '+step+'</p>');
		return
	}
	elem.val(val);
	elem.trigger('change');
});

$('body').off('click', '.count_plus');
$('body').on('click', '.count_plus', function() {
	var elem=$('input[name="count"]', $(this).closest('.modifiers_count'));
	var step=Number(elem.attr('step'));
	var val=Number(elem.val())+step;
	if(val%step>0) {
		false_alarm();
		show_window('error', '<p class="false">Количество должно быть кратно '+step+'</p>');
		return
	}
	elem.val(Number(elem.val())+Number(step));
	elem.trigger('change');
});

$('body').off('change', '.modifiers_count input[name="count"]');
$('body').on('change', '.modifiers_count input[name="count"]', function() {
	modifiers_count(this);
});

$('body').off('change', 'form[name="receipts_coorect1_form"] select[name="correct_type"]');
$('body').on('change', 'form[name="receipts_coorect1_form"] select[name="correct_type"]', function(){
	if($(this).val()==1) {
		$('.correct_type_1').show();
		$('.correct_type_0').hide();
	}
	else {
		$('.correct_type_1').hide();
		$('.correct_type_0').show();
	}
});

$('body').off('change', 'form[name="print_turn_form"] input[type="radio"]');
$('body').on('change', 'form[name="print_turn_form"] input[type="radio"]', function(){
	$('form[name="print_turn_form"]').submit();
});

function save_order_status(status_id) {
	$(".order_status").html($('#status_'+status_id).val());
	close_window("#select_order_status");
}

$('body').off('change', '#ticket_description');
$('body').on('change', '#ticket_description', function(){
	var txt=$(this).val();
	var receipt_id=$(this).attr('data-id');
	$.ajax({
        	url: '/receipts/description',
        	method: 'POST',
        	data: {'description': txt, 'id': receipt_id}
 		});
});

if($('#ticket_description').length>0) {
	$('#ticket_description').trigger('change');
}

$('body').off('click', '#ticket_description_reset');
$('body').on('click', '#ticket_description_reset', function(){
	$('#ticket_description').val('');
	$('#ticket_description').trigger('change');
});

$('body').off('submit', 'form[name="online_order_form"]');
$('body').on('submit', 'form[name="online_order_form"]', function(){
	$(this).closest('.popup').remove();
});

$('body').off('click', '.online_order_search_button_show a');
$('body').on('click', '.online_order_search_button_show a', function(){
	$('.online_order_search').removeClass('online_order_search_hide');
});

$('body').off('click', '.online_order_search_button_hide a');
$('body').on('click', '.online_order_search_button_hide a', function(){
	$('.online_order_search').addClass('online_order_search_hide');
});

$('body').off('click', '.receipt_pay_ok');
$('body').on('click', '.receipt_pay_ok', function() {
	$('#receipt_pay_ok').trigger('click');
});

$('body').off('click', '#receipt_pay_ok');
$('body').on('click', '#receipt_pay_ok', function(){
	if($(this).prop('disabled') || $('#loading').length>0) return; // уже отправляется, игнорируем повторный клик
	var form=$('.tab_page_select form');
	var ok=0;
	var error=-1;
	$('input.no_egais', form).val(0);
	if(receipt_sum>0) {
		$('input.client_sum', form).each(function(n){
			ok=$(this).val();
			if(ok<=0 || ok=='') error=n;
		});
	}
	if(error<0) {
		$('#receipt_pay_ok, .receipt_pay_ok').prop('disabled', true);
		$('.tab_page_select form').submit();
	}
	else {
		false_alarm();
		if(error==0) var txt='Сумма наличных должна быть больше 0';
		if(error==1) var txt='Сумма безналичных должна быть больше 0';
		show_window('error', txt);
	}
});

$('body').off('click', '.egais_alarm_ok');
$('body').on('click', '.egais_alarm_ok', function(){
	close_window(this);
	var form=$('.tab_page_select form');
	var ok=0;
	var error=-1;
	$('input.no_egais', form).val(1);
	if(receipt_sum>0) {
		$('input.client_sum', form).each(function(n){
			ok=$(this).val();
			if(ok<=0 || ok=='') error=n;
		});
	}
	if(error<0) $('.tab_page_select form').submit();
	else {
		false_alarm();
		if(error==0) var txt='Сумма наличных должна быть больше 0';
		if(error==1) var txt='Сумма безналичных должна быть больше 0';
		show_window('error', txt);
	}
});

$('body').off('click', '#writeoff_ok');
$('body').on('click', '#writeoff_ok', function() {
	$('input[name="writeoff"]').val($('select[name="TypeWriteOff"]').val());
	$('.tab_page_select form').submit();
});

$('body').off('change', '#fr_print_0');
$('body').on('change', '#fr_print_0', function(){
	if($(this).prop('checked')) {
		$('.fr_print').val(1);
	}
	else {
		$('.fr_print').val(0);
	}
});


function paycontrol() {
	if($('form[name="controlpay_qr_form"]').length==0) {
		$.ajax({
	        url: '/',
	        method: 'GET',
	        dataType: "html",
	        timeout: 1000
	 	});
		return;
	}
	if($('.show_qr').length==0) return;
	var form=$('form[name="controlpay_qr_form"]');
	var formData = $(form).serialize();
	$.ajax({
        url: form.attr('action'),
        method: 'POST',
        dataType: "json",
        data: formData,
        success: function(response) {
        	if(response.success===true) {
        		close_window(form);
        		$('.tab_page_select form').submit();
        		return;
        	}
        	if(response.show_error===true) {
        		false_alarm();
        		close_window(form);
        		show_window('error', response.txt);
        		return;
        	}
       		setTimeout('paycontrol()', 1000);
    	},
    	error: function(response) {
    		false_alarm();
    		setTimeout('paycontrol()', 1000);
    	},
    	timeout: 65000
 	});
}

$('body').off('click', '#print_qr');
$('body').on('click', '#print_qr', function(){
	show_window('loading', loading_txt);
	$.ajax({
		url: $(this).attr('href'),
		dataType: "html",
		success: function(response) {
			close_window('#loading');
	    },
	    error: function(response) {
	    	false_alarm();
	    	$("#loading .popup_content").html(response.statusText);
            $("#loading .close").show();
	    },
	    timeout: 65000
 	});
});

$('body').off('click', '.show_epays_report');
$('body').on('click', '.show_epays_report', function(){
	$('.txt_show', this).toggle();
	$('.txt_hide', this).toggle();
	$('.epays_report').toggle();
});

$(document).click(function(e){
	var div = $(".ticket_body");
	if (!div.is(e.target) && div.has(e.target).length==0) {
		$('.ticket_body').removeClass('ticket_body_show');
	}
});

$('body').off('click', '.ticket_body');
$('body').on('click', '.ticket_body', function(){
	$('.ticket_body').removeClass('ticket_body_show');
	$(this).toggleClass('ticket_body_show');
});

if(gs1_ok==undefined) {
	var keys_with_alt='';
	var key_29=false;

	$('body').off('keyup', '.product_search, .marking_input, .mark_return_input');
	$('body').on('keyup', '.product_search, .marking_input, .mark_return_input', function(e) {
		e.preventDefault();

		if(e.originalEvent.getModifierState('CapsLock')) {
			$('.caps_on').val(1);
		}
		else {
			$('.caps_on').val(0);
		}

		if(e.originalEvent.code=='F8') {
			$(this).val($(this).val()+gs1_symbols);
			return;
		}
		var symbols=new Map();
		symbols['Numpad0']='0';
		symbols['Numpad1']='1';
		symbols['Numpad2']='2';
		symbols['Numpad3']='3';
		symbols['Numpad4']='4';
		symbols['Numpad5']='5';
		symbols['Numpad6']='6';
		symbols['Numpad7']='7';
		symbols['Numpad8']='8';
		symbols['Numpad9']='9';
		if(e.altKey===true && symbols[e.originalEvent.code]!=undefined) {
			keys_with_alt+=symbols[e.originalEvent.code];
		}
		else{
			if(e.which==18 && !key_29) {
				if(keys_with_alt=='029') {
					$(this).val($(this).val()+gs1_symbols);
					key_29=true;
				}
			}
			else {
				key_29=false;
			}
			keys_with_alt='';
		}
		if(isNaN($(this).val())) {
			$(this).closest('form').removeAttr('no_loading_txt');
		}
		else {
			$(this).closest('form').attr('no_loading_txt', '1');
		}
		if($(this).val().substr(0, gs1_symbols.length)==gs1_symbols) {
			$(this).val($(this).val().substr(gs1_symbols.length));
		}
	});

	$('body').off('keypress', '.product_search, .marking_input, .mark_return_input');
	$('body').on('keypress', '.product_search, .marking_input, .mark_return_input', function(e) {
		if(e.keyCode==29 && !key_29) { // BracketRight + Ctrl
			e.preventDefault();
			$(this).val($(this).val()+gs1_symbols);
			key_29=true;
		}
		else {
			key_29=false;
		}
	});
	
	var gs1_ok=1;
}

$('body').off('click', '.delivery_button');
$('body').on('click', '.delivery_button', function(){
	show_window('error');
	var href=$(this).attr('href');
	$.ajax({
        url: href,
        dataType: "html",
        success: function(response) {
        	$('#error').remove();
       		var isJson = true;
        	var res;
        	try {
    			res=JSON.parse(response);
			} catch(e) {
    			isJson = false;
			}
       		if(isJson) {
       			ajax_response(response);
       		}
       		else {
       			show_window(null, response);
       		}
    	},
    	error: function(response) {
    		false_alarm();
    		$('#error').remove();
            show_window('error', response.statusText);
    	},
    	timeout: 65000
 	});
});

if(stock_error && $('form[name="product_search_form"] input[name="type"]').val()!=2) {
	false_alarm();
	show_window('error', '<p class="false">В чеке есть товары с недостаточным кол-вом.</p>');
	stock_error=false;
}

$('body').off('click', '.pricetags_button');
$('body').on('click', '.pricetags_button', function(){
	var form=$(this).closest('form');
	$('input[name="print"]', form).val($(this).attr('data-print'));
	$('input[name="print_type"]', form).val($(this).val());
	form.submit();
});

$('body').off('click', '.select_tap');
$('body').on('click', '.select_tap', function(){
	var form=$(this).closest('form');
	form.submit();
});

$('body').off('submit', 'form[name="add_marking_cocktail_form"]');
$('body').on('submit', 'form[name="add_marking_cocktail_form"]', function() {
	setTimeout('$(".marking_input").val("")', 100);
});

$('body').off('click', '.select_open_bottle');
$('body').on('click', '.select_open_bottle', function() {
	var mark=$(this).attr('data-mark');
	var form=$(this).closest('form');
	$('.marking_input', form).val(mark);
	form.submit();
});

$('body').off('click', '.delete_cocktail_mark');
$('body').on('click', '.delete_cocktail_mark', function() {
	var mark=$(this).attr('data-mark');
	$('.input_'+mark).remove();
	var form=$(this).closest('form');
	$('.marking_input', form).val('');
	form.submit();
});

function get_weight(line_id) {
	$.ajax({
        url: '/scales/weight?line_id='+line_id,
        dataType: "html",
        success: function(response) {
        	if($('form[name="receipts_change_count_form"]').length==0) return;
        	var res;
        	try {
    			res=JSON.parse(response);
    			if(res.success==true && res.weight>0) {
    				$('form[name="receipts_change_count_form"] input[name="count"]').val(res.weight);
   					$('form[name="receipts_change_count_form"]').submit();
    				return;
    			}
    			setTimeout(get_weight, 500, line_id);
			}
			catch(e) {
				console.log(e);
			}
    	},
    	timeout: 65000
 	});
}

$('body').off('click', '.receipt_body');
$('body').on('click', '.receipt_body', function() {
	$(this).addClass('receipt_body_show');
});

$('body').off('click', '.receipt_body_show');
$('body').on('click', '.receipt_body_show', function() {
	$(this).removeClass('receipt_body_show');
});

$('body').off('click', '.show_slip');
$('body').on('click', '.show_slip', function() {
	var div=$(this).closest('div');
	$('.slip', div).toggle();
	$(this, div).toggleClass('show_slip_show');
});

$('body').off('click', '.merge_button');
$('body').on('click', '.merge_button', function() {
	$(this).hide();
	$('.open_ticket .show_window').hide();
	$('.open_ticket .send_ajax').hide();
	$('.new_receipt').hide();
	$('.merge_cancel').show();
	$('.merge_ok').show();
	$('.open_ticket .custom-checkbox+label').removeClass('hide');
});

$('body').off('click', '.merge_cancel');
$('body').on('click', '.merge_cancel', function() {
	$(this).hide();
	$('.open_ticket .show_window').show();
	$('.open_ticket .send_ajax').show();
	$('.merge_button').show();
	$('.merge_ok').hide();
	$('.new_receipt').show();
	$('.open_ticket .custom-checkbox+label').addClass('hide');
	$('.open_ticket .custom-checkbox').prop('checked', false);
});

$('body').off('click', '.new_receipt');
$('body').on('click', '.new_receipt', function() {
	show_window();
	var table_id=$(this).attr('data-table');
	$.ajax({
    	url: '/receipts/new?table_id='+table_id,
    	success: function(response) {
    		try {
    			res=JSON.parse(response);
    			if(res.success) {
    				$('#screen').load(location.pathname+'?not_ajax=1&table_id='+table_id+' #screen_window', function(){
    					receiptlines_div_resize();
    					close_all_window();
  					});
    			}
    			else {
    				ajax_response(res);
    			}
			} catch(e) {
    			show_window(response);
			}
    	},
    	timeout: 3000
	})
});

$('body').off('click', '.printdoc_ok');
$('body').on('click', '.printdoc_ok', function() {
	show_window('load_iframe_print');
	$('#print_frame').html('<iframe id="print_iframe" src="/receipts/pdf?url='+$('select[name="printtemplates"]').val()+'" onload=\'document.getElementById("print_iframe").contentWindow.print(); close_window("#load_iframe_print");\'></iframe>');
	window.onerror=function(){
		$('#load_iframe_print .popup_content').html("<h1>Ошибка</h1><p>Настройки Вашего браузера не позволяют открывать PDF-файлы.</p><p>Если Вы используете Яндекс.Браузер,<br>то в настройках браузера в разделе \"Инструменты\"<br>необходимо разрешить браузеру открывать PDF-файлы.</p><p>А пока можете просто скачать документ <a href='"+href+"'><button type='button'>Скачать</button></a></p>");
	};
});

function check_epay() {
	if($('.paymentmethod_table').length==0) return;
	$.ajax({
    	url: '/receipts/checkepay',
    	success: function(response) {
    		try {
    			res=JSON.parse(response);
    			if(res.success) {
    				$('.paymentmethod_table').hide();
    				$('#select_epay').hide();
    				$('.paymentmethod_slip').show();
    				$('.paymentmethod_slip .show_slip').html(res.slip);
    				return;
    			}
    			setTimeout(check_epay, 2000);
			} catch(e) {
				setTimeout(check_epay, 2000);
			}
    	},
    	error: function(e) {
    		console.log(e);
    		setTimeout(check_epay, 2000);
    	},
    	timeout: 3000
	})
}

$('body').off('click', '#line_button_poopup .line_count_for_line');
$('body').on('click', '#line_button_poopup .line_count_for_line', function () {
	if(!$('.virtual_keyboard_line_count').is(":visible")) {
		$(this).select();
	}
	if(!$(this).is(':focus')) return;
	$('.virtual_keyboard_line_count').show();
});

$('body').off('click', '#cancel_qr');
$('body').on('click', '#cancel_qr', function () {
	var href=$(this).attr('href');
	close_window(this);
	$.ajax({
    	url: href,
    	success: function(response) {
    		try {
    			res=JSON.parse(response);
    			if(!res.success) {
    				console.log(res.txt);
    			}
			} catch(e) {
    			console.log(e);
			}
    	},
    	error: function(e) {
    		console.log(e);
    	},
    	timeout: 3000
	});
});

$('body').off('click', '.product_search_in_all');
$('body').on('click', '.product_search_in_all', function() {
	var title=$('form[name="products_new_form"] input[name="title"]').val();
	$('#product_search_form input[name="product_search"]').val(title);
	$('#product_search_form input[name="category_id"]').val(-1);
	$('#product_search_form').submit();
	close_window($(this));
	$('#product_search_form input[name="category_id"]').val(0);
});