var defaultWidth = 700;
var defaultHeight = 1400;
var defaultHeightDoor = 2200;
var minFrameWidth = 300;
var maxFrameWidth = 10000;
var minHeight = 200;
var maxHeight = 3000;
var minWinWidth = 100;
var maxWinWidth = 3000;

var t1 = new Image; t1.src = 'assets/img/prices/t1.gif';
var t2 = new Image; t2.src = 'assets/img/prices/t2.gif';
var t3 = new Image; t3.src = 'assets/img/prices/t3.gif';
var t4 = new Image; t4.src = 'assets/img/prices/t4.gif';
var b1 = new Image; b1.src = 'assets/img/prices/b1.gif';
var b2 = new Image; b2.src = 'assets/img/prices/b2.gif';
var b3 = new Image; b3.src = 'assets/img/prices/b3.gif';
var b4 = new Image; b4.src = 'assets/img/prices/b4.gif';
var wt1 = new Image; wt1.src = 'assets/img/prices/wt1.gif';
var wt2 = new Image; wt2.src = 'assets/img/prices/wt2.gif';
var wt3 = new Image; wt3.src = 'assets/img/prices/wt3.gif';
var wt4 = new Image; wt4.src = 'assets/img/prices/wt4.gif';
var wb1 = new Image; wb1.src = 'assets/img/prices/wb1.gif';
var wb2 = new Image; wb2.src = 'assets/img/prices/wb2.gif';
var wb3 = new Image; wb3.src = 'assets/img/prices/wb3.gif';
var wb4 = new Image; wb4.src = 'assets/img/prices/wb4.gif';
var bbg = new Image; bbg.src = 'assets/img/prices/bbg.gif';

var win0 = new Image; win0.src = 'assets/img/prices/win_0.gif';
var win1_0 = new Image; win1_0.src = 'assets/img/prices/win_1.gif';
var win1_1 = new Image; win1_1.src = 'assets/img/prices/win_1_1.gif';
var win1_2 = new Image; win1_2.src = 'assets/img/prices/win_1_2.gif';
var win2_0 = new Image; win2_0.src = 'assets/img/prices/win_2.gif';
var win2_1 = new Image; win2_1.src = 'assets/img/prices/win_2_1.gif';
var win2_2 = new Image; win2_2.src = 'assets/img/prices/win_2_2.gif';
var win31_0 = new Image; win31_0.src = 'assets/img/prices/win_31.gif';
var win31_1 = new Image; win31_1.src = 'assets/img/prices/win_31_1.gif';
var win31_2 = new Image; win31_2.src = 'assets/img/prices/win_31_2.gif';
var win32_0 = new Image; win32_0.src = 'assets/img/prices/win_32.gif';
var win32_1 = new Image; win32_1.src = 'assets/img/prices/win_32_1.gif';
var win32_2 = new Image; win32_2.src = 'assets/img/prices/win_32_2.gif';

function ccFrame (type, width, height, windows, customset) {
	this.type = type;
	this.width = width;
	this.height = height;
	this.windows = windows;
	this.customset = customset;
	return this
}

function ccWindow (type, width, customset) {
	this.type = type;
	this.width = width;
	this.customset = customset;
	return this
}

function ccAccessory (name, width, height, qty, price, priceType) {
	this.name = name;
	this.width = width;
	this.height = height;
	this.qty = qty;
	this.price = price;
	this.priceType = priceType;
	return this
}

function ccAccessoryPrice (name, priceType, qty, price) {
	this.name = name;
	this.priceType = priceType;
	this.qty = qty;
	this.price = price;
	return this
}

function ccSystem (id, name, kasa, delitel, krilo_prozorec, krilo_vrata, obkov_prozorec_ed, obkov_prozorec_dv, obkov_vrata_ed, obkov_vrata_dv, delitel_br, trud) {
	this.id = id;
	this.name = name;
	this.kasa = kasa;
	this.delitel = delitel;
	this.krilo_prozorec = krilo_prozorec;
	this.krilo_vrata = krilo_vrata;
	this.obkov_prozorec_ed = obkov_prozorec_ed;
	this.obkov_prozorec_dv = obkov_prozorec_dv;
	this.obkov_vrata_ed = obkov_vrata_ed;
	this.obkov_vrata_dv = obkov_vrata_dv;
	this.delitel_br = delitel_br;
	this.trud = trud;
	return this
}

function ccFramePrice (windows, system, glass, width, height, area, price) {
	this.windows = windows;
	this.system = system;
	this.glass = glass;
	this.width = width;
	this.height = height;
	this.area = area;
	this.price = price;
	return this
}

