var qr_id=0;
function cd_reload() {
	var time=new Date().getTime();
	$('#receiptlines_cd .receiptlines_html').load('/ui/receiptlines_html.htm?uid='+time, function() {
		$('#receiptlines_cd').scrollTop($('#receiptlines_cd .receiptlines_div').height());
		if($('.line').length>0) {
			$('#cd_receipt').show();
			$('#cd_advs').css('width', '65%');
		}
		else {
			$('#cd_receipt').hide();
			$('#cd_advs').css('width', '100%');
		}
		if($('#cd_advs img').length>0 || $('#show_qr_ok').length>0) {
			$('#cd_advs').show();
			$('#cd_logo').addClass('cd_position_absolute');
			$('#receiptlines_cd').addClass('receiptlines_cd_advs');
			$('#cd_receipt').css('width', 'calc(35% - 10px)');
		}
		else {
			$('#cd_advs').hide();
			$('#cd_receipt').css('width', '100%');
		}
	});
	if($('#show_qr_ok').length>0) {
		if(qr_id!=$('#show_qr_ok').attr('data-id')) {
			$('#qr_html').show();
			$('#cd_logo').removeClass('cd_position_absolute');
			$('#receiptlines_cd').removeClass('receiptlines_cd_advs');
			$('#qr_html').load('/ui/qr_html.htm?uid='+time);
			qr_id=$('#show_qr_ok').attr('data-id');
		}
	}
	if($('#show_qr_ok').length==0) {
		$('#qr_html').hide();
		$('#qr_html').html('');
	}
}

function advs_reload() {
	adv_n=-1;
	$('#advs_cd').load('/cd/receipt?adv=1&ajax=1 #advs_cd .reload', function() {
		adv_n=0;
		advs_src();
	});
}

function advs_src() {
	if(adv_n<0) return;
	$('#advs_cd img').remove();
	var adv=$('#advs_list .adv_'+adv_n).html();
	if(adv) {
		$('#advs_cd .reload').append('<img src="'+adv+'">');
	}
	adv_n++;
	if($('#advs_list .adv_'+adv_n).length==0) {
		adv_n=0;
	}
}

if($('#receiptlines_cd').length>0) {
	cd_reload();
	window.setInterval('cd_reload()', 1000);
}
if($('#cd_advs').length>0) {
	var adv_n=0;
	advs_reload();
	window.setInterval('advs_reload()', 600000);
	//advs_src();
	window.setInterval('advs_src()', cd_time_advs_src);
}

$(document).keydown(function(e){
	$('#product_info input[name="barcode"]').focus();
});

function clear_product_info() {
	$('#product_info_txt').html('');
	$('#product_img').html('');
	$('#cd_pricechecker').removeClass('show_pricechecker_result');
}

var clear_timer;
function clear_barcode_input() {
	$('#pricecheker_form input').removeAttr('disabled');
	$('#pricecheker_form input').val('');
	clear_timer=setTimeout(clear_product_info, pricechecker_clear*1000);
}

$('#pricecheker_form').submit(function(e){
	e.preventDefault();
	$('input', this).blur();
	$('input', this).attr('disabled', 'true');
	
	$('#product_info_txt').html('Идет загрузка...');
	clearTimeout(clear_timer);
	$.ajax({
        url: $(this).attr('action'),
        type: 'GET',
        dataType: "html",
        data: {barcode: $('#pricecheker_form input').val()},
        success: function(response) {
        	$('#cd_pricechecker').addClass('show_pricechecker_result');
        	var res=JSON.parse(response);
        	var txt=res.txt.replace(/([^>])\n/g, '$1<br/>');
        	$('#product_info_txt').html(txt);
        	if(res.img!='') {
        		$('#product_img').html('<img src="'+res.img+'">');
        	}
        	if(pricechecker_speek>0) {
        		var speak='';
        		if(res.success===true) {
        			var rub=Math.floor(res.price);
        			var kop=(res.price*100-rub*100);
        			var last_rub=rub%10;
        			var last2_rub=rub%100;
        			var last_kop=kop%10;
        			var last2_kop=kop%100;
        			var rub_txt='';
        			var kop_txt='';
        			if((last2_rub>=5 && last2_rub<=19) || (last_rub==0 || (last_rub>=5 && last_rub<=9))) {
        				rub_txt='рублей';
        			}
        			else {
        				if(last_rub>=2 && last_rub<=4) {
        					rub_txt='рубля';
        				}
        				else rub_txt='рубль';
        			}

        			if((last2_kop>=5 && last2_kop<=19) || (last_kop==0 || (last_kop>=5 && last_kop<=9))) {
        				kop_txt='копеек';
        			}
        			else {
        				if(last_kop>=2 && last_kop<=4) {
        					kop_txt='копейки';
        				}
        				else kop_txt='копейка';
        			}

        			if(rub>0 || kop==0) {
        				speak+=rub+' '+rub_txt;
        			}
        			if(kop>0) {
        				speak+=' '+kop+' '+kop_txt;
        			}
        			if(speak!='') speak='Цена товара '+speak;
        		}
        		else {
        			speak='Товар не найден, попробуйте еще раз';
        		}
        		speek_product_info(speak);
        	}
        	clear_barcode_input();
    	},
    	error: function(response) {
    		$('#product_info_txt').html(response.statusText);
    		clear_barcode_input();
    	}
 	});
});

if($('#pricecheker_form').length>0 && pricechecker_speek>0) {
	const U=new SpeechSynthesisUtterance();
	var voices=speechSynthesis.getVoices();
	var selected_voice;
	setTimeout(function(){
		voices=speechSynthesis.getVoices();
		selected_voice=voices.findIndex(
    		(voice)=>voice.name===pricechecker_voice
  		);
	}, 100);

  	function speek_product_info(txt) {
  		if(voices.length==0) return;
  		U.text=txt.trim();
		// Получаем выбранный голос
		const voice=voices[selected_voice];
		// Передаем голос и другие настройки экземпляру
		U.voice=voice;
		// язык
		U.lang=voice.lang;
		// громкость
		U.volume=pricechecker_volume;
		// скорость
		U.rate=pricechecker_rate;
		// высота голоса
		U.pitch=pricechecker_pitch;
		// Запускаем озвучивание!
		speechSynthesis.speak(U);
  	}
}