 /**************************************************************************
 **   Файл сценариев для реализации визуальной работы калькулятора.       **
 **                                                                       **
 **   Авторы: Глумов Артём Геннадьевич (artyom.altair@gmail.com)          **
 **           Коновальчук Дмитрий Владимирович (dmitry.strong@gmail.com)  **
 **************************************************************************/

//конфигурация, ширина, высота, стеклопакет, профиль
var type='t1-stvor';
var profid='prof-kbe58';
var conf=1;
var width=500;
var height=700;
var packet=1;
var packet_block=0;
var profile=1;
	
$(window).ready(function() {
	//изначальный подсчет стартовой конфигурации
	$('#swidth').val(width);
	$('#sheight').val(height);
	calculate(conf,width,height,packet,profile);

	// Обработка выбора типа
	$("#t1-stvor,#t2-stvor,#t3-stvor,#tsepar,#tdoor").click(function(){
		var cid1=1;
		var cid2=2;
		var bigimg='1-stvor.png';
		
		/* удаляем старое выделение */
		var tnewclass=$('#'+type).attr('class').slice(0,-8);
		$('#'+type).removeClass($('#'+type).attr('class'));
		$('#'+type).addClass(tnewclass);
		
		/* выделяем нужную кнопку */
		var thisclass=$(this).attr('class');
		$(this).removeClass(thisclass);
		$(this).addClass(thisclass+'-checked');
		type=$(this).attr('id');
		
		/* определяем нужную конфигурацию */
		
		//если раздвижки - разблокируем кнопки стеклопакета
		packet_block=0;
		$('#ponecam').removeClass($('#ponecam').attr('class'));
		$('#ponecam').css('cursor', 'pointer');
		$('#ptwocam').removeClass($('#ptwocam').attr('class'));
		$('#ptwocam').css('cursor', 'pointer');
		if(packet==1)
		{
			$('#ponecam').addClass('graybtn-left-checked');
			$('#ptwocam').addClass('graybtn-right');
		}
		else if(packet==2)
		{
			$('#ponecam').addClass('graybtn-left');
			$('#ptwocam').addClass('graybtn-right-checked');
		}
		
		if($(this).attr('id') == 't1-stvor')
		{
			cid1=1;
			cid2=2;
			bigimg='1-stvor.png';
		}
		else if($(this).attr('id') == 't2-stvor')
		{
			cid1=3;
			cid2=4;
			bigimg='2-stvor.png';
		}
		else if($(this).attr('id') == 't3-stvor')
		{
			cid1=5;
			cid2=6;
			bigimg='3-stvor.png';
		}
		else if($(this).attr('id') == 'tsepar')
		{
			cid1=7;
			cid2=8;
			bigimg='separ.png';
			//если раздвижки - блокируем кнопки стеклопакета
			packet_block=1;
			$('#ponecam').removeClass($('#ponecam').attr('class'));
			$('#ponecam').addClass('graybtn-left-disabled');
			$('#ponecam').css('cursor', 'default');
			$('#ptwocam').removeClass($('#ptwocam').attr('class'));
			$('#ptwocam').addClass('graybtn-right-disabled');
			$('#ptwocam').css('cursor', 'default');
		}
		else if($(this).attr('id') == 'tdoor')
		{
			cid1=9;	
			bigimg='door.png';
		}
		
		/* выводим и считаем нужную конфигурацию */
		if($(this).attr('id') == 'tdoor')
		{
			conf=cid1;
			SetSliderRestrictions();
			calculate(conf,width,height,packet,profile);
			$('#win-conf').html('<a id="conf-'+cid1+'" class="checked" href="#" onClick="confclick(\'conf-'+cid1+'\');return false;"><img src="style/images/icons/'+cid1+'.png" alt="" /></a>');
			$('.big-win').html('<img src="style/images/icons/big/'+bigimg+'" alt="" />');
			return false;
		}
		else
		{
			conf=cid1;
			SetSliderRestrictions();
			calculate(conf,width,height,packet,profile);
			$('#win-conf').html('<a id="conf-'+cid1+'" class="checked" href="#" onClick="confclick(\'conf-'+cid1+'\');return false;"><img src="style/images/icons/'+cid1+'.png" alt="" /></a><a id="conf-'+cid2+'" href="#" onClick="confclick(\'conf-'+cid2+'\');return false;"><img src="style/images/icons/'+cid2+'.png" alt="" /></a>');	
			$('.big-win').html('<img src="style/images/icons/big/'+bigimg+'" alt="" />');
			return false;
		}
	});
	
	//Выбор 1-2 конфигурации
	$("#conf-1,#conf-2").click(function(){
		confclick($(this).attr('id'));
		return false;
	});
	
	//Выбор стеклопакета
	$("#ponecam,#ptwocam").click(function(){
		if(packet_block==0)
		{
			if($(this).attr('id')=='ponecam')
			{
				$('#ptwocam').removeClass($('#ptwocam').attr('class'));
				$('#ptwocam').addClass('graybtn-right');
				$('#ponecam').addClass('graybtn-left-checked');
				packet=1;	
			}
			else
			{
				$('#ponecam').removeClass($('#ponecam').attr('class'));
				$('#ponecam').addClass('graybtn-left');
				$('#ptwocam').addClass('graybtn-right-checked');
				packet=2;
			}
			calculate(conf,width,height,packet,profile);
		}
		return false;
	});
	
	//выбор профиля
	$("#prof-kbe58,#prof-kbe70,#prof-veka60,#prof-veka70,#prof-trocal70,").click(function(){
		
		/* удаляем старое выделение */
		var tnewclass=$('#'+profid).attr('class').slice(0,-8);
		$('#'+profid).removeClass($('#'+profid).attr('class'));
		$('#'+profid).addClass(tnewclass);
		
		/* выделяем нужную кнопку */
		var thisclass=$(this).attr('class');
		$(this).removeClass(thisclass);
		$(this).addClass(thisclass+'-checked');
		profid=$(this).attr('id');
		
		if($(this).attr('id') == 'prof-kbe58')
		{
			profile=1;
		}
		else if($(this).attr('id') == 'prof-kbe70')
		{
			profile=2;
		}
		else if($(this).attr('id') == 'prof-veka60')
		{
			profile=3;
		}
		else if($(this).attr('id') == 'prof-veka70')
		{
			profile=4;
		}
		else if($(this).attr('id') == 'prof-trocal70')
		{
			profile=5;
		}
		
		calculate(conf,width,height,packet,profile);
		return false;
	});
	
	//Ввод ширины\высоты
	$('.whwin').keypress(function(e) {
		//ограничиваем цифрами
		if(e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) return false;
	});
	
	//Выделяем текст ширины\высоты при клике
	$(".whwin").click(function () {
		$(this).val(removeSpaces($(this).val()));
		this.select();
	});
	
	//пересчитываем и разбиваем на разряды ширину\высоту (при изменении значения)
	$('.whwin').change(function() {
	
		//Временно работаем только с 2х-камерными	
		//packet=2;
		
		var restr = getRestrictions(conf,packet);
		
		if($(this).attr('id')=='swidth')
		{
			width=parseInt($(this).val());
			if(width < restr.fWidth) { width=restr.fWidth; $(this).val(restr.fWidth); }
			if(width > restr.lWidth) { width=restr.lWidth; $(this).val(restr.lWidth); }
			
			$("#swslider").slider('value', width);
		}
		else if($(this).attr('id')=='sheight')
		{
			height=parseInt($(this).val());
			if(height < restr.fHeight) { height=restr.fHeight; $(this).val(restr.fHeight); }
			if(height > restr.lHeight) { height=restr.lHeight; $(this).val(restr.lHeight); }
			
			$("#shslider").slider('value', height);
		}
		calculate(conf,width,height,packet,profile);
		
		$(this).val(formatNum($(this).val()));
	});

	SliderStart(500,1500,700,1900);
});