var frameArray = new Array();
var frameArrayPrice = new Array();
var frameAccessoryPrice = new Array();
var frameSelected = null;
var frameType = 0;
var accessoryArray = new Array();
var bpFrameObj = null;
var bpFrameIndex = null;
var bpWinObj = null;
var bpWinIndex = null;
var bpWinParentIndex = null;
var TotalPrice = 0;
/*
var systemArray = new Array();
systemArray[382] = new ccSystem ('382', 'Кьомерлинг 5К 70 мм бял', '15', '15', '15', '45', '38.5', '20', '246', '0', '15', '21');
systemArray[383] = new ccSystem ('383', 'Кьомерлинг 5К 70 мм цветен', '23', '23', '23', '55', '38.5', '20', '246', '0', '15', '21');
systemArray[384] = new ccSystem ('384', 'KBE 3К 60 мм бял', '12', '12', '12', '30', '38.5', '20', '246', '0', '15', '21');
systemArray[385] = new ccSystem ('385', 'KBE 3К 60 мм цветен', '20', '20', '20', '45', '38.5', '20', '246', '0', '15', '21');
systemArray[386] = new ccSystem ('386', 'KMG 3К 60 мм бял', '9.5', '11', '9.5', '20', '38.5', '20', '246', '0', '12', '21');
systemArray[387] = new ccSystem ('387', 'KMG 3К 60 мм цветен', '17.5', '19', '17.5', '32', '38.5', '20', '246', '0', '12', '21');
*/
function frameClick (sender, count, type) {
	if (frameSelected == sender) {
		frameDeselect(sender);
		frameCustomFill(0);
		frameSelected = null;
		frameType = 0;
	} else {
		if (frameSelected != null) frameDeselect(frameSelected);
		frameSelect(sender);
		frameCustomFill(count, type);
		frameSelected = sender;
		frameType = type;
	}
}

function frameDoubleClick (sender, count, type) {
	frameAdd(count, type);
	if (frameSelected != null) frameDeselect(frameSelected);
	frameSelected = null;
	frameType = 0;
}

function frameSelect(sender) {
	sender.className = 'frameSelected';
}

function frameDeselect(sender) {
	sender.className = 'frameNormal';
}

function frameCustomFill(count, type) {
	if (count == 0) {
		document.getElementById('editFrameCount').value = '';

	} else {
		document.getElementById('editFrameCount').value = count;
		if (type == 1) {
			document.getElementById('radioDoor').checked = true;
		} else {
			document.getElementById('radiowindow').checked = true;
		}
	}
}

function frameButtonAdd() {
	var value = document.getElementById('editFrameCount').value;
	if (!isNaN(value) && value >=1 && value <=10) {
		if (document.getElementById('radioDoor').checked == true) {
			frameAdd(value, 1);
		} else {
			frameAdd(value, 0);
		}
	}
	document.getElementById('editFrameCount').value = '';
	if (frameSelected != null) frameDeselect(frameSelected);
	frameSelected = null;
	frameType = 0;

}

function frameAdd(count, type) {
	if ((count >=1) && (count <=10) && (frameArray.length <= 20)) {
		var winArray = new Array();
		for (i=0; i<count; i++) {
			var tmpWindow = new ccWindow(0, defaultWidth, false);
			winArray[winArray.length] = tmpWindow;
		}
		var tmpHeight = 0;
		if (type == 1) {
			tmpHeight = defaultHeightDoor;
		} else {
			tmpHeight = defaultHeight;
		}
		var tmpFrame = new ccFrame(type, getFrameWidth(winArray),tmpHeight , winArray, 0);
		frameArray[frameArray.length] = tmpFrame;
		bpFrameIndex = frameArray.length - 1;
		widthObj = document.getElementById('editWidth');
		heightObj = document.getElementById('editHeight');
		widthObj.value = frameArray[frameArray.length - 1].width;
		heightObj.value = frameArray[frameArray.length - 1].height;
		bpWinObj = null;
		bpWinIndex = null;
		bpWinParentIndex = null;
	}
	Display();
}

function getFrameWidth(winArray) {
	var tmpWidth = 0;
	for (i=0; i<winArray.length; i++) {
		tmpWidth = Number(winArray[i].width) + Number(tmpWidth);
	}
	return tmpWidth;
}

function Display() {
	var tmpStr = '<table id="blueprintTable" border="0" cellspacing="0" cellpadding="0"><tr>';
	for (i=0; i<frameArray.length; i++) {
		tmpStr += '<td valign="top">';
		tmpStr += drawFrame(frameArray[i], i);
		tmpStr += '<\/td>';
	}
	tmpStr += '<\/tr><\/table>';
	document.getElementById('blueprint').innerHTML = tmpStr;
	if ((bpWinIndex != null) && (bpWinParentIndex != null)) {
		bpWinObj = document.getElementById('win_' + bpWinParentIndex + '_' + bpWinIndex);
	}
	if (bpFrameIndex != null) {
		bpFrameObj = document.getElementById('frame_' + bpFrameIndex);
	}
	calculatePrice();
}

