$dr(document).ready(function(){

	$dr('.leasing-calc').each(function(){
		var fieldsCont = $dr(this).children('.credit-calc-fields');
		var valuesCont = $dr(this).children('.leasing-calc-values');
				
		var setCreditVisual = function(){
			var val1 = valuesCont.children('.leasing-calc-value').eq(0);
			var val1val = val1.find('.leasing-calc-value-val').children('span');
			var val2 = valuesCont.children('.leasing-calc-value').eq(1);
			var val2val = val2.find('.leasing-calc-value-val').children('span');
			var val3 = valuesCont.children('.leasing-calc-value').eq(2);
			var val3val = val3.find('.leasing-calc-value-val').children('span');
			var val4 = valuesCont.children('.leasing-calc-value').eq(3);
			var val4val = val4.find('.leasing-calc-value-val').children('span');
			var val5 = valuesCont.children('.leasing-calc-value').eq(4);
			var val5val = val5.find('.leasing-calc-value-val').children('span');
			
			var creditPrice = Number( $dr('#calcInputSum').val() );
			var creditAvans = Number( $dr('#calcAvans').val() );
			var creditSum = creditPrice - (creditPrice * creditAvans / 100);
			var creditPeriod = Number( $dr('#calcPeriod').val() );
			
			var stavka = false;
			creditCalcData.forEach(function(elem, idx){
				if (creditSum >= elem[0] && creditSum <= elem[1] && creditPeriod >= elem[2] && creditPeriod <= elem[3] && creditAvans >= elem[4] && creditAvans <= elem[5]) {
					stavka = elem[6];
				}
			});
			
			if (stavka !== false) {
				// count month pay
				var stavkaMonth = stavka / 100 / 12;
				
				var tmpChislitel = 1;
				for (var i = 1; i <= creditPeriod; i++) {
					tmpChislitel = tmpChislitel * (1 + stavkaMonth);
				}
				
				var creditMonth = creditSum * stavkaMonth / (1 - (1/tmpChislitel));
				// ---------------
				
				var creditSum2 = creditMonth * creditPeriod;
				
				val1val.html( addCommas( Math.ceil(creditPrice)) );
				val2val.html( addCommas( Math.ceil(creditPrice-creditSum)) );
				val3val.html( addCommas( Math.ceil(creditMonth)) );
				val4val.html( addCommas( Math.ceil(creditPeriod)) );
				val5val.html( addCommas( Math.ceil(creditSum2)) );
			}
		}
		
		
		
		fieldsCont.children('.credit-calc-field').each(function(){
			var begun = $dr(this).find('.begun');
			var begunSel = begun.find('.begun-sel');
			var bul = begunSel.children('div');
			
			var inputId = begun.children('.inputId').val();
			var begunField = $dr('#' + inputId);
			
			var begunStart = begun.children('.min').val();
			var begunEnd = begun.children('.max').val();
			var begunStep = begun.children('.step').val();
			var begunCountSteps = (begunEnd - begunStart) / begunStep;
			
			var begunWidthMin = 0;
			var begunWidthMax = begun.width()-bul.width();
			var begunWidthStart = 0;
			var begunWidthStep = (begunWidthMax - begunWidthMin) / begunCountSteps;
			
			var bulStart = 0;
			var bulEnd = 0;
			var inAction = 0;
			
			var setBegunVal = function(){
				begunField.val( Number(begunStart) + Number(Math.floor((begunSel.width()-begunWidthMin)  / begunWidthStep) * begunStep)  );
				begunField.change();
			};
			
			var setBegunPos = function(elem){
				if (!inAction) {
					var val = Number ( elem.val() );
					if (isNaN (val) || val < begunStart) {
						val = begunStart;
					} else if (val > begunEnd) {
						val = begunEnd;
					}
					begunField.val( val );
					
					if (begunStart == begunEnd) {
						begunSel.width(   begunWidthMax   );
					} else {
						begunSel.width(   Math.floor( ((val-begunStart) / begunStep) * begunWidthStep )   );
					}
					
				}
			}
			
			setBegunPos( begunField );
			
			
			begunField.change(function(){
				setBegunPos( $dr(this) );
				setCreditVisual();
			});
		
			bul.mousedown(function(event){
				bulStart = event.pageX;
				begunWidthStart = begunSel.width();
				inAction = 1;
			});
			
			$dr(document).mousemove(function(event){
				if (inAction) {
					bulEnd= event.pageX;
					
					if (begunWidthStart + bulEnd - bulStart <= begunWidthMin) {
						begunSel.width(begunWidthMin);
					} else if (begunWidthStart + bulEnd - bulStart >= begunWidthMax) {
						begunSel.width( begunWidthMax );
					} else {
						begunSel.width( begunWidthStart + bulEnd - bulStart );
					}
					setBegunVal();
					setCreditVisual();
				}
			});
			
			begun.click(function(event){
				inAction = true;
				bulStart = begun.offset().left;
				bulEnd= event.pageX;
				if (bulEnd - bulStart <= begunWidthMin) {
					begunSel.width(begunWidthMin);
				} else if (bulEnd - bulStart >= begunWidthMax) {
					begunSel.width( begunWidthMax );
				} else {
					begunSel.width( bulEnd - bulStart - 8);
				}
				setBegunVal();
				inAction = false;
				setCreditVisual();
			}).find('.begun-sel > div').click(function(event){
				event.stopPropagation();
			});
			
			bul.mouseup(function(event){
				inAction = false;
				setCreditVisual();
			});
			$dr(document).mouseup(function(event){
				if (inAction) {
					inAction = false;
					setCreditVisual();
				}
			});
			
		});
		
		setCreditVisual();
		
	});






	
	$dr('.credit-calc').each(function(){
		var fieldsCont = $dr(this).children('.credit-calc-fields');
		var valuesCont = $dr(this).children('.credit-calc-values');
		
		var inAnimateVisual = false;
		
		var setCreditVisual = function(){
			var val1 = valuesCont.children('.credit-calc-value').eq(0);
			var val1max = Number( val1.find('input.maxHeight').val() );
			var val1body = val1.find('.calc-visual-body');
			var val1val = val1.find('.credit-calc-value-val').children('span');
			
			var val2 = valuesCont.children('.credit-calc-value').eq(1);
			var val2max = Number( val2.find('input.maxHeight').val() );
			var val2body = val2.find('.calc-visual-body');
			var val2val = val2.find('.credit-calc-value-val').children('span');
			
			var val3 = valuesCont.children('.credit-calc-value').eq(2);
			var val3max = Number( val3.find('input.maxHeight').val() );
			var val3body = val3.find('.calc-visual-body');
			var val3val = val3.find('.credit-calc-value-val').children('span');
			
			
			var creditMaxSum = Number( $dr('#calcInputSum').closest('.credit-calc-field').find('input.max').val() );
			var creditMinSum = Number( $dr('#calcInputSum').closest('.credit-calc-field').find('input.min').val() );
			var creditSum = Number( $dr('#calcInputSum').val() );
			var creditMaxPeriod = Number( $dr('#calcPeriod').closest('.credit-calc-field').find('input.max').val() );
			var creditPeriod = Number( $dr('#calcPeriod').val() );
			
			var stavka = false;
			var maxperiod = 0;
			if ( $dr('#creditInsurance').is(':checked') ) {
				var creditData = creditCalcData[1];
			} else {
				var creditData = creditCalcData[0];
			}
			creditData.forEach(function(elem, idx){
				if (creditSum >= elem[0] && creditSum <= elem[1] && creditPeriod >= elem[2] && creditPeriod <= elem[3]) {
					stavka = elem[4];
					if (maxperiod < elem[3]) {
						maxperiod = elem[3];
					}
				}
			});
			
			
			if (stavka !== false) {
				// count month pay
				var stavkaMonth = stavka / 100 / 12;
				
				var tmpChislitel = 1;
				for (var i = 1; i <= creditPeriod; i++) {
					tmpChislitel = tmpChislitel * (1 + stavkaMonth);
				}
				
				var tmpZnamenatel = 1;
				for (var i = 1; i <= creditPeriod-1; i++) {
					tmpZnamenatel2 = 1;
					for (var j = i+1; j <= creditPeriod; j++) {
						tmpZnamenatel2 = tmpZnamenatel2 * (1 + stavkaMonth);
					}
					tmpZnamenatel = tmpZnamenatel + tmpZnamenatel2;
				}
				
				var creditMonth = creditSum * tmpChislitel / tmpZnamenatel;
				// ---------------
				
				var creditSum2 = creditMonth * creditPeriod;
				
				val1val.html( addCommas( Math.ceil(creditMonth)) );
				val2val.html( addCommas( Math.ceil(creditSum)) );
				val3val.html( addCommas( Math.ceil(creditSum2)) );
				
				//var val1height = creditMonth / (creditTotalMax * creditMaxPeriod) * Number(val1max);
				//var val2height = creditSum / (creditTotalMax * creditMaxPeriod) * Number(val2max);
				//var val3height = creditSum2 / (creditTotalMax * creditMaxPeriod) * Number(val3max);
				
				/*
				var val3height = ( 1 - creditMinSum / creditSum2 ) * Number(val3max) * 1.1;
				var val2height = creditSum / creditSum2 * val3height;
				var val1height = creditMonth / creditSum2 * val3height;
				
				// correction
				val3height = val3height  +  25;// * (1 - (creditSum / creditMaxSum));
				val2height = val2height  +  20;// * (1 - (creditSum / creditMaxSum));
				val1height = val1height  +  10;
				*/
				
				var val3height = ( 1 - creditMinSum / creditSum2 ) * 50;
				var val2height = creditSum / creditSum2 * val3height;
				var val1height = creditMonth / creditSum2 * val3height;
				
				// correction
				val3height = val3height  +  40;
				val2height = val2height  +  35;
				val1height = val1height  +  15;
				
				//$dr('.credit-calc-value-label').html(     1 - (creditMinSum / creditSum2)       );
				
				val1body.css('height', val1height + 'px');
				val2body.css('height', val2height + 'px');
				val3body.css('height', val3height + 'px');
			}
		}
		
		
		
		fieldsCont.find('.credit-calc-checkbox').children('input[type=checkbox]').change(function(){
			setCreditVisual();
		});
		
		
		
		fieldsCont.children('.credit-calc-field').each(function(){
			var begun = $dr(this).find('.begun');
			var begunSel = begun.find('.begun-sel');
			var bul = begunSel.children('div');
			
			var inputId = begun.children('.inputId').val();
			var begunField = $dr('#' + inputId);
			
			var begunStart = begun.children('.min').val();
			var begunEnd = begun.children('.max').val();
			var begunStep = begun.children('.step').val();
			var begunCountSteps = (begunEnd - begunStart) / begunStep;
			
			var begunWidthMin = 0;
			var begunWidthMax = begun.width()-bul.width();
			var begunWidthStart = 0;
			var begunWidthStep = (begunWidthMax - begunWidthMin) / begunCountSteps;
			
			var bulStart = 0;
			var bulEnd = 0;
			var inAction = 0;
			
			var setBegunVal = function(){
				begunField.val( Number(begunStart) + Number(Math.floor((begunSel.width()-begunWidthMin)  / begunWidthStep) * begunStep)  );
				begunField.change();
			};
			
			var setBegunPos = function(elem){
				if (!inAction) {
					var val = Number ( elem.val() );
					if (isNaN (val) || val < begunStart) {
						val = begunStart;
					} else if (val > begunEnd) {
						val = begunEnd;
					}
					begunField.val( val );
					
					if (begunStart == begunEnd) {
						begunSel.width(   begunWidthMax   );
					} else {
						begunSel.width(   Math.floor( ((val-begunStart) / begunStep) * begunWidthStep )   );
					}
					
				}
			}
			
			setBegunPos( begunField );
			
			
			begunField.change(function(){
				setBegunPos( $dr(this) );
				setCreditVisual();
			});
		
			bul.mousedown(function(event){
				bulStart = event.pageX;
				begunWidthStart = begunSel.width();
				inAction = 1;
			});
			
			$dr(document).mousemove(function(event){
				if (inAction) {
					bulEnd= event.pageX;
					
					if (begunWidthStart + bulEnd - bulStart <= begunWidthMin) {
						begunSel.width(begunWidthMin);
					} else if (begunWidthStart + bulEnd - bulStart >= begunWidthMax) {
						begunSel.width( begunWidthMax );
					} else {
						begunSel.width( begunWidthStart + bulEnd - bulStart );
					}
					setBegunVal();
					setCreditVisual();
				}
			});
			
			begun.click(function(event){
				inAction = true;
				bulStart = begun.offset().left;
				bulEnd= event.pageX;
				if (bulEnd - bulStart <= begunWidthMin) {
					begunSel.width(begunWidthMin);
				} else if (bulEnd - bulStart >= begunWidthMax) {
					begunSel.width( begunWidthMax );
				} else {
					begunSel.width( bulEnd - bulStart - 8);
				}
				setBegunVal();
				inAction = false;
				setCreditVisual();
			}).find('.begun-sel > div').click(function(event){
				event.stopPropagation();
			});
			
			bul.mouseup(function(event){
				inAction = false;
				setCreditVisual();
			});
			$dr(document).mouseup(function(event){
				if (inAction) {
					inAction = false;
					setCreditVisual();
				}
			});
			
		});
		
		setCreditVisual();
		
	});














	$dr('.deposit-calc').each(function(){
		var fieldsCont = $dr(this).children('.credit-calc-fields');
		var valuesCont = $dr(this).children('.credit-calc-values');
		var capitalization = Number( fieldsCont.find('input.calcCapitalization').val() );
		
		var setCreditVisual = function(){
			var val1 = valuesCont.children('.credit-calc-value').eq(0);
			var val1max = Number( val1.find('input.maxHeight').val() );
			var val1body = val1.find('.calc-visual-body');
			var val1val = val1.find('.credit-calc-value-val').children('span');
			
			var val2 = valuesCont.children('.credit-calc-value').eq(1);
			var val2max = Number( val2.find('input.maxHeight').val() );
			var val2body = val2.find('.calc-visual-body');
			var val2val = val2.find('.credit-calc-value-val').children('span');
			
			var val3 = valuesCont.children('.credit-calc-value').eq(2);
			var val3max = Number( val3.find('input.maxHeight').val() );
			var val3body = val3.find('.calc-visual-body');
			var val3val = val3.find('.credit-calc-value-val').children('span');
			
			
			var creditMaxSum = Number( $dr('#calcInputSum').closest('.credit-calc-field').find('input.max').val() );
			var creditMinSum = Number( $dr('#calcInputSum').closest('.credit-calc-field').find('input.min').val() );
			var creditSum = Number( $dr('#calcInputSum').val() );
			var creditMaxPeriod = Number( $dr('#calcPeriod').closest('.credit-calc-field').find('input.max').val() );
			var creditPeriod = Number( $dr('#calcPeriod').val() );
			
			var stavka = false;
			var maxperiod = 0;
			var creditData = creditCalcData[capitalization];
			
			creditData.forEach(function(elem, idx){
				if (creditSum >= elem[0] && creditSum <= elem[1] && creditPeriod >= elem[2] && creditPeriod <= elem[3]) {
					stavka = elem[4];
					if (maxperiod < elem[3]) {
						maxperiod = elem[3];
					}
				}
			});
			
			
			if (stavka !== false) {
				// count month pay
				if (capitalization > 0) {
					var daysInPeriod = creditPeriod * 30;
					var capOperations = Math.floor(creditPeriod / capitalization);
					var capDays = capitalization*30;
					
					var tmpSkoba = 1 + (stavka * capDays) / (100 * 365);
					var tmpInSkoba = 1;
					for (var i = 1; i <= capOperations; i++) {
						tmpInSkoba = tmpInSkoba * tmpSkoba;
					}
					
					var totalSum = creditSum * tmpInSkoba;
				} else {
					var daysInPeriod = creditPeriod * 30;
					var totalSum = creditSum + (creditSum * stavka * daysInPeriod) / (365 * 100);
				}
				// ---------------
								
				val1val.html( addCommas( Math.ceil(creditSum)) );
				val2val.html( addCommas( Math.ceil(totalSum)) );
				val3val.html( addCommas( Math.ceil(totalSum-creditSum)) );
				
				var val2height = ( 1 - creditMinSum / totalSum ) * Number(val2max);
				var val1height = creditSum / totalSum * val2height;
				var val3height = (totalSum-creditSum) / totalSum * val2height;
				
				val1body.css('height', (val1height + 10) + 'px');
				val2body.css('height', (val2height + 10) + 'px');
				val3body.css('height', (val3height*1.1 + 10) + 'px');

			}
		}
		
		
		fieldsCont.children('.credit-calc-field').each(function(){
			var begun = $dr(this).find('.begun');
			var begunSel = begun.find('.begun-sel');
			var bul = begunSel.children('div');
			
			var inputId = begun.children('.inputId').val();
			var begunField = $dr('#' + inputId);
			
			var begunStart = begun.children('.min').val();
			var begunEnd = begun.children('.max').val();
			var begunStep = begun.children('.step').val();
			var begunCountSteps = (begunEnd - begunStart) / begunStep;
			
			var begunWidthMin = 0;
			var begunWidthMax = begun.width()-bul.width();
			var begunWidthStart = 0;
			var begunWidthStep = (begunWidthMax - begunWidthMin) / begunCountSteps;
			
			var bulStart = 0;
			var bulEnd = 0;
			var inAction = 0;
			
			var setBegunVal = function(){
				begunField.val( Number(begunStart) + Number(Math.floor((begunSel.width()-begunWidthMin)  / begunWidthStep) * begunStep)  );
				begunField.change();
			};
			
			var setBegunPos = function(elem){
				if (!inAction) {
					var val = Number ( elem.val() );
					if (isNaN (val) || val < begunStart) {
						val = begunStart;
					} else if (val > begunEnd) {
						val = begunEnd;
					}
					begunField.val( val );
					
					if (begunStart == begunEnd) {
						begunSel.width(   begunWidthMax   );
					} else {
						begunSel.width(   Math.floor( ((val-begunStart) / begunStep) * begunWidthStep )   );
					}
					
					
				}
			}
			
			setBegunPos( begunField );
			
			
			begunField.change(function(){
				setBegunPos( $dr(this) );
				setCreditVisual();
			});
		
			bul.mousedown(function(event){
				bulStart = event.pageX;
				begunWidthStart = begunSel.width();
				inAction = 1;
			});
			
			$dr(document).mousemove(function(event){
				if (inAction) {
					bulEnd= event.pageX;
					
					if (begunWidthStart + bulEnd - bulStart <= begunWidthMin) {
						begunSel.width(begunWidthMin);
					} else if (begunWidthStart + bulEnd - bulStart >= begunWidthMax) {
						begunSel.width( begunWidthMax );
					} else {
						begunSel.width( begunWidthStart + bulEnd - bulStart );
					}
					setBegunVal();
					setCreditVisual();
				}
			});
			
			begun.click(function(event){
				inAction = true;
				bulStart = begun.offset().left;
				bulEnd= event.pageX;
				if (bulEnd - bulStart <= begunWidthMin) {
					begunSel.width(begunWidthMin);
				} else if (bulEnd - bulStart >= begunWidthMax) {
					begunSel.width( begunWidthMax );
				} else {
					begunSel.width( bulEnd - bulStart - 8 );
				}
				setBegunVal();
				inAction = false;
				setCreditVisual();
			}).find('.begun-sel > div').click(function(event){
				event.stopPropagation();
			});
			
			bul.mouseup(function(event){
				inAction = false;
				setCreditVisual();
			});
			$dr(document).mouseup(function(event){
				if (inAction) {
					inAction = false;
					setCreditVisual();
				}
			});
			
			setCreditVisual();
		});
	});
	
	
	
	
	
	
	
	
	
	
	
	
	$dr('.deposits-matching').each(function(){
		var cmContainer = $dr(this);
		var fieldsCont = cmContainer.find('.credit-calc-fields');
		var cmResults = cmContainer.find('.credit-matching-results');
		
		$dr(document).click(function(elem){
			if ( $dr(elem.target).closest('.credits-matching-container').length == 0 && cmContainer.hasClass('fullscreen')) {
				cmContainer.removeClass('fullscreen');
				var tmpCont = cmContainer.children('.credits-matching-container');
				tmpCont.css('margin-top', '0px');
			}
		});
		
		var creditsMatching = function() {
			cmResults.html('<p>Результаты подбора:</p>');
			
			var creditSum = Number( $dr('#calcInputSum').val() );
			var creditPeriod = Number( $dr('#calcPeriod').val() );
			var countResults = 0;
			
			if ( creditCalcData.length ) {
				creditCalcData.forEach(function(elemItems, idx) { // предложения
					
					var stavkaFix = 0;
					var stavkaTmp = 0;
					var periodFix = creditPeriod;
					var periodTmp = 0;
					var maxAllowSum = 0;
					
					if (elemItems.percents[1].length) {
						if (periodFix < Number(elemItems.minperiod) && (periodFix * 1.25) >= Number(elemItems.minperiod) ) {
							// срок меньше минимального. если минимальный срок = указанному сроку + максимум 25%, ищем ставку для минимального срока
							periodFix = Number( elemItems.minperiod );
						} else if (periodFix > Number(elemItems.maxperiod) && (periodFix * 0.75) <= Number(elemItems.maxperiod) ) {
							// срок больше максимального. если максимальный срок = указанному сроку - максимум 25%, ищем ставку для максимального срока
							periodFix = Number( elemItems.maxperiod );
						}
						
						// ищем ставку по сроку
						elemItems.percents[1].forEach(function(elemPr, idx1) { //проценты
							if (maxAllowSum <= elemPr[1] && creditSum >= elemPr[0]) { // сумма должна быть ограничена снизу
								// срок подходит
								if (periodFix >= elemPr[2] && periodFix <= elemPr[3]) { // период подошел
									stavkaFix = elemPr[4];
									maxAllowSum = elemPr[1]; // в итоге ставку берем для максимально разрешенной суммы
									                         // даже если указали сумма выше, чем в конфиге вклада
								}
							}
						});
					}

					if (stavkaFix > 0 && periodFix > 0) {
						// calculate
						var daysInPeriod = periodFix * 30;
						var capOperations = Math.floor(periodFix / 1) ;
						var capDays = 30;
						
						var tmpSkoba = 1 + (stavkaFix * capDays) / (100 * 365);
						var tmpInSkoba = 1;
						for (var i = 1; i <= capOperations; i++) {
							tmpInSkoba = tmpInSkoba * tmpSkoba;
						}
						var totalMaxSum = creditSum * tmpInSkoba;
						// --------------
						
						if (countResults == 0) {
							cmResults.append('<div class="credit-matching-results-header"><span style="margin-left:300px">Срок</span><span>Чистый доход</span><span style="width:200px">Сумма с учетом дохода</span></div>');
						}
						
						cmResults.append('<div class="credit-matching-results-item">' + 
						'<span style="width:300px"><a href="/' + elemItems.url + '">' + elemItems.title + '</a></span>' + 
						'<span>' + periodFix + ' мес.</span>' + 
						'<span>' + addCommas (Math.floor(totalMaxSum - creditSum)) + ' руб.</span>' + 
						'<span>' + addCommas (Math.floor(totalMaxSum)) + ' руб.</span></div>');
						
						countResults = countResults+1;
					}
				});
				
				
			}
			
			if (!countResults) {
				cmResults.html('<p>К сожалению, по вашему запросу предложений не найдено. Попробуйте изменить параметры запроса.</p>');
			}
			
			
			var tmpCont = cmContainer.children('.credits-matching-container');
			tmpCont.animate({
				'margin-top': ( (window.innerHeight - tmpCont.height()) / 2) + 'px'
			}, 'fast');
		}
		
		if (cmContainer.hasClass('fullscreen')) {
			creditsMatching();
		}
		
		cmContainer.find('a.btn-red-big2').click(function(){
			if (!cmContainer.hasClass('fullscreen')) {
				cmContainer.addClass('fullscreen');
			}
			
			creditsMatching();
		});
		
		fieldsCont.children('.credit-calc-field').each(function(){
			var begun = $dr(this).find('.begun');
			var begunSel = begun.find('.begun-sel');
			var bul = begunSel.children('div');
			
			var inputId = begun.children('.inputId').val();
			var begunField = $dr('#' + inputId);
			
			var begunStart = begun.children('.min').val();
			var begunEnd = begun.children('.max').val();
			var begunStep = begun.children('.step').val();
			var begunCountSteps = (begunEnd - begunStart) / begunStep;
			
			var begunWidthMin = 0;
			var begunWidthMax = begun.width()-bul.width();
			var begunWidthStart = 0;
			var begunWidthStep = (begunWidthMax - begunWidthMin) / begunCountSteps;
			
			var bulStart = 0;
			var bulEnd = 0;
			var inAction = 0;
			
			var setBegunVal = function(){
				if (inputId == 'calcInputSum') {
					var wallPercent1 = 0.5; // стенка 1
					var wallPercent2 = 0.75; // стенка 2
					
					if ( begunSel.width() / begunWidthMax < wallPercent1 ) {  // 0 .. 0.5
						var begunValTmp = Number(begunStart) + Number(Math.floor( 700000 *  begunSel.width() / begunWidthMax / wallPercent1 ));
					} else if ( begunSel.width() / begunWidthMax >= wallPercent1   &&   begunSel.width() / begunWidthMax <= (wallPercent1 + 0.02) ) { // 0.5
						var begunValTmp = 700000;
					} else if ( begunSel.width() / begunWidthMax > (wallPercent1 + 0.02)   &&   begunSel.width() / begunWidthMax < wallPercent2 ) { // 0.5 .. 0.75
						var begunValTmp = 700000 + Number(Math.floor( 1300000 *  (begunSel.width() / begunWidthMax - wallPercent1) / ( wallPercent2 - wallPercent1 ) ));
					} else if ( begunSel.width() / begunWidthMax >= wallPercent2   &&   begunSel.width() / begunWidthMax <= (wallPercent2 + 0.02) ) { // 0.75
						var begunValTmp = 2000000;
					} else {
						var begunValTmp = 2000000   +   (begunEnd - 2000000) * (begunSel.width() / begunWidthMax - wallPercent2) / (1-wallPercent2);
					}

				} else {
					var begunValTmp = Number(begunStart) + Number(Math.floor((begunSel.width()-begunWidthMin)  / begunWidthStep) * begunStep);
				}
				begunField.val( Math.floor(begunValTmp) );
				begunField.change();
			};
			
			var setBegunPos = function(elem){
				if (!inAction) {
					var val = Number ( elem.val() );
					if (isNaN (val) || val < begunStart) {
						val = begunStart;
					} else if (val > begunEnd) {
						val = begunEnd;
					}
					
					if (inputId == 'calcInputSum') {
						var wallPercent1 = 0.5; // стенка 1
						var wallPercent2 = 0.75; // стенка 2
						if (val <= 700000) {
							var begunPosTmp = ((val-begunStart) / 700000) * (begunWidthMax * wallPercent1);
						} else if (val > 700000 && val < 2000000) {
							var begunPosTmp = begunWidthMax * (wallPercent1  +  (wallPercent2 - wallPercent1) * ((val-700000) / 1300000));
						} else {
							var begunPosTmp = begunWidthMax * (wallPercent2  +  (1 - wallPercent2) * ((val-2000000) / (begunEnd-2000000)));
						}
						/* else {
							var begunPosTmp = (begunWidthMax * wallPercent1)  +  ((val-begunStart-700000) / (begunEnd-700000)) * (begunWidthMax * (1-wallPercent1) );
						}*/
					} else {
						var begunPosTmp = ((val-begunStart) / begunStep) * begunWidthStep;
					}
					
					begunField.val( val );
					begunSel.width(   Math.floor( begunPosTmp ) );
					
				}
			}
			
			setBegunPos( begunField );
			
			
			begunField.change(function(){
				setBegunPos( $dr(this) );
			});
		
			bul.mousedown(function(event){
				bulStart = event.pageX;
				begunWidthStart = begunSel.width();
				inAction = 1;
			});
			
			$dr(document).mousemove(function(event){
				if (inAction) {
					bulEnd= event.pageX;
					
					if (begunWidthStart + bulEnd - bulStart <= begunWidthMin) {
						begunSel.width(begunWidthMin);
					} else if (begunWidthStart + bulEnd - bulStart >= begunWidthMax) {
						begunSel.width( begunWidthMax );
					} else {
						begunSel.width( begunWidthStart + bulEnd - bulStart );
					}
					setBegunVal();
				}
			});
			
			begun.click(function(event){
				inAction = true;
				bulStart = begun.offset().left;
				bulEnd= event.pageX;
				if (bulEnd - bulStart <= begunWidthMin) {
					begunSel.width(begunWidthMin);
				} else if (bulEnd - bulStart >= begunWidthMax) {
					begunSel.width( begunWidthMax );
				} else {
					begunSel.width( bulEnd - bulStart - 8 );
				}
				setBegunVal();
				inAction = false;
			}).find('.begun-sel > div').click(function(event){
				event.stopPropagation();
			});
			
			bul.mouseup(function(event){
				inAction = false;
			});
			$dr(document).mouseup(function(event){
				if (inAction) {
					inAction = false;
				}
			});
			
		});
	});






	$dr('.credits-matching').each(function(){
		var cmContainer = $dr(this);
		var fieldsCont = cmContainer.find('.credit-calc-fields');
		var cmResults = cmContainer.find('.credit-matching-results');
		
		$dr(document).click(function(elem){
			if ( $dr(elem.target).closest('.credits-matching-container').length == 0 && cmContainer.hasClass('fullscreen')) {
				cmContainer.removeClass('fullscreen');
				var tmpCont = cmContainer.children('.credits-matching-container');
				tmpCont.css('margin-top', '0px');
			}
		});
		
		var creditsMatching = function() {
			cmResults.html('<p>Результаты подбора:</p>');
			
			var creditSum = Number( $dr('#calcInputSum').val() );
			var creditSumMaxTotal = 1000000;
			var creditPeriod = Number( $dr('#calcPeriod').val() );
			var countResults = 0;
			
			if ( creditCalcData.length ) {
				creditCalcData.forEach(function(elemItems, idx) { // предложения
					
					var creditSumFix = creditSum;
					var creditSumMin = 0;
					var creditSumMax = 0;
					var stavkaFix = 0;
					var stavkaTmp = 0;
					var periodFix = creditPeriod;
					var periodTmp = 0;
					var maxAllowSum = 0;
					
					if (elemItems.percents[1].length) {
						if (periodFix < Number(elemItems.minperiod) && (periodFix * 1.25) >= Number(elemItems.minperiod) ) {
							// срок меньше минимального. если минимальный срок = указанному сроку + максимум 25%, ищем ставку для минимального срока
							periodFix = Number( elemItems.minperiod );
						} else if (periodFix > Number(elemItems.maxperiod) && (periodFix * 0.75) <= Number(elemItems.maxperiod) ) {
							// срок больше максимального. если максимальный срок = указанному сроку - максимум 25%, ищем ставку для максимального срока
							periodFix = Number( elemItems.maxperiod );
						}
						
						// ищем ставку по сроку
						elemItems.percents[1].forEach(function(elemPr, idx1) { //проценты
							if (creditSumFix >= elemPr[0] && creditSum <= elemPr[1] && // фильтр ставок по сумме
							periodFix >= elemPr[2] && periodFix <= elemPr[3]) { // фильтр по сроку
								stavkaFix = elemPr[4];
							}
							
							// запомним макс и мин суммы
							if (creditSumMax < elemPr[1]) creditSumMax = elemPr[1];
							if (creditSumMin > elemPr[0] || creditSumMin == 0) creditSumMin = elemPr[0];
						});
						
						if (stavkaFix == 0) {
							// по введенной сумме кредит не подошел
							// попробуем изменить сумму
							if (creditSumFix < creditSumMin && (creditSumFix * 1.25) >= creditSumMin) {
								creditSumFix = creditSumMin;
							} else if (creditSumFix > creditSumMax && (creditSumFix * 0.75) <= creditSumMax && creditSumFix <= creditSumMaxTotal) {
								creditSumFix = creditSumMax;
							}
							
							if (creditSumFix == creditSumMin || creditSumFix == creditSumMax) { // если выше изменилась сумма
								elemItems.percents[1].forEach(function(elemPr, idx1) { //проценты
									if (creditSumFix >= elemPr[0] && creditSum <= elemPr[1] && // фильтр ставок по сумме
									periodFix >= elemPr[2] && periodFix <= elemPr[3]) { // фильтр по сроку
										stavkaFix = elemPr[4];
									}
								});
							}
							
						}
					}
					
					if (stavkaFix > 0) {
						if (countResults == 0) {
							cmResults.append('<div class="credit-matching-results-header"><span style="margin-left:220px;width:100px">Срок</span><span style="width:140px">Сумма</span><span style="width:160px">Ежемесячный платеж</span><span style="width:200px">Сумма с учетом переплаты</span></div>');
						}
						
						// count month pay
						var stavkaMonth = stavkaFix / 100 / 12;
						
						var tmpChislitel = 1;
						for (var i = 1; i <= periodFix; i++) {
							tmpChislitel = tmpChislitel * (1 + stavkaMonth);
						}
						
						var tmpZnamenatel = 1;
						for (var i = 1; i <= periodFix-1; i++) {
							tmpZnamenatel2 = 1;
							for (var j = i+1; j <= periodFix; j++) {
								tmpZnamenatel2 = tmpZnamenatel2 * (1 + stavkaMonth);
							}
							tmpZnamenatel = tmpZnamenatel + tmpZnamenatel2;
						}
						
						var creditMonth = creditSumFix * tmpChislitel / tmpZnamenatel;
						// ---------------
						
						cmResults.append('<div class="credit-matching-results-item">' + 
							'<span style="width:220px"><a href="/' + elemItems.url + '">' + elemItems.title + '</a></span>' + 
							'<span style="width:100px">' + periodFix + ' мес.</span>' + 
							'<span style="width:140px">' + addCommas (Math.floor(creditSumFix)) + ' руб.</span>' + 
							'<span style="width:160px">' + addCommas (Math.floor(creditMonth)) + ' руб.</span>' + 
							'<span>' + addCommas (Math.floor(creditMonth * creditPeriod)) + ' руб.</span></div>');
							
						countResults = countResults+1;
					}
					
					
				});
				
				
				if (countResults == 0 && creditSum > creditSumMaxTotal) {
					cmResults.html('<p>Предлагаем <a href="/requestcredit">оформить заявку</a> на кредит на индивидуальных условиях.</p>');
					
					creditCalcData.forEach(function(elemItems, idx) { // предложения
						var creditSumFix = creditSum;
						var creditSumMin = 0;
						var creditSumMax = 0;
						var stavkaFix = 0;
						var stavkaTmp = 0;
						var periodFix = creditPeriod;
						var periodTmp = 0;
						var maxAllowSum = 0;
						
						if (elemItems.percents[1].length) {
							if (periodFix < Number(elemItems.minperiod) && (periodFix * 1.25) >= Number(elemItems.minperiod) ) {
								// срок меньше минимального. если минимальный срок = указанному сроку + максимум 25%, ищем ставку для минимального срока
								periodFix = Number( elemItems.minperiod );
							} else if (periodFix > Number(elemItems.maxperiod) && (periodFix * 0.75) <= Number(elemItems.maxperiod) ) {
								// срок больше максимального. если максимальный срок = указанному сроку - максимум 25%, ищем ставку для максимального срока
								periodFix = Number( elemItems.maxperiod );
							}
							
							// ищем ставку по сроку
							elemItems.percents[1].forEach(function(elemPr, idx1) { //проценты
								if (creditSumMaxTotal >= elemPr[0] && creditSumMaxTotal <= elemPr[1] && // фильтр ставок по сумме
								periodFix >= elemPr[2] && periodFix <= elemPr[3]) { // фильтр по сроку
									stavkaFix = elemPr[4];
								}
							});
							
							if (stavkaFix > 0) {
								if (countResults == 0) {
									cmResults.append('<div class="credit-matching-results-header"><span style="margin-left:220px;width:100px">Срок</span><span style="width:140px">Сумма</span><span style="width:160px">Ежемесячный платеж</span><span style="width:200px">Сумма с учетом переплаты</span></div>');
								}
								
								// count month pay
								var stavkaMonth = stavkaFix / 100 / 12;
								
								var tmpChislitel = 1;
								for (var i = 1; i <= periodFix; i++) {
									tmpChislitel = tmpChislitel * (1 + stavkaMonth);
								}
								
								var tmpZnamenatel = 1;
								for (var i = 1; i <= periodFix-1; i++) {
									tmpZnamenatel2 = 1;
									for (var j = i+1; j <= periodFix; j++) {
										tmpZnamenatel2 = tmpZnamenatel2 * (1 + stavkaMonth);
									}
									tmpZnamenatel = tmpZnamenatel + tmpZnamenatel2;
								}
								
								var creditMonth = creditSum * tmpChislitel / tmpZnamenatel;
								// ---------------
								
								cmResults.append('<div class="credit-matching-results-item">' + 
									'<span style="width:220px"><a href="/' + elemItems.url + '">' + elemItems.title + '</a></span>' + 
									'<span style="width:100px">' + periodFix + ' мес.</span>' + 
									'<span style="width:140px">' + addCommas (Math.floor(creditSum)) + ' руб.</span>' + 
									'<span style="width:160px">' + addCommas (Math.floor(creditMonth)) + ' руб.</span>' + 
									'<span>' + addCommas (Math.floor(creditMonth * creditPeriod)) + ' руб.</span></div>');
									
								countResults = countResults+1;
							}
						}
					});
				}
				
			}
			
			if (!countResults) {
				cmResults.html('<p>К сожалению, по вашему запросу предложений не найдено. Попробуйте изменить параметры запроса.</p>');
			}
			
			
			var tmpCont = cmContainer.children('.credits-matching-container');
			tmpCont.animate({
				'margin-top': ( (window.innerHeight - tmpCont.height()) / 2) + 'px'
			}, 'fast');
		}
		
		if (cmContainer.hasClass('fullscreen')) {
			creditsMatching();
		}
		
		cmContainer.find('a.btn-red-big2').click(function(){
			if (!cmContainer.hasClass('fullscreen')) {
				cmContainer.addClass('fullscreen');
			}
			
			creditsMatching();
		});
		
		fieldsCont.children('.credit-calc-field').each(function(){
			var begun = $dr(this).find('.begun');
			var begunSel = begun.find('.begun-sel');
			var bul = begunSel.children('div');
			
			var inputId = begun.children('.inputId').val();
			var begunField = $dr('#' + inputId);
			
			var begunStart = begun.children('.min').val();
			var begunEnd = begun.children('.max').val();
			var begunStep = begun.children('.step').val();
			var begunCountSteps = (begunEnd - begunStart) / begunStep;
			
			var begunWidthMin = 0;
			var begunWidthMax = begun.width()-bul.width();
			var begunWidthStart = 0;
			var begunWidthStep = (begunWidthMax - begunWidthMin) / begunCountSteps;
			
			var bulStart = 0;
			var bulEnd = 0;
			var inAction = 0;
			
			var setBegunVal = function(){
				if (inputId == 'calcInputSum') {
					var wallPercent = 0.75; // стенка
					
					if ( begunSel.width() / begunWidthMax < wallPercent ) {  // 0 .. 0.75
						var begunValTmp = Number(begunStart) + Number(Math.floor( 1000000 *  begunSel.width() / begunWidthMax / wallPercent ));
					} else if ( begunSel.width() / begunWidthMax >= wallPercent   &&   begunSel.width() / begunWidthMax <= (wallPercent + 0.02) ) { // 0.75
						var begunValTmp = 1000000;
					} else { // 0.75 ...
						var begunValTmp = 1000000 + Number(Math.floor( (begunEnd-1000000) *  (begunSel.width() / begunWidthMax - wallPercent) / ( 1 - wallPercent ) ));
					}

				} else {
					var begunValTmp = Number(begunStart) + Number(Math.floor((begunSel.width()-begunWidthMin)  / begunWidthStep) * begunStep);
				}
				begunField.val( Math.floor(begunValTmp) );
				begunField.change();
			};
			
			var setBegunPos = function(elem){
				if (!inAction) {
					var val = Number ( elem.val() );
					if (isNaN (val) || val < begunStart) {
						val = begunStart;
					} else if (val > begunEnd) {
						val = begunEnd;
					}
					
					if (inputId == 'calcInputSum') {
						var wallPercent = 0.75; // стенка
						if (val <= 1000000) {
							var begunPosTmp = ((val-begunStart) / 1000000) * (begunWidthMax * wallPercent);
						} else {
							var begunPosTmp = begunWidthMax * (wallPercent  +  (1 - wallPercent) * ((val-1000000) / (begunEnd-1000000)));
						}
					} else {
						var begunPosTmp = ((val-begunStart) / begunStep) * begunWidthStep;
					}
					
					begunField.val( val );
					begunSel.width(   Math.floor( begunPosTmp ) );
				}
			}
			
			setBegunPos( begunField );
			
			
			begunField.change(function(){
				setBegunPos( $dr(this) );
			});
		
			bul.mousedown(function(event){
				bulStart = event.pageX;
				begunWidthStart = begunSel.width();
				inAction = 1;
			});
			
			$dr(document).mousemove(function(event){
				if (inAction) {
					bulEnd= event.pageX;
					
					if (begunWidthStart + bulEnd - bulStart <= begunWidthMin) {
						begunSel.width(begunWidthMin);
					} else if (begunWidthStart + bulEnd - bulStart >= begunWidthMax) {
						begunSel.width( begunWidthMax );
					} else {
						begunSel.width( begunWidthStart + bulEnd - bulStart );
					}
					setBegunVal();
				}
			});
			
			begun.click(function(event){
				inAction = true;
				bulStart = begun.offset().left;
				bulEnd= event.pageX;
				if (bulEnd - bulStart <= begunWidthMin) {
					begunSel.width(begunWidthMin);
				} else if (bulEnd - bulStart >= begunWidthMax) {
					begunSel.width( begunWidthMax );
				} else {
					begunSel.width( bulEnd - bulStart - 8);
				}
				setBegunVal();
				inAction = false;
			}).find('.begun-sel > div').click(function(event){
				event.stopPropagation();
			});
			
			bul.mouseup(function(event){
				inAction = false;
			});
			$dr(document).mouseup(function(event){
				if (inAction) {
					inAction = false;
				}
			});
			
		});
	});
	
	
});