//выбор конфигурации
function confclick(confid)
{
	$('#conf-'+conf).removeClass('checked');
	$('#'+confid).addClass('checked');
	conf=confid.slice(-1);
	
	if(conf==1)
	{
		$('.big-win').html('<img src="style/images/icons/big/1-stvor.png" alt="" />');
	}
	else if(conf==2)
	{
		$('.big-win').html('<img src="style/images/icons/big/1-stvor-2.png" alt="" />');
	}
	
	SetSliderRestrictions();
	calculate(conf,width,height,packet,profile);
}

/* функция подсчета стоимости */
function calculate(conf,width,height,packet,profile)
{
	//Временно работаем только с 2х-камерными
	//packet=2;

	var changeArgs = {
		euro: $('#euro').val(),
		kbe58cost: $('#kbe58cost').val(),
		kbe70perc: $('#kbe70perc').val(),
		veka60perc: $('#veka60perc').val(),
		veka70perc: $('#veka70perc').val(),
		trocal70perc: $('#trocal70perc').val(),
		
		otkDoor: $('#otkDoor').val(),
		otkAl: $('#otkAl').val(),
		otk1: $('#otk1').val(),
		otk2: $('#otk2').val(),
		otk3: $('#otk3').val(),
		
		sillInd: $('#sillInd').val()
	}
	
	prices = calculate_window(conf,packet,width,height,profile,changeArgs);
	
	var timer,intv = 25,msecs = 1000;
	ticks = msecs/intv;
	
	var current = {
		wp: parseInt(removeSpaces($("#win_price").text())),
		tp: parseInt(removeSpaces($("#trim_price").text())),
		sp: parseInt(removeSpaces($("#sill_price").text())),
		ap: parseInt(removeSpaces($("#assembly_price").text()))
	}
	var newp = {
		wp: prices["win_price"]-current.wp,
		tp: prices["trim_price"]-current.tp,
		sp: prices["sill_price"]-current.sp,
		ap: prices["assembly_price"]-current.ap
	}
	var koef = {
		wp: newp.wp/ticks,
		tp: newp.tp/ticks,
		sp: newp.sp/ticks,
		ap: newp.ap/ticks
	}
	
	$(".block .loading").css('background-image', "url('/style/images/load-anim.gif')");
	timer = setInterval(function(){
		if (ticks<=0) 
		{
			clearInterval(timer);
			$(".block .loading").css('background-image', "url('/style/images/load-fixed.gif')");
		}
			$("#win_price").html(formatNum(Math.round(current.wp)));
			$("#trim_price").html(formatNum(Math.round(current.tp)));
			$("#sill_price").html(formatNum(Math.round(current.sp)));
			$("#assembly_price").html(formatNum(Math.round(current.ap)));
			current.wp += koef.wp;
			current.tp += koef.tp;
			current.sp += koef.sp;
			current.ap += koef.ap;
		ticks--;
	},intv);
	/*
	$("#win_price").html(formatNum(prices["win_price"]));
	$("#trim_price").html(formatNum(prices["trim_price"]));
	$("#sill_price").html(formatNum(prices["sill_price"]));
	$("#assembly_price").html(formatNum(prices["assembly_price"]));
	*/
}