function calculatePrice() {
	var sistemaObj = document.getElementById('editSistema');
	var sistemaId = sistemaObj.options[sistemaObj.selectedIndex].value;
	var styklopaketObj = document.getElementById('editStyklopaket');
	var styklopaketPrice = styklopaketObj.options[styklopaketObj.selectedIndex].value;
	var tmpPriceTotal = 0;
	var tmpPriceStr = '';
	var tmpPriceStrForPdf ='';
	frameArrayPrice = new Array();

	if ((frameArray.length == 0) && (accessoryArray.length == 0)) {
		document.getElementById('orderTable').innerHTML = 'няма направена поръчка';
		return;
	}
	if (frameArray.length > 0) {
		tmpPriceStr += '<div class="title">Дограма:<\/div>';
		tmpPriceStr += '<table border="1" cellspacing="0" cellpadding="2">';
		tmpPriceStr += '<tr><td width="20" class="headrow">№<\/td>';
		tmpPriceStr += '<td class="headrow">Система<\/td>';
		tmpPriceStr += '<td class="headrow">Стъклопакет<\/td>';
		
		tmpPriceStr += '<td class="headrow">Височина [mm]<\/td>';
		tmpPriceStr += '<td class="headrow">Ширина [mm]<\/td>';
		tmpPriceStr += '<td width="50" class="headrow">Площ [кв. м.]<\/td>';
		tmpPriceStr += '<td width="80" class="headrow">Количество<\/td>';
		//tmpPriceStr += '<td width="75" class="headrow">Цена<\/td>';
		tmpPriceStr += '<td width="21">&nbsp;<\/td>';
		tmpPriceStr += '<\/tr>';
		
		for (k=0; k<frameArray.length; k++) {
			frameArray[k].width = getFrameWidth(frameArray[k].windows);
			var tmpRamkaArea = Number(frameArray[k].width * frameArray[k].height / 1000000);
			var tmpRamkaLength = Number((2 * frameArray[k].width / 1000) + (2 * frameArray[k].height / 1000));
			var tmpDeliteliNum = Number(frameArray[k].windows.length - 1);
			var tmpDeliteliLength = Number((frameArray[k].windows.length - 1) * (frameArray[k].height / 1000));
			var tmpRamkaOpenLengthDoor = 0;
			var tmpRamkaOpenLengthWindow = 0;
			var tmpOtvarjaemostWindowSingle = 0;
			var tmpOtvarjaemostWindowDouble = 0;
			var tmpOtvarjaemostDoorSingle = 0;
			var tmpOtvarjaemostDoorDouble = 0;
			var tmpRamkaPrice = 0;

			for (l=0; l<frameArray[k].windows.length; l++) {
				if (frameArray[k].windows[l].type != 0 ) {
					if (frameArray[k].type == 0) {
						tmpRamkaOpenLengthWindow += Number((2 * frameArray[k].windows[l].width / 1000) + (2 * frameArray[k].height / 1000));
					} else {
						tmpRamkaOpenLengthDoor += Number((2 * frameArray[k].windows[l].width / 1000) + (2 * frameArray[k].height / 1000));
					}
					if ((frameArray[k].windows[l].type == 1) || (frameArray[k].windows[l].type == 2)) {
						if (frameArray[k].type == 0) {
							tmpOtvarjaemostWindowSingle++;
						} else {
							tmpOtvarjaemostDoorSingle++;
						}
					} else if ((frameArray[k].windows[l].type == 31) || (frameArray[k].windows[l].type == 32)) {
						if (frameArray[k].type == 0) {
							tmpOtvarjaemostWindowSingle++;
							tmpOtvarjaemostWindowDouble++;
						} else {
							tmpOtvarjaemostDoorDouble++;
						}
					}
				}
			}

			tmpRamkaPrice += tmpRamkaLength * Number(systemArray[sistemaId].kasa);
			tmpRamkaPrice += tmpDeliteliNum * Number(systemArray[sistemaId].delitel_br);
			tmpRamkaPrice += tmpDeliteliLength * Number(systemArray[sistemaId].delitel);
			tmpRamkaPrice += tmpRamkaOpenLengthWindow * Number(systemArray[sistemaId].krilo_prozorec);
			tmpRamkaPrice += tmpRamkaOpenLengthDoor * Number(systemArray[sistemaId].krilo_vrata);
			tmpRamkaPrice += tmpOtvarjaemostWindowSingle * Number(systemArray[sistemaId].obkov_prozorec_ed);
			tmpRamkaPrice += tmpOtvarjaemostWindowDouble * Number(systemArray[sistemaId].obkov_prozorec_dv);
			tmpRamkaPrice += tmpOtvarjaemostDoorSingle * Number(systemArray[sistemaId].obkov_vrata_ed);
			tmpRamkaPrice += tmpOtvarjaemostDoorDouble * Number(systemArray[sistemaId].obkov_vrata_dv);
			tmpRamkaPrice += tmpRamkaArea * styklopaketPrice;
			tmpRamkaPrice += tmpRamkaArea * Number(systemArray[sistemaId].trud);

			tmpPriceTotal += tmpRamkaPrice;

			tmpFramePrice = new ccFramePrice();
			tmpFramePrice.windows = frameArray[k].windows;
			tmpFramePrice.system = encodeURI(systemArray[sistemaId].name);
			tmpFramePrice.glass = encodeURI(styklopaketObj.options[styklopaketObj.selectedIndex].text);
			tmpFramePrice.width = frameArray[k].width;
			tmpFramePrice.height = frameArray[k].height;
			tmpFramePrice.area = Math.round(tmpRamkaArea * 100) / 100;
			tmpFramePrice.price = encodeURI(Math.round(tmpRamkaPrice * 100) / 100 + ' лв.');
			frameArrayPrice[frameArrayPrice.length] = tmpFramePrice;
			
			tmpPriceStr += '<tr><td>' + Number(k+1) + '<\/td>';
			tmpPriceStr += '<td>' + systemArray[sistemaId].name + '<\/td>';
			tmpPriceStr += '<td>' + styklopaketObj.options[styklopaketObj.selectedIndex].text + '<\/td>';

			tmpPriceStr += '<td>' + frameArray[k].height + '<\/td>';
			tmpPriceStr += '<td>' + frameArray[k].width + '<\/td>';
			tmpPriceStr += '<td>' + Math.round(tmpRamkaArea * 100) / 100 + '<\/td>';
			tmpPriceStr += '<td>1<\/td>';
			//tmpPriceStr += '<td>' + Math.round(tmpRamkaPrice * 100) / 100 + ' лв.<\/td>';
			tmpPriceStr += '<td><input type="image"  src="assets/img/prices/button_delete.gif" class="price_input" style="cursor: pointer;" onclick="frameDelete(' + k + ')" /><\/td>';
			tmpPriceStr += '<\/tr>';
		
		}
		tmpPriceStr += '<\/table>';
		tmpPriceStrForPdf += '<\/table>';
	}

	frameAccessoryPrice = new Array();
	if (accessoryArray.length > 0) { 
		tmpPriceStr += '<div class="title">Аксесоари:<\/div>';
		tmpPriceStr += '<table border="1" cellspacing="0" cellpadding="2">';
		tmpPriceStr += '<tr style="text-align:center;"><td width="20" class="headrow">№<\/td>';
		tmpPriceStr += '<td class="headrow">Аксесоар<\/td>';
		tmpPriceStr += '<td class="headrow">Мярка<\/td>';
		tmpPriceStr += '<td width="80" class="headrow">Количество<\/td>';
		//tmpPriceStr += '<td width="75" class="headrow">Цена<\/td>';
		tmpPriceStr += '<td width="21"><\/td>';
		tmpPriceStr += '<\/tr>';		

		for (m=0; m<accessoryArray.length; m++) {
			var tmpAccPrice = 0;
			var tmpAccPriceType = '';
			var tmpAccQty = 0;
			if (accessoryArray[m].priceType == 1) {
				tmpAccPrice = accessoryArray[m].width * accessoryArray[m].price / 1000;
				tmpAccPriceType = 'лин. м.';
				tmpAccQty = accessoryArray[m].width / 1000;
				if (accessoryArray[m].qty > 0) {
					tmpAccPrice = tmpAccPrice * Math.round(accessoryArray[m].qty);
					tmpAccQty = tmpAccQty * Math.round(accessoryArray[m].qty);
				}
			} else if (accessoryArray[m].priceType == 2) {
				tmpAccPrice = accessoryArray[m].width * accessoryArray[m].height * accessoryArray[m].price / 1000000;
				tmpAccPriceType = 'кв. м.';
				tmpAccQty = accessoryArray[m].width * accessoryArray[m].height / 1000000;
				if (accessoryArray[m].qty > 0) {
					tmpAccPrice = tmpAccPrice * Math.round(accessoryArray[m].qty);
					tmpAccQty = tmpAccQty * Math.round(accessoryArray[m].qty);
				}
			} else if (accessoryArray[m].priceType == 3) {
				tmpAccPrice = accessoryArray[m].qty * accessoryArray[m].price;
				tmpAccPriceType = 'бр.';
				tmpAccQty = accessoryArray[m].qty;
			};

			var tmpAccessoryPrice = new ccAccessoryPrice();
			tmpAccessoryPrice.name = encodeURI(accessoryArray[m].name);
			tmpAccessoryPrice.priceType = encodeURI(tmpAccPriceType);
			tmpAccessoryPrice.qty = Math.round(tmpAccQty * 100) / 100;
			tmpAccessoryPrice.price = encodeURI(Math.round(tmpAccPrice * 100) / 100 + ' лв.');
			frameAccessoryPrice[frameAccessoryPrice.length] = tmpAccessoryPrice;

			tmpPriceStr += '<tr><td>' + Number(m+1) + '<\/td>';
			tmpPriceStr += '<td>' + accessoryArray[m].name + '<\/td>';
			tmpPriceStr += '<td>' + tmpAccPriceType + '<\/td>';
			tmpPriceStr += '<td>' + Math.round(tmpAccQty * 100) / 100 + '<\/td>';
			//tmpPriceStr += '<td>' + Math.round(tmpAccPrice * 100) / 100 + ' лв.<\/td>';
			tmpPriceStr += '<td><input type="image" class="price_input"  src="assets/img/prices/button_delete.gif" style="cursor: pointer;" onclick="accDelete(' + m + ')" /><\/td><\/tr>';
			tmpPriceTotal += tmpAccPrice;
		}
		tmpPriceStr += '<\/table>';
		tmpPriceStrForPdf += '<\/table>';
	}
	TotalPrice = tmpPriceTotal;
	//tmpPriceStr += '<div class="titlePrice">Крайна цена: <span class="price">' + Math.round(tmpPriceTotal * 100) / 100 + ' лв.<\/span> с ДДС<\/div>';
	document.getElementById('orderTable').innerHTML = tmpPriceStr;
	
}

