$(function(){
    /*Прогресс-бар доступа по покупке*/
    if ($('.user-product-block').length) {
    var productId = $('.progress-1 .user-product-block').attr('id').replace(/\D+/g,"");
    function declOfNum(n, text_forms) {  
    	n = Math.abs(n) % 100; 
    	var n1 = n % 10;
    	if (n > 10 && n < 20) { return text_forms[2]; }
    	if (n1 > 1 && n1 < 5) { return text_forms[1]; }
    	if (n1 == 1) { return text_forms[0]; }
    	return text_forms[2];
    };
    const months = {
    	'Янв':'01',
    	'Фев':'02',
    	'Мар':'03',
    	'Апр':'04',
    	'Май':'05',
    	'Июн':'06',
    	'Июл':'07',
    	'Авг':'08',
    	'Сен':'09',
    	'Окт':'10',
    	'Ноя':'11',
    	'Дек':'12'
    };
    $.get("/sales/control/userProduct/my", function(data) {
    	$('.table-notitle tbody tr', data).each(function(){
    		var salesProductId = $(this).find('a').attr('href').replace(/\D+/g,"");
    		if (productId == salesProductId) {
    			var startDay = $(this).find('td:nth-child(2)').text().split(' ')[1];
    			var startMonth = $(this).find('td:nth-child(2)').text().split(' ')[2];
    			var startYear = $(this).find('td:nth-child(2)').text().split(' ')[3];
    			var endDay = $(this).find('td:nth-child(2)').text().split(' ')[5];
    			var endMonth = $(this).find('td:nth-child(2)').text().split(' ')[6];
    			var endYear = $(this).find('td:nth-child(2)').text().split(' ')[7];
    			var startDate = new Date(months[startMonth] + '.' + startDay + '.' + startYear);
    			var endDate = new Date(months[endMonth] + '.' + endDay + '.' + endYear);
    			var totalDays = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 3600 *24));
    			var currentDate = new Date();
    			var restDays = Math.ceil((endDate.getTime() - currentDate.getTime()) / (1000 * 3600 *24));
    			var percent = Math.ceil(100 - restDays / totalDays * 100);
    			$('.progress-1 .progress-block .scale').css('width', `${percent}%`)
    			console.log(percent);
    			if (restDays > 0) {
    				$('.progress-1 .progress-block .title').text(`Осталось ${restDays} из ${totalDays} ${declOfNum(totalDays, ['дня', 'дней', 'дней'])}`);
    			} else {
    				$('.progress-1 .progress-block .title').text(`Осталось 0 из ${totalDays} ${declOfNum(totalDays, ['дня', 'дней', 'дней'])}`);
    			}
    		};
    	});
    });}
});
