var Calc = {
	prices: "",								// объект с ценами
	timerId: "",							// идентификатор таймера	
	dspSize: "",							// толщина дсп
	sectionsCount: "",						// кол-во секций
	
	selDoors: "select[name*=doors_]",		// селектор дверей
	selCase: "input[name*=case_]",			// селектор параметров корпуса
	selSize: "input[name*=size_]",			// селектор размеров корпуса
	selDsp: "input[name=dsp_height]",		// селектор параметров ДСП
	selProfile: "input[name=profile_type]",	// селектор профиля
	selLists: "select[id*=list_]",			// селектор списочных свойств
	selOther: "#other_table select",		// выбор списка доп. опций
	aErrors: {},
	bError: false,
	iCalcCnt: 0,
	
	/**
	 * Инициализирует калькулятор
	 */
	init: function(prices)
	{
		if($.isEmptyObject(prices))
			return;
		
		this.prices = prices;
		this.defaultValues();	// заполняет форму дефолтными значениями
		this.calculate();		// считает цену
		this.bind();			// постановка обработчиков событий
	},
	
	/**
	 * Подвешивает обработчики событий на поля калькулятора
	 */
	bind: function()
	{
		var _this = this;
				
		/**
		 * Пересчет при изменении размеров шкафа
		 * пересчет производится по таймауту
		 */
		$(this.selSize).bind("keyup", function(event){
			Calc.curObj = this;
			if(Calc.timerId)
			{
				clearTimeout(Calc.timerId);
			};

			Calc.timerId = setTimeout('Calc.changeCaseSize(Calc.curObj)', 300);
		});
		
		/**
		 * пересчет при изменении параметров копуса (без левой стенки, без правой и тп)
		 */
		$(this.selCase).bind("click", function(event){
			_this.calculate();
		});
		
		/**
		 * Изменение толщины ДСП, если такая толщина найдена в конфиге пересчитывается сумма
		 */
		$(this.selDsp).bind("change", function(){
			if(_this.prices.dsp[this.value])
			{
				_this.dspSize = this.value;
				_this.calculate();
			}
		});
		
		/**
		 * Пересчет стоимости при изменении кол-ва секций или полок (внутренних)
		 */
		$(this.selLists).bind("change", function(){
			aId = this.id.split("_");
			key = aId[1] + "Count";
			_this[key] = parseInt(this.value, 10);
						
			_this.calculate();
		});
		
		
		/**
		 * Кол-во дверей или цвет материала
		 */
		$(this.selDoors).bind("change", function(){
			aId = this.name.split("_");

			if(!aId[2])
			{
				_this.checkMaxHeightByDoorMaterial(aId[1], this);
				_this.reBuildDoorList();
				
			}			
			_this.calculate();
		});
		
		/**
		 * Механизмы
		 */
		$(this.selProfile).each(function(){
			// изменение модели профиля
			$(this).bind("change", function(){
				$(this).parent().parent().parent().addClass('act').find("select").attr("disabled", false);
				$(this).parent().parent().parent().siblings().removeClass('act').find("select").attr("disabled", true);
				
				_this.checkMaxHeightByMachinery(this.value);			
				_this.calculate();
			});
			
			typeSelect = '#' + this.value + '_type';
			colorSelect = '#' + this.value + '_color';
			
			// изменение типа профиля
			$(typeSelect).bind("change", function(){
				aId = this.id.split("_");
				sId = "#" + this.id.replace("_type", "_color");
							
				_this.rebuildColors(this.value, sId, _this.prices.machinery[aId[0]].colors);
				_this.calculate();
			});
			
			// изменение цвета профиля
			$(colorSelect).bind("change", function(){
				_this.calculate();
			});
		});
		
		/**
		 * Дополнительные характеристики
		 */
		$("#other_table select").bind("change", function(){
			_this.calculate();
		});
	},
	
	/**
	 * 
	 */
	checkMaxHeightByDoorMaterial: function(materia, obj)
	{
		iValue = parseInt(obj.value, 10);
		
		aSize = this.GetSize();
		sError = "";
		sErrorId = "#door_errors";
		objMach = this.prices.doors[materia];
		id = "materia";
	
		if(!this.aErrors[sErrorId])
		{
			this.aErrors[sErrorId] = "";
		} else
		{
			this.aErrors[sErrorId].remove();
		}

		if(iValue > 0)
		{
			if(aSize.height > objMach.size.height)
			{
				sError = "Максимальная высота дверей для материала: " + objMach.name + " " + objMach.size.height + "мм";
				this.aErrors[sErrorId] = this.showError(sError, sErrorId, id);
			} else if(this.aErrors[sErrorId])
			{
				this.aErrors[sErrorId].remove();
				this.aErrors[sErrorId] = "";
			}
		}
	},
	
	/**
	 * Проверяет является ли высота шкафа для выбранного профиля допустимой
	 */
	checkMaxHeightByMachinery: function(type)
	{
		aSize = this.GetSize();
		sError = "";
		sErrorId = "#machinery_errors";
		objMach = this.prices.machinery[type];
		id = "machinery";
		
		if(this.aErrors[sErrorId])
		{
			this.aErrors[sErrorId].remove();
		} else
		{
			this.aErrors[sErrorId] = "";
		}
		
		if(aSize.height > objMach.size.height)
		{
			sError = "Максимальная высота дверей " + objMach.name + " " + objMach.size.height + "мм";
			this.aErrors[sErrorId] = this.showError(sError, sErrorId, id);
		} else if(this.aErrors[sErrorId])
		{
			this.aErrors[sErrorId].remove();
			this.aErrors[sErrorId] = "";
		}
	},
	
	/**
	 * Блокирует выбор дополнительных опций
	 * (свет, ящики и боковые полочки)
	 */
	blockOther: function()
	{
		$(this.selOther).attr("disabled", true);
	},
	
	/**
	 * Разблокирует выбор дополнительных опций
	 * (свет, ящики и боковые полочки)
	 */
	unblockOther: function()
	{
		$(this.selOther).attr("disabled", false);
	},
	
	/**
	 * Блокирует выбор секций и полок
	 */
	blockLists: function()
	{		
		$(this.selLists).attr("disabled", true);
	},
	
	/**
	 * Разблокировывает выбор кол-ва секций полок
	 */
	unblockLists: function()
	{
		$(this.selLists).attr("disabled", false);
	},
		
	/**
	 * Проверяет соответствует ли высота максимально разрешенной
	 */
	checkHeight: function()
	{
		sErrorId = "top_error";
		obj = this.prices.mainParams.size.height;
		id = "height";
		
		if(!this.aErrors[sErrorId])
		{
			this.aErrors[sErrorId] = {};
		}		
		if(this.aErrors[sErrorId]["height"])
		{
			this.aErrors[sErrorId]["height"].remove();
		}
		
		aSize = this.GetSize();
		if(aSize.height > this.detectMaxHeight())
		{
			sError = 'Неверно заполнен параметр: ' + obj.name + ' значение должно быть в диапазоне от ' + obj.min + ' до ' + obj.max;
			this.aErrors[sErrorId]["height"] = this.showError(sError, "#" + sErrorId, "height");
		}
	},
		
	/**
	 * Определяет максимальную высоту шкафа
	 */
	detectMaxHeight: function()
	{
		var _this = this;
		var height = this.prices.mainParams.size.height.max;
		
		$(this.selDoors).each(function(){
			aId = this.name.split("_");
	
			if(aId[2] > 0) return;			
			if(this.value > 0 && height > _this.prices.doors[aId[1]].size.height)
			{				
				height = _this.prices.doors[aId[1]].size.height;	
			}
		});
		
		$(this.selProfile).each(function(){
			if(this.checked && height > _this.prices.machinery[this.id].size.height)
			{
				height = _this.prices.machinery[this.id].size.height;
			}
		});
	
		return height;
	},
	
	/**
	 * Заполняет поля формы значениями по умолчанию
	 */
	defaultValues: function()
	{
		var _this = this;

		/**
		 * Размеры шкафа по умолчанию
		 */
		$("input[name*=size_]").each(function(){
			aId = this.id.split("_");
			
			if(_this.prices.mainParams[aId[0]][aId[1]].default_value)
			{
				$(this).attr("value", _this.prices.mainParams[aId[0]][aId[1]].default_value);
			};
		});
		
		/**
		 * Кол-во секций
		 */
		sectionId = "#list_sections";
		$(sectionId).empty();
		sSections = "";
		selected = "";
		
		for(i = this.prices.mainParams.sections.min; i <= this.prices.mainParams.sections.max; i++)
		{
			if(i == this.calcDefaultSections())
			{
				this.sectionsCount = i;
				selected = " selected";
			} else
			{
				selected = "";
			}
			
			sSections += '<option value="' + i + '"' + selected + '>' + i + '</option>';
		};
		
		$(sSections).appendTo(sectionId);
		sSections;
		
		/**
		 * Кол-во полок
		 */
		shelfId = "#list_shelf";
		$(shelfId).empty();
		sSections = "";
		selected = "";
		
		for(i = this.prices.mainParams.shelf.min; i <= this.prices.mainParams.shelf.max; i++)
		{
			if(i ==  this.prices.mainParams.shelf.default_value)
			{
				this.shelfCount = i;
				selected = " selected";
			} else
			{
				selected = "";
			}
			
			sSections += '<option value="' + i + '"' + selected + '>' + i + '</option>';
		};
		
		$(sSections).appendTo(shelfId);
		
		/**
		 * Толщина ДСП
		 */
		var checked = false;
		$("input[name*=dsp_]").each(function(){
			if(!_this.prices.dsp[this.value])
			{
				$(this).parent().parent().remove();
				return;
			}
			
			if(_this.prices.dsp[this.value]["default"] && !checked)
			{				
				_this.dspSize = this.value;
				this.checked = true;
				checked = true;
			} else
			{
				this.checked = false;
			}
		});
				
		/**
		 * Кол-во дверей и материалы
		 */
		this.iDoorCount = 0;
		$("select[name*=doors_]").each(function(){

			aId = this.name.split("_");
			if(aId[2])
			{
				return;
			}	
			
			if(!_this.prices.doors[aId[1]])
			{
				$(this).parent().parent().parent().remove();
			} else
			{			
				door = _this.prices.doors[aId[1]];
				
				/**
				 * Подсказки по типу дверей
				 */
				$("label[for=" + this.id + "]").find("span").attr("title", door.hint);
				$("label[for=" + this.id + "]").find("span").attr("alt", door.hint);
				
				// заполняем селекты значениями которые пользователь может выбрать
				sOpt = "";
				for(i = 0; i <= 5; i ++)
				{
					sOpt += '<option value="' + i + '">' + i + '</option>';
				}
				
				$(this).empty();
				$(sOpt).appendTo(this);
				
				// материалы
				obj = $(this).parent().parent().siblings();
				objSel = obj.find("select");
				if(!door.vars)
				{
					$("label[for=" + objSel.attr("id") + "]").remove();
					objSel.remove();
				} else
				{
					objSel.empty();
					sOpt = "";
					for(oVar in door.vars)
					{
						selected = '';
						if(door.vars[oVar]["default"])
						{
							selected = ' selected';
						}
						sOpt += '<option value="' + oVar + '"' + selected + '>' + door.vars[oVar].name + '</option>';
					}
					
					$(sOpt).appendTo(objSel);
				}
			}
		});
		
		/**
		 * Выбор профиля
		 */
		this.buildMachinery();
		
		/**
		 * Дополнительные опции
		 */
		$("#other_table").empty();
		for(val in this.prices.other)
		{
			sHtml = '<tr>'
						+ '<td><label for="opt14">' + this.prices.other[val].name + '</label></td>'
						+ '<td>'
						+ '<div class="err">'
						+	'<select class="small" name="' + val + '" id="opt14">';
			for(i = this.prices.other[val].min; i <= this.prices.other[val].max; i ++)
			{
				selected = "";
				if(i == this.prices.other[val]["default"])
				{
					selected = " selected";
				}
				sHtml += '<option value="' + i + '"' + selected + '>' + i + '</option>';
			}
			sHtml +=	'</select><span class="err-mess"><i></i><span class="err-inner">введите&nbsp;число&nbsp;дверей</span></span>'
					+ '</div>';										
			sHtml += '</td></tr>';
			
			$(sHtml).appendTo("#other_table");
		}
	},
	
	/**
	 * Уставновит новое значение кол-ва секций
	 */
	reSetSections: function()
	{
		_this = this;
		$("#list_sections").children().each(function(){
			if(this.value == _this.calcDefaultSections())
			{
				this.selected = true;
			} else
			{
				this.selected = false;
			}
		});
	},
	
	/**
	 * Перестраивает списко цветов для выбранного типа профиля
	 */
	rebuildColors: function(selectedType, objId, objColors)
	{
		$(objId).empty();
		sHtml = "";
		for(color in objColors)
		{
		
			if(objColors[color][selectedType] <= 0) continue;
			selected = "";
			if(objColors[color][selectedType]["default"])
			{
				selected = " selected";
			}
			sHtml += '<option value="' + color + '"' + selected + '>' + objColors[color]["name"] + '</option>';
		}

		$(sHtml).appendTo(objId);		
	},
	
	/**
	 * Строит выбор механизмов и их цветов
	 */
	buildMachinery: function()
	{
		obj = $("table.type tr");
		obj.empty();
		for(type in this.prices.machinery)
		{
			typeId = type;
			objType = this.prices.machinery[type];
			tdObj = $("<td></td>").appendTo(obj);
			obj.find('td').first().addClass('act');
			
			sHtml = "";					
			sHtml += '<label for="' + type + '">';
			if(objType.img)
			{
				sHtml += '<img src="' + objType.img + '" alt="" class="inact"/><img src="' + objType.img2 + '" alt="" class="act"/>';
			}
			
		
			checked = "";
			if(objType.is_default)
			{
				checked = " checked";				
			}
			
			sHtml += '<span class="row"><input type="radio" value="' + type + '" name="profile_type" id="' + type + '"' + checked + '/> ' + objType.name + ' <span class="q" title="' + objType.hint + '"></span></span>';
			sHtml += '</label>';
			
			$(sHtml).appendTo(tdObj);
			
			//выбор типа			
			selectName = typeId + '_type';
			sHtml = '<select name="' + selectName + '" id="' + selectName + '">';
			cnt = 0;
			for(type in objType.types)
			{
				if(!cnt)
				{
					sHtml += '<option disabled="disabled">--- Форма ручки ---</option>';
				}
				selected = "";
				if(objType.types[type]["default"])
				{
					selectedType = type;
					selected = " selected";
				}
				sHtml += '<option value="' + type + '"' + selected + '>' + objType.types[type].name + '</option>';
				cnt ++;
			}
			sHtml += '</select>';
			$(sHtml).appendTo(tdObj);
			
			// цвета
			sHtml = "";
			selectName = typeId + '_color';
			sHtml = '<select name="' + selectName +'" id="' + selectName + '">';
			cnt = 0;

			for(color in objType.colors)
			{
				objColor = objType.colors[color];
				
				if(objColor[selectedType] <= 0) continue;
				
				if(!cnt)
				{
					sHtml += '<option disabled="disabled">--- Цвет ручки ---</option>';
				}
				
				selected = "";
				if(objColor["default"])
				{
					selected = " selected";
				}
				
				sHtml += '';
				
				sHtml += '<option value="' + color + '"' + selected + '>' + objColor.name + '</option>';
				cnt ++;
			}
			
			sHtml += '</select>';			
			$(sHtml).appendTo(tdObj);			
			
			if(!objType.is_default)
			{
				tdObj.find("select").attr("disabled", true);
			}
		}
	},
	
	/**
	 * Вернет кол-во секций которое устанавливается по умолчанию
	 */
	calcDefaultSections: function()
	{
		if(this.prices.mainParams.sections.default_value > 0)
			return this.prices.mainParams.sections.default_value;
		
		aSize = this.GetSize();
		return Math.ceil(aSize.width / 800);
	},
	
	/**
	 * Проверяет является ли значение размера допустимым
	 * если нет выводятся ошибки
	 * если размеры допустимые идет дальнейшая обработка
	 */
	changeCaseSize: function(obj)
	{
		if($.isEmptyObject(obj))
			return false;
		
		aId = obj.id.split("_");
		name = aId[1];
		sErrorId = "top_error";
		
		if(!this.aErrors[sErrorId])
		{
			this.aErrors[sErrorId] = {};
		}
		
		
		// приводим к числу
		obj.value = parseInt(obj.value, 10);		
		if(isNaN(obj.value))
			obj.value = 0;
				 
		if(!this.prices.mainParams[aId[0]][name])
			return;
		
		objParam = this.prices.mainParams[aId[0]][name];
		bError = false;
		// проверка на допустимое минимальное и максимальное значения
		if((objParam.min && objParam.min > obj.value) || (objParam.max && objParam.max < obj.value))
		{
			bError = true;
		}
			
		if(bError)
		{
			if(this.aErrors[sErrorId][name])
			{
				$(this.aErrors[sErrorId][name]).remove();
			}
			
			sError = 'Неверно заполнен параметр: ' + objParam.name + ' значение должно быть в диапазоне от ' + objParam.min + ' до ' + objParam.max;
			this.aErrors[sErrorId][name] = this.showError(sError, "#top_error", name);		
			
		} else if(this.aErrors[sErrorId][name])
		{
			this.aErrors[sErrorId][name].remove();
			delete this.aErrors[sErrorId][name];
		}
		
		// пересчет только в том случае если ошибок не было найденно
		if(!bError)
		{
			// меняем заголовок
			if(name == "deep" && obj.value <= 150)
			{
				$("h1").html("Расчет дверей купе");
				this.blockLists();	// блокируем выбор кол-ва полок и перегородок
				this.blockOther();	// блокируем выбор доп. опций
				
			} else if(name == "deep" && obj.value > 150)
			{
				$("h1").html("Расчета шкафа купе");
				
				this.unblockLists();	// разблокировываем выбор кол-ва полок и перегородок
				this.unblockOther();	// разблокировываем выбор доп. параметров		
			}
			
			this.reSetSections();
			this.calculate();
		}
		
		this.bError = bError;
	},
	
	showError: function(sError, where, id)
	{
		return $('<span id="error_'+ id +'">' + sError + '</span><br />').appendTo(where);
	},
		
	/**
	 * Функция вернет объект содержащий значения размера шкафа
	 * свойства - width, height, deep
	 */
	GetSize: function()
	{
		var size = {};
		
		$("input[name*=size_]").each(function(){
			aId = this.name.split("_");
			
			size[aId[1]] = parseInt(this.value, 10);
		});
		
		return size;
	},
	
	/**
	 * Вернет объект содержащий параметры копуса шкафа
	 * свойства left, right, floor, roof
	 */
	GetParams: function()
	{
		var aParams = {};
		$(this.selCase).each(function(){
			aName = this.name.split("_");
			aParams[aName[1]] = this.checked;
		});
		
		return aParams;
	},
	
	/**
	 * Вернет размер ДСП который выбран сейчас
	 */
	GetDSPSize: function()
	{
		return this.dspSize;
	},
			
	/**
	 * Установит цену в форму
	 */
	setPrice: function(iPrice)
	{
		$(".total span").html(this.formatPrice(Math.ceil(iPrice)));
	},
	
	/**
	 * Форматирует цену в соответствии с дизайном
	 */
	formatPrice: function(iPrice)
	{
		var iPrice = new String(iPrice);
		
		sPrice = "";
		len = iPrice.length - 1;
		cnt = 0;
		for(i = len; i >= 0; i --)
		{
			if(cnt && cnt % 3 == 0)
				sPrice = '.' + sPrice;

			sPrice = iPrice.charAt(i) + sPrice;
			cnt ++;
		}

		return sPrice;
	},
	
	/**
	 * Расчитывает максимальное кол-во дверей которое может выбрать пользователь
	 */
	getMaxDoors: function()
	{
		aSize = this.GetSize();
		
		return Math.ceil(aSize.width / this.prices.mainParams.doorMinSize);
	},
	
	/**
	 * Метод вызывается при изменении кол-ва дверей
	 * отвечает за правильный выбор пользователем кол-ва дверей
	 */
	reBuildDoorList: function()
	{
		var iDoorMax = this.getMaxDoors();
		var iCnt = 0;
		
		$(this.selDoors).each(function(){
			aId = this.name.split("_");
			if(!aId[2])
			{
				iCnt += parseInt(this.value, 10);
			}
		});
	
		sErrorId = "door_errors";
		if(!this.aErrors[sErrorId])
		{
			this.aErrors[sErrorId] = new Object;
		}
		
		if(iCnt > iDoorMax)
		{
			sError = "Превышенно максимальное кол-во дверей, дверей должно быть не более " + iDoorMax;
			this.aErrors[sErrorId] = this.showError(sError, "#" + sErrorId, "doors")
		} else if(!$.isEmptyObject(this.aErrors[sErrorId]))
		{
			this.aErrors[sErrorId].remove();
		}
	},
	
	/**
	 * Пересчет стоимости шкафа
	 */
	calculate: function()
	{
		iSumm = "";
		
		aSize = this.GetSize();
		dspPrice = this.prices.dsp[this.GetDSPSize()].price;
		edgePrice = this.prices.dsp[this.GetDSPSize()].edge;
		
		if(this.GetDSPSize() == 16)
		{
			edgePriceInner = this.prices.edge[this.GetDSPSize() + "_inner"].price;
		} else
		{
			edgePriceInner = edgePrice;
		}
		
		aParams = this.GetParams();
		
		/**
		 * Корпус
		 */	
		sizePrice = FCalc.calcSize(
			aSize,
			dspPrice,
			edgePrice,
			aParams,
			this.prices,
			edgePriceInner
		);
		
		iSumm = sizePrice;
		
		/**
		 * Секции
		 */
		if(this.getSections() && aSize.deep > 150)
		{
			sectionPrice = FCalc.calcSection(
				aSize.height,
				aSize.deep,
				dspPrice,
				edgePriceInner,
				aParams
			);
			
			sectionsPrice = sectionPrice * (this.getSections() - 1);

			iSumm = iSumm + sectionsPrice;
		}
		
		/**
		 * Полки (внутренние)
		 */
		shelfPrice = FCalc.calcShelf(aSize.width, aSize.deep, dspPrice, edgePriceInner, aParams);
		iSumm = iSumm + (shelfPrice * this.shelfCount);
				
		/**
		 * Цоколь
		 */
		if(aSize.deep > 150)
		{
			iSumm = iSumm + (FCalc.calcCocol(aSize.width, dspPrice, edgePriceInner, aParams) * 2);
		}
		
		/**
		 * Двери
		 */
		aDoors = this.getDoors();
		aProfile = this.getProfile();
		
		iSumm = iSumm + FCalc.calcDoors(aSize, aDoors, aProfile, this.prices);
		
		/**
		 * Светильники, ящики и боковые полки
		 */
		aOther = this.getOtherParams();
		iSumm = iSumm + FCalc.calcOther(aOther, this.prices, aSize);
		
		/**
		 * Установка
		 */
		iSumm = iSumm + FCalc.calcInstallation(iSumm, this.prices);
		
		/**
		 * Доставка
		 */
		iSumm = iSumm + this.prices.delivery;
		iSumm = iSumm * this.prices.cooficient;
		
		this.setPrice(iSumm);
	},
	
	/**
	 * Вернет объект содержащий значения дополнительных параметров
	 * (кол-во боковых полочек, ящики и свет)
	 */
	getOtherParams: function()
	{
		aOther = {};
		$("#other_table select").each(function(){
			aOther[this.name] = this.value;
		});
		
		return aOther;
	},
	
	/**
	 * Вернет объект с параметрами дверей (кол-во, цвет)
	 */
	getDoors: function()
	{				
		aDoors = {};
		
		$(this.selDoors).each(function(){
			aId = this.name.split("_");
			
			if(!aId[2])
			{
				aDoors[aId[1]] = {
					"count": parseInt(this.value, 10),
					"color": ""
				};
			} else
			{
				aDoors[aId[1]]["color"] = this.value;
			}
		});
		
		return aDoors;
	},
	
	/**
	 * Вернет объект содержащий параметры профиля
	 */
	getProfile: function()
	{
		var aProfile = {};
		$(this.selProfile).each(function(){
			if(this.checked)
			{
				aProfile = {
					"name": this.value,
					"type": $("#" + this.id + "_type").attr("value"),
					"color": $("#" + this.id + "_color").attr("value")
				};
			}
		});
		
		return aProfile;
	},
	
	/**
	 * Вернет кол-во секций
	 */
	getSections: function()
	{
		return $("#list_sections").attr("value");
	}
};