function drawFrame(thisFrame, position) {
	var tmpClass = 'bpFrameNormal';
	if (bpFrameIndex == position) tmpClass = 'bpFrameSelected';
	var tmpStr = '<div class="' + tmpClass + '" onclick="bpFrameClick(this, ' + position + ')" id="frame_' + position + '"><table border="0" cellspacing="0" cellpadding="0">';

	tmpStr += '<tr><td width="7" height="7"><img src="' + t1.src + '" width="7" height="7" \/><\/td><td colspan="' + Math.round(thisFrame.windows.length * 2 - 1) + '" background="' + b1.src + '"><\/td><td width="7"><img src="' + t2.src + '" width="7" height="7" \/><\/td><\/tr>';

	tmpStr += '<tr><td background="' + b4.src + '"><\/td>';

	tmpStr += drawWindow(thisFrame.windows, thisFrame.height, position);

	tmpStr += '<td background="' + b2.src + '"><\/td><\/tr>';

	tmpStr += '<tr><td width="7" height="7"><img src="' + t3.src + '" width="7" height="7" \/><\/td><td colspan="' + Math.round(thisFrame.windows.length * 2 - 1) + '" background="' + b3.src + '"><\/td><td width="7"><img src="' + t4.src + '" width="7" height="7" \/><\/td><\/tr>';

	tmpStr += '<\/table><\/div>';
	return tmpStr;

}
function drawWindow(thisWindows, height, parentPosition) {
	var tmpStr = '';
	var tmpClass = 'bpWinNormal';
	for (j=0; j<thisWindows.length; j++) {
		tmpClass = 'bpWinNormal';//alert (thisWindows[j].width);
		if ((bpWinIndex == j) && (bpWinParentIndex == parentPosition)) tmpClass = 'bpWinSelected';
		tmpStr += '<td class="' + tmpClass + '" onclick="bpWinClick(this, ' + j + ', ' + parentPosition + ', event)" id="win_' + parentPosition + '_' + j + '">';

		if (thisWindows[j].type == 0) { 
			tmpStr += '<img src="' + win0.src + '" width="' + Math.round(thisWindows[j].width / 10) + '" height="' + Math.round(height / 10) + '" />';
		} else {
			tmpStr += '<table border="0" cellspacing="0" cellpadding="0"><tr><td width="6" height="6"><img src="' + wt1.src + '" width="6" height="6" \/><\/td><td background="' + wb1.src + '"><\/td><td width="6"><img src="' + wt2.src + '" width="6" height="6" \/><\/td><\/tr>';
			tmpStr += '<tr><td background="' + wb4.src + '"><\/td>';

			var tmpWinWidth = Math.round(thisWindows[j].width / 10 - 12)
			var tmpWinHeight = Math.round(height / 10 - 12)
			var tmpImgSrc = win0.src;
			var tmpSizeuffix = 0;
			if (tmpWinWidth > 128) {
				tmpSizeuffix = 2;
			} else if (tmpWinWidth > 58) {
				tmpSizeuffix = 1;
			} else if (tmpWinHeight > 268) {
				tmpSizeuffix = 2;
			} else if (tmpWinHeight > 128) {
				tmpSizeuffix = 1;
			};

			if (thisWindows[j].type == 1) {
				tmpImgSrc = eval('win1_' + tmpSizeuffix + '.src');
			} else if (thisWindows[j].type == 2) {
				tmpImgSrc = eval('win2_' + tmpSizeuffix + '.src');
			} else if (thisWindows[j].type == 31) {
				tmpImgSrc = eval('win31_' + tmpSizeuffix + '.src');
			} else if (thisWindows[j].type == 32) {
				tmpImgSrc = eval('win32_' + tmpSizeuffix + '.src');
			};

			tmpStr += '<td><img src="' + tmpImgSrc + '" width="' + Math.round(thisWindows[j].width / 10 - 12) + '" height="' + Math.round(height / 10 - 12) + '" /><\/td>';

			tmpStr += '<td background="' + wb2.src + '"><\/td><\/tr>';

			tmpStr += '<tr><td width="6" height="6"><img src="' + wt3.src + '" width="6" height="6" \/><\/td><td background="' + wb3.src + '"><\/td><td width="6"><img src="' + wt4.src + '" width="6" height="6" \/><\/td><\/tr><\/table>';
		}
		tmpStr += '<\/td>';
		if (j < thisWindows.length - 1) {
			tmpStr += '<td width="5" background="' + bbg.src + '"><img src="' + bbg.src + '" width="5" height="5" \/><\/td>';
		}
	}
	return tmpStr;
}