//Форматирует число по разрядам
function formatNum(param){return (param+'').replace(/(\d\d\d$)/i,' $1');}

//Код инициализации слайдера значениями
function SliderStart(wmin, wmax, hmin, hmax)
{
	//уничтожаем слайдеры на всякий случай
	$("#swslider").slider('destroy');
	$("#shslider").slider('destroy');
	
	$(function() {
		$("#swslider").slider({
			animate: true,
			range: "min",
			step: 10,
			min: wmin,
			max: wmax,
			slide: function(event, ui) {
				width=ui.value;
				$('#swidth').val(formatNum(ui.value));
			},
			stop: function(event, ui) {
				width=ui.value;
				$('#swidth').val(formatNum(ui.value));
				calculate(conf,width,height,packet,profile);
			}

		});
		
		$("#shslider").slider({
			animate: true,
			range: "min",
			step: 10,
			min: hmin,
			max: hmax,
			slide: function(event, ui) {
				height=ui.value;
				$('#sheight').val(formatNum(height));
			},
			stop: function(event, ui) {
				height=ui.value;
				$('#sheight').val(formatNum(height));
				calculate(conf,width,height,packet,profile);
			}
		});
	});
}

//Устанавливает ограничения слайдеру.
function SetSliderRestrictions()
{
	//Временно работаем только с 2х-камерными	
	//packet=2;
	
	var restr = getRestrictions(conf,packet);
	width = restr.fWidth;
	height = restr.fHeight;
	SliderStart(restr.fWidth,restr.lWidth,restr.fHeight,restr.lHeight);
	$('#swidth').val(restr.fWidth);
	$('#sheight').val(restr.fHeight);
}

//удаление пробелов из строки
function removeSpaces(str)
{
	var allSpacesRe = /\s+/g;
	return str.replace(allSpacesRe, "");
}