var FCalc = {
	
	/**
	 * Расчет корпуса шкафа
	 */
	calcSize: function(aSize, dspPrice, edgePrice, aParams, aPrices, edgePriceInner)
	{		
		sum = 0;	
		// расчет шкафа
		if(aSize.deep > 150)
		{
			// левая стенка
			if(aParams.left)
			{
				sum += this.calcWall(aSize.height, 100, dspPrice, edgePrice, edgePriceInner);
			} else
			{
				sum += this.calcWall(aSize.height, aSize.deep, dspPrice, edgePrice, 0);
			}
			
			// правая стенка
			if(aParams.right)
			{
				sum += this.calcWall(aSize.height, 100, dspPrice, edgePrice, edgePriceInner);
			} else
			{
				sum += this.calcWall(aSize.height, aSize.deep, dspPrice, edgePrice, 0);
			}
			
			// пол
			if(aParams.floor)
			{
				sum += this.calcFloor(aSize.width - (Calc.GetDSPSize() * 2), 100, dspPrice, edgePrice, edgePriceInner);
			} else
			{
				sum += this.calcFloor(aSize.width - (Calc.GetDSPSize() * 2), aSize.deep, dspPrice, edgePrice, 0);
			}
			
			// крыша
			if(aParams.roof)
			{
				sum += this.calcFloor(aSize.width - (Calc.GetDSPSize() * 2), 100, dspPrice, edgePrice, edgePriceInner);
			} else
			{
				sum += this.calcFloor(aSize.width - (Calc.GetDSPSize() * 2), aSize.deep, dspPrice, edgePrice, 0);
			}
			
			/**
			 * Если не убраны стенки плюсуем оргалит
			 */
			if((!aParams.floor && !aParams.roof && !aParams.left && !aParams.right))
			{
				sum += this.calcHardboard(aSize, aPrices);
			}
		} else
		{
			// расчет дверей купе
			if(!aParams.left)
			{
				sum += this.calcWall(aSize.height, 100, dspPrice, edgePrice, edgePriceInner);
			}
			
			if(!aParams.right)
			{
				sum += this.calcWall(aSize.height, 100, dspPrice, edgePrice, edgePriceInner);
			}
			
			if(!aParams.floor)
			{
				sum += this.calcFloor(aSize.width - (Calc.GetDSPSize() * 2), 100, dspPrice, edgePrice, edgePriceInner);
			}
			
			if(!aParams.roof)
			{
				sum += this.calcFloor(aSize.width - (Calc.GetDSPSize() * 2), 100, dspPrice, edgePrice, edgePriceInner);
			}
		}
		
		return sum;		
	},
	
	/**
	 * Расчет задней стенки
	 */
	calcHardboard: function(aSize, aPrices)
	{
		return parseInt(this.calcSquareMeter(aSize.height, aSize.width) * aPrices.hardboard, 10);
	},
	
	/**
	 * Расчет стоимости 1 секции (перегородки)
	 */
	calcSection: function(height, deep, dspPrice, edgePrice, aParams)
	{
		if(!aParams.floor)
		{
			height = height - 70;
		}
		deep = deep - 100;
		
		
		return ((this.calcSquareMeter(height, deep) * dspPrice) + (edgePrice * this.calcSquareMeter(height)));
	},
	
	/**
	 * Расчет стоимость крышки или пола
	 */
	calcFloor: function(width, deep, dspPrice, edgePrice, edgePriceInner)
	{
		price = ((this.calcSquareMeter(width, deep) * dspPrice) + (edgePrice * this.calcSquareMeter(width)));
		if(edgePriceInner)
		{
			price += edgePriceInner * this.calcSquareMeter(width);
		}
		
		return price;
	},
		
	/**
	 * Расчет стоимости одной боковой стенки
	 */
	calcWall: function(height, deep, dspPrice, edgePrice, edgePriceInner)
	{
		price = (this.calcSquareMeter(height, deep) * dspPrice + edgePrice * this.calcSquareMeter(height));
		
		if(edgePriceInner)
		{
			price += edgePriceInner * this.calcSquareMeter(height);
		}
		
		return price;
	},
	
	/**
	 * Расчет стоимости цоколя
	 */
	calcCocol: function(width, dspPrice, edgePrice, aParams)
	{
		if(aParams.floor)
			return 0;
	
		price = ((this.calcSquareMeter(width, 50) * dspPrice) + (this.calcSquareMeter(width) * edgePrice));
		return price;
	},
	
	/**
	 * Расчитывает стоимость 1 полки
	 */
	calcShelf: function(width, deep, dspPrice, edgePrice, aParams)
	{
		sectionsCount = Calc.getSections();
		iSections = sectionsCount - 1;
		iDeep = deep - 105;
		iWidth = 0;
		
		if(!aParams.left && !aParams.right)
		{// если есть боковые стенки
			iWidth = width - ((Calc.GetDSPSize() * 2) + (Calc.GetDSPSize() * iSections));
								
		} else if(aParams.left && aParams.right)
		{// если нет обеих боковых стенок
			iWidth = width - (Calc.GetDSPSize() * iSections);
		} else
		{// если есть хотя бы одна стенка
			iWidth = width - Calc.GetDSPSize() * 1 - Calc.GetDSPSize() * iSections;
		}
		
		if(sectionsCount > 1)
			iWidth = iWidth / sectionsCount;

		price = (this.calcSquareMeter(iWidth, iDeep) * dspPrice) + (this.calcSquareMeter(iWidth) * edgePrice);
				
		return price;
	},
	
	/**
	 * Считает стоимость дверей
	 */
	calcDoors: function(aSize, aDoors, aProfile, aPrices)
	{
		cntDoors = 0;
		width = aSize.width;
		for(door in aDoors)
		{
			cntDoors = cntDoors + aDoors[door].count;
		}
		
		if(cntDoors <= 0)
		{
			return 0;
		}
		
		doorWidth = Math.ceil(width / cntDoors);
		iSumm = 0;
		
		// корректируем размеры дверей
		for(door in aDoors)
		{
			if(aDoors[door].count > 0)
			{
				if(doorWidth > aPrices["doors"][door]["size"]["width"])
				{
					iDoor = Math.ceil((aPrices["doors"][door]["size"]["width"] * aDoors[door].count));
					width = width - iDoor;
					doorWidth = Math.ceil(width / cntDoors);
					aDoors[door].width = iDoor;
					aDoors[door].height = aSize.height;
				} else
				{
					aDoors[door].width = doorWidth;
					aDoors[door].height = aSize.height;
				}
				aDoors[door].type = door;
				
				iPrice = 0;
				
				switch(aDoors[door].type)
				{
					case("dsp"):
						if(aDoors[door].width <= 1000)
						{
							iPrice += parseInt(aPrices.doors[aDoors[door].type].vars.small, 10);
						} else
						{
							iPrice += parseInt(aPrices.doors[aDoors[door].type].vars.full, 10);
						}			
						break;
						
					case("rotang"):
						iPrice += parseInt(aPrices.doors[aDoors[door].type].vars.price, 10);
						break;
						
					default:
						iPrice = this.calcSquareMeter(aDoors[door].width, aDoors[door].height) * aPrices.doors[aDoors[door].type].vars[aDoors[door].color].price;
						break;
				}
				
				iPrice = iPrice * aDoors[door].count;
				
				iProfilePrice = parseInt(aPrices.machinery[aProfile.name].colors[aProfile.color][aProfile.type], 10);
				iPrice += iProfilePrice * aDoors[door].count;
								
				iSumm = iSumm + iPrice;
			}
		}
		
		return iSumm;
	},
	
	/**
	 * Расчет дополнительных параметров
	 * боковых полочек, ящиков и светильников
	 */
	calcOther: function(aOther, aPrices, aSize)
	{
		iPrice = 0;
		
		for(name in aOther)
		{
			val = aOther[name];
			if(aOther[name] > 0)
			{
				switch(name)
				{
					// светильники
					case("light"):
						iPrice += parseInt(aPrices.other.light.price[val], 10);
						break;
					
					// ящики
					case("smallbox"):
					case("bigbox"):
						iPrice += (parseInt(aPrices.other[name].price, 10) * val);
						break;
						
					case("shelf"):
						iPrice += this.calcLateralShelf(aSize, aPrices, val);
						break;
				}
			}
		}
		
		return iPrice;
	},
	
	calcInstallation: function(iPrice, aPrices)
	{
		return ((iPrice / 100) * aPrices.installation);
	},
	
	/**
	 * Расчет стоимости боковых полок
	 */
	calcLateralShelf: function(aSize, aPrices, count)
	{
		iPrice = 0;
		dspSize = Calc.GetDSPSize();
		count = parseInt(count, 10);
		
		if(!count)
		{
			return iPrice;
		}
		
		/**
		 * Задняя стенка
		 */
		iPrice += (this.calcSquareMeter(aSize.height, 350) * aPrices.dsp[dspSize].price); // дсп
		iPrice += (this.calcSquareMeter(aSize.height) * aPrices.edge[dspSize].price); // кромка
		
		/**
		 * Полки
		 */		
		iPrice += (this.calcSquareMeter(aSize.deep, 350) * aPrices.dsp[dspSize].price * count);
		iPrice += (this.calcSquareMeter(aSize.deep) * aPrices.edge[dspSize].price * count);
		iPrice += (this.calcSquareMeter(350) * aPrices.edge[dspSize].price * count);
		
		iPrice += (count * aPrices.other.shelf.price.sketch);
				
		return parseInt(iPrice, 10);
	},
		
	/**
	 * Пересчитывает миллиметры в метры или квадратные метры если заданно два значения
	 */
	calcSquareMeter: function(first, second)
	{
		if(second)
			return ((first / 1000) * (second / 1000));
		else
			return (first / 1000);
	}
};

var CTools = {
	
	/**
	 * Проверяет является ли нажатая кнопка числом или служебной разрешенной клавишей
	 */
	isIntKey: function(keyCode)
	{
		if((keyCode >= 48 && keyCode <= 57) || (keyCode >=96 && keyCode <=105))
		{
			return true;
		}
		return this.isAllowKey(keyCode);
	},
	
	/**
	 * Проверяет является ли нажатая кнопка разрещенной (служебной)
	 */
	isAllowKey: function(keyCode)
	{
		switch(keyCode)
		{
			case(46):	// delete
			case(8):	// backspace
				return true;
			break;
		}
		
		return false;
	}
};

$("body").ready(function(){
	Calc.init(CalcPrices);
});