function bpFrameClick(sender, position) {
	widthObj = document.getElementById('editWidth');
	heightObj = document.getElementById('editHeight');
	if (bpWinObj != null) bpWinDeselect(bpWinObj);
	bpWinObj = null;
	bpWinIndex = null;
	bpWinParentIndex = null;
	enableHeight();
	if (bpFrameObj == sender) {
		bpFrameDeselect(sender);
		bpFrameObj = null;
		bpFrameIndex = null;
		widthObj.value = '';
		heightObj.value = '';
		if (document.getElementById('kozirkaWidth')) document.getElementById('kozirkaWidth').value = '';
		if (document.getElementById('poliWidth')) document.getElementById('poliWidth').value = '';
	} else {
		if (bpFrameObj != null) bpFrameDeselect(bpFrameObj);
		bpFrameSelect(sender);
		bpFrameObj = sender;
		bpFrameIndex = position;
		widthObj.value = frameArray[position].width;
		heightObj.value = frameArray[position].height;
		if (document.getElementById('kozirkaWidth')) document.getElementById('kozirkaWidth').value = frameArray[position].width;
		if (document.getElementById('poliWidth')) document.getElementById('poliWidth').value = frameArray[position].width;
	}
}

function bpWinClick(sender, position, parentPosition, event) {
	widthObj = document.getElementById('editWidth');
	heightObj = document.getElementById('editHeight');
	if (window.event) {
		window.event.cancelBubble = true;
	} else {
		event.stopPropagation();
	};
	if (bpFrameObj != null) bpFrameDeselect(bpFrameObj);
	bpFrameObj = null;
	bpFrameIndex = null;
	if (bpWinObj == sender) {
		bpWinDeselect(sender);
		bpWinObj = null;
		bpWinIndex = null;
		bpWinParentIndex = null;
		enableHeight();
		widthObj.value = '';
		heightObj.value = '';
		if (document.getElementById('kozirkaWidth')) document.getElementById('kozirkaWidth').value = '';
		if (document.getElementById('poliWidth')) document.getElementById('poliWidth').value = '';
	} else {
		if (bpWinObj != null) bpWinDeselect(bpWinObj);
		bpWinSelect(sender);
		bpWinObj = sender;
		bpWinIndex = position;
		bpWinParentIndex = parentPosition;
		disableHeight();
		widthObj.value = frameArray[parentPosition].windows[position].width;
		heightObj.value = frameArray[parentPosition].height;
		if (document.getElementById('kozirkaWidth')) document.getElementById('kozirkaWidth').value = frameArray[parentPosition].width;
		if (document.getElementById('poliWidth')) document.getElementById('poliWidth').value = frameArray[parentPosition].width;
	}
}

function resize() {
	if (bpFrameIndex != null) {
		var newHeight = document.getElementById('editHeight').value;
		if (isNaN(newHeight)) {
			document.getElementById('editHeight').value = frameArray[bpFrameIndex].height;
			newHeight = frameArray[bpFrameIndex].height;
		} else if (newHeight < minHeight) {
			document.getElementById('editHeight').value = minHeight;
			newHeight = minHeight;
		} else if (newHeight > maxHeight) {
			document.getElementById('editHeight').value = maxHeight;
			newHeight = maxHeight;
		}

		var newWidth = document.getElementById('editWidth').value;
		if (isNaN(newWidth)) {
			document.getElementById('editWidth').value = frameArray[bpFrameIndex].width;
			newWidth = frameArray[bpFrameIndex].width;
		} else if (newWidth < minFrameWidth) {
			document.getElementById('editWidth').value = minFrameWidth;
			newWidth = minFrameWidth;
		} else if (newWidth > maxFrameWidth) {
			document.getElementById('editWidth').value = maxFrameWidth;
			newWidth = maxFrameWidth;
		}

		var customSetNum = 0;
		for (i=0; i<frameArray[bpFrameIndex].windows.length; i++) {
			if (frameArray[bpFrameIndex].windows[i].customset) {
				customSetNum ++;
			}
		}
		if (customSetNum == frameArray[bpFrameIndex].windows.length) {
			var newWinWidth = Math.round(newWidth / frameArray[bpFrameIndex].windows.length);
			if (newWinWidth >= minWinWidth) {
				for (i=0; i<frameArray[bpFrameIndex].windows.length; i++) {
					frameArray[bpFrameIndex].windows[i].width = newWinWidth;
				}
			}
		} else {
			var calcMinWidth = 0;
			var tmpWinCount = frameArray[bpFrameIndex].windows.length;
			var tmpWinResizeCount = 0;
			var tmpWinResizewidth = 0;
			for (i=0; i<frameArray[bpFrameIndex].windows.length; i++) {
				if (frameArray[bpFrameIndex].windows[i].customset) {
					calcMinWidth = Number(frameArray[bpFrameIndex].windows[i].width) + Number(calcMinWidth);
					tmpWinResizewidth = Number(frameArray[bpFrameIndex].windows[i].width) + Number(tmpWinResizewidth);
				} else {
					calcMinWidth = Number(minWinWidth) + Number(calcMinWidth);
					tmpWinResizeCount ++;
				}
			}
			tmpWinResizewidth = newWidth - tmpWinResizewidth
			if (newWidth < calcMinWidth) {
				alert('Има ръчно зададени размери на прозорци. За да намалите рамката намалете първо размерите на прозорците.');
			} else {
				for (i=0; i<frameArray[bpFrameIndex].windows.length; i++) {
					if (!frameArray[bpFrameIndex].windows[i].customset) {
						frameArray[bpFrameIndex].windows[i].width = Math.round(tmpWinResizewidth / tmpWinResizeCount);
					}
				};
				frameArray[bpFrameIndex].width = getFrameWidth(frameArray[bpFrameIndex].windows);
				frameArray[bpFrameIndex].customset = 1
			}
		}

		frameArray[bpFrameIndex].height = newHeight;
		Display();
	} else if ((bpWinIndex != null) && (bpWinParentIndex != null)) {
		newWidth = document.getElementById('editWidth').value;
		if (isNaN(newWidth)) {
			document.getElementById('editWidth').value = frameArray[bpWinParentIndex].windows[bpWinIndex].width;
			return;
		} else if (newWidth < minWinWidth) {
			document.getElementById('editWidth').value = minWinWidth;
			newWidth = minWinWidth;
		} else if (newWidth > maxWinWidth) {
			document.getElementById('editWidth').value = maxWinWidth;
			newWidth = maxWinWidth;
		}
		if (frameArray[bpWinParentIndex].customset != 1) {
			frameArray[bpWinParentIndex].windows[bpWinIndex].width = newWidth;
			frameArray[bpWinParentIndex].width = getFrameWidth(frameArray[bpWinParentIndex].windows);
			frameArray[bpWinParentIndex].windows[bpWinIndex].customset = true;
		} else {
			if (bpWinIndex < frameArray[bpWinParentIndex].windows.length - 1) {
				var rightWin = Number(frameArray[bpWinParentIndex].windows[bpWinIndex].width) + 
						Number(frameArray[bpWinParentIndex].windows[bpWinIndex + 1].width) -
							Number(newWidth);
				if (rightWin < minWinWidth) {
					alert('Няма достатъчно място. Преозмерете рамката или съседните прозорци.');
					return;
				} else {
					frameArray[bpWinParentIndex].windows[bpWinIndex].width = newWidth;
					frameArray[bpWinParentIndex].windows[bpWinIndex + 1].width = rightWin;
					frameArray[bpWinParentIndex].windows[bpWinIndex].customset = true
				}
			} else {
;				var leftWin = Number(frameArray[bpWinParentIndex].windows[bpWinIndex].width) + 
						Number(frameArray[bpWinParentIndex].windows[bpWinIndex - 1].width) -
							Number(newWidth);
				if (leftWin < minWinWidth) {
					alert('Няма достатъчно място. Преозмерете рамката или съседните прозорци.');
					return;
				} else {
					frameArray[bpWinParentIndex].windows[bpWinIndex].width = newWidth;
					frameArray[bpWinParentIndex].windows[bpWinIndex - 1].width = leftWin;
					frameArray[bpWinParentIndex].windows[bpWinIndex].customset = true
				}
			}
		}
		Display();
	}
}

function setWinType(type) {
	if ((bpWinIndex != null) && (bpWinParentIndex != null)) {
		if (frameArray[bpWinParentIndex].type == 1) {
			if (type == 31) {
				type = 1;
				alert ('Входните врати могат да се отварят само наляво и надясно.');
			}
			if (type == 32) {
				type = 2;
				alert ('Входните врати могат да се отварят само наляво и надясно.');
			}
		}
		frameArray[bpWinParentIndex].windows[bpWinIndex].type = type;
		Display();
	}
}

function winLeft() {
	if ((bpWinIndex != null) && (bpWinParentIndex != null)) {
		if (bpWinIndex > 0) {
			var tmpWindow = frameArray[bpWinParentIndex].windows[bpWinIndex];
			frameArray[bpWinParentIndex].windows[bpWinIndex] = frameArray[bpWinParentIndex].windows[bpWinIndex - 1];
			frameArray[bpWinParentIndex].windows[bpWinIndex - 1] = tmpWindow;
			bpWinIndex --;
			Display();
		}
	} else if (bpFrameIndex != null) {
		if (bpFrameIndex > 0) {
			var tmpFrame = frameArray[bpFrameIndex];
			frameArray[bpFrameIndex] = frameArray[bpFrameIndex - 1];
			frameArray[bpFrameIndex - 1] = tmpFrame;
			bpFrameIndex --;
			Display();
		}
	}
}

function winRight() {
	if ((bpWinIndex != null) && (bpWinParentIndex != null)) {
		if (bpWinIndex < frameArray[bpWinParentIndex].windows.length - 1) {
			var tmpWindow = frameArray[bpWinParentIndex].windows[bpWinIndex];
			frameArray[bpWinParentIndex].windows[bpWinIndex] = frameArray[bpWinParentIndex].windows[bpWinIndex + 1];
			frameArray[bpWinParentIndex].windows[bpWinIndex + 1] = tmpWindow;
			bpWinIndex ++;
			Display();
		}
	} else if (bpFrameIndex != null) {
		if (bpFrameIndex < frameArray.length - 1) {
			var tmpFrame = frameArray[bpFrameIndex];
			frameArray[bpFrameIndex] = frameArray[bpFrameIndex + 1];
			frameArray[bpFrameIndex + 1] = tmpFrame;
			bpFrameIndex ++;
			Display();
		}
	}
}

function winDelete() {
	if ((bpWinIndex != null) && (bpWinParentIndex != null)) {
		if (confirm('Сигурни ли сте, че искате да изтриете прозорец №' + Number(bpWinIndex + 1) + ' ?')) {
			if (frameArray[bpWinParentIndex].windows.length == 1) {
				var tmpArray = new Array;
				for (i=0; i<frameArray.length; i++) {
					if (bpWinParentIndex != i) {
						tmpArray[tmpArray.length] = frameArray[i];
					}
				};
				frameArray = tmpArray;
				bpWinObj = null;
				bpWinIndex = null;
				bpWinParentIndex = null;
				Display();
			} else {
				var tmpArray = new Array;
				for (i=0; i<frameArray[bpWinParentIndex].windows.length; i++) {
					if (bpWinIndex != i) {
						tmpArray[tmpArray.length] = frameArray[bpWinParentIndex].windows[i];
					}
				};
				frameArray[bpWinParentIndex].windows = tmpArray;
				bpWinObj = null;
				bpWinIndex = null;
				bpWinParentIndex = null;
				Display();
			}
		}
	} else if (bpFrameIndex != null) {
		if (confirm('Сигурни ли сте, че искате да изтриете рамка №' + Number(bpFrameIndex + 1) + ' ?')) {
			var tmpArray = new Array;
			for (i=0; i<frameArray.length; i++) {
				if (bpFrameIndex != i) {
					tmpArray[tmpArray.length] = frameArray[i];
				}
			};
			frameArray = tmpArray;
			bpFrameObj = null;
			bpFrameIndex = null;
			Display();
		}
	}
}

function frameDelete(index) {
	bpWinIndex = null;
	bpWinParentIndex = null;
	bpFrameIndex = index;
	winDelete();
}

function addAccessory(select, widthObj, heightObj, qtyObj, priceType) {

	var tmpWidth = 0;
	if (widthObj != null) tmpWidth = document.getElementById(widthObj).value;
	if (((isNaN(tmpWidth)) || (tmpWidth < 0) || (tmpWidth > maxFrameWidth)))
		tmpWidth = 0;

	var tmpHeight = 0;
	if (heightObj != null) tmpHeight = document.getElementById(heightObj).value;
	if (((isNaN(tmpHeight)) || (tmpHeight < 0) || (tmpHeight > maxHeight)))
		tmpHeight = 0;

	var tmpQty = 0;
	if (qtyObj != null) tmpQty = document.getElementById(qtyObj).value;
	if ((isNaN(tmpQty)) || (tmpQty < 0))
		tmpQty = 0;

	if ((priceType == 1) && ((tmpWidth == 0) || (tmpQty == 0))) return;
	if ((priceType == 2) && ((tmpWidth == 0) || (tmpHeight == 0) || (tmpQty == 0))) return;
	if ((priceType == 3) && (tmpQty == 0)) return;

	var selectObj = document.getElementById(select);
	var tmpItem = selectObj.options[selectObj.selectedIndex].text;
	var tmpPrice = selectObj.options[selectObj.selectedIndex].value;

	var tmpAccessory = new ccAccessory (tmpItem, tmpWidth, tmpHeight, tmpQty, tmpPrice, priceType);
	accessoryArray[accessoryArray.length] = tmpAccessory;
	calculatePrice();
}

function accDelete(index) {
	if (confirm('Сигурни ли сте, че искате да изтриете ' + accessoryArray[index].name + '?')) {
		var tmpArray = new Array;
		for (i=0; i<accessoryArray.length; i++) {
			if (index != i) {
				tmpArray[tmpArray.length] = accessoryArray[i];
			}
		};
		accessoryArray = tmpArray;
		Display();
	}
}

function bpFrameSelect(sender) {
	sender.className = 'bpFrameSelected';
}

function bpFrameDeselect(sender) {
	sender.className = 'bpFrameNormal';
}

function bpWinSelect(sender) {
	sender.className = 'bpWinSelected';
}

function bpWinDeselect(sender) {
	sender.className = 'bpWinNormal';
}

function enableHeight() {
	editObj = document.getElementById('editHeight');
	editObj.className = 'editDefault';
	editObj.disabled = false;
}

function disableHeight() {
	editObj = document.getElementById('editHeight');
	editObj.className = 'editDisabled';
	editObj.disabled = true;
}


function sendOffer(type) {
	if ((frameArray.length == 0) && (accessoryArray.length == 0)) {
		alert('Няма направена поръчка!');
		return;
	}
	var tmpFName = document.getElementById('offerFName').value;
	var tmpLName = document.getElementById('offerLName').value;
	var tmpPhone = document.getElementById('offerPhone').value;
	var tmpEmail = document.getElementById('offerEmail').value;
	var tmpAgree = document.getElementById('offerAgree').checked;
	var tmpNotes = document.getElementById('offerNotes').value;

	if (tmpFName == '') {
		alert('Моля, попълнете полето Име.');
		document.getElementById('offerFName').focus();
		return;
	}
	if (tmpLName == '') {
		alert('Моля, попълнете полето Фамилия.');
		document.getElementById('offerLName').focus();
		return;
	}
	if (tmpPhone == '') {
		alert('Моля, попълнете полето Телефон.');
		document.getElementById('offerPhone').focus();
		return;
	}
	if (tmpEmail == '') {
		alert('Моля, попълнете полето E-mail.');
		document.getElementById('offerEmail').focus();
		return;
	} else if ((tmpEmail.indexOf('@')<=0) || (tmpEmail.lastIndexOf('.') < tmpEmail.indexOf('@'))) {
			alert('Моля, въведете коректен е-мейл адрес');
			document.getElementById('offerEmail').focus();
			return;
	}
	if (!tmpAgree) {
		alert('За да генерирате оферта трябва да сте съгласни с условията за ползване на конфигуратора!');
		return;
	}

	document.offerForm.FName.value = encodeURI(tmpFName);
	document.offerForm.LName.value = encodeURI(tmpLName);
	document.offerForm.Phone.value = encodeURI(tmpPhone);
	document.offerForm.EMail.value = encodeURI(tmpEmail);
	document.offerForm.Notes.value = encodeURI(tmpNotes);

	document.offerForm.Total.value = encodeURI(Math.round(TotalPrice * 100) / 100 + ' лв.');

	document.offerForm.type.value = type;
	document.offerForm.order.value = frameArrayPrice.toJSONString();
	document.offerForm.accessory.value = frameAccessoryPrice.toJSONString();
	document.offerForm.submit();
}
