var area_id     = 0;
var group_id    = 0;
var subgroup_id = 0;
var assortment_id = 0;
var firm_id     = 0;
var type_id     = 0;
var model_id    = 0;
var colorID     = 0;
var page        = 1;

var color_group_list = 0;

window.attachEvent('onload', Init);

// Resize Info
function ResizeInfo(n)
{
	if ( document.getElementById('tpl_info_' + n) )
	{
		var obj = document.getElementById('tpl_info_' + n);
	
		if ( obj.is_open == true || obj.style.display == 'inline' )
		{
			obj.style.display = 'none';
			document.getElementById('order_resize_' + n).src = path + 'templates/' + template_name + '/images/order_resize_close.gif';
			obj.is_open = false;
		}
		else
		{
			obj.style.display = 'inline';
			document.getElementById('order_resize_' + n).src = path + 'templates/' + template_name + '/images/order_resize_open.gif';
			obj.is_open = true;
		}
		
	}
}


function Init()
{
	//UpdateCalculator(0);
}

// Update Global variables
function UpdateVariables()
{
	var oForm = document.getElementById('frm_Order');
	
	CreateColorGroupList(oForm);
	
	area_id     = document.getElementById('area_id').value;
	group_id    = document.getElementById('group_id').value;
	subgroup_id = document.getElementById('subgroup_id').value;
	assortment_id = document.getElementById('assortment_id').value;
	firm_id     = document.getElementById('firm_id').value;
	type_id     = document.getElementById('type_id').value;
	model_id    = document.getElementById('model_id').value;
	colorID     = trim(document.getElementById('search_color').value);
	page        = document.getElementById('page').value;
}

function CreateColorGroupList(oForm)
{
	color_group_list = '';
	
	if ( oForm['color_group[]'] )
	{
		for (var i=0; i < oForm['color_group[]'].length; i++) 
		{
			if ( document.getElementById('color_group_0').checked && !oForm['color_group[]'][i].checked )
			{
				//oForm['color_group[]'][i].checked = true;	
			}
			
			if (oForm['color_group[]'][i].checked == true || document.getElementById('color_group_0').checked)
			{
				if (color_group_list != '')
				{
					color_group_list = color_group_list + ',';
				}
				color_group_list = color_group_list + oForm['color_group[]'][i].value;
			}
		}
	}
	
	if ( color_group_list == '')
	{
		if (document.getElementById('color_group_0').checked)
		{
			color_group_list = 'all';
		}
		else
		{
			// 0 - не выбрано ничего
			color_group_list = 0;
		}
	}
}

function GoToPage(page_num)
{
	document.getElementById('page').value = page_num;
	UpdateVariables();
	//PHPtoDIV('tpl_products', '/includes/_neworder_jalousie_products.php?subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=all&colorID=' + colorID + '&page=' + page);

	// Показать продукты
	destination.push('tpl_products');
	ajax_req = 'subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=' + color_group_list + '&colorID=' + colorID + '&assortment_id=' + assortment_id + '&page=' + page + '&target=neworder_jalousie_products';
	cache.push(ajax_req);
	getAjaxRequest();

	return false;
}

function ColorGroupAll_Click(oForm, checked)
{
	UpdateVariables();
	
	for (var i=0; i < oForm['color_group[]'].length; i++) 
	{
		oForm['color_group[]'][i].checked = checked;
	}

	CreateColorGroupList(oForm);
	
	//PHPtoDIV('tpl_products', '/includes/_neworder_jalousie_products.php?subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=' + color_group_list + '&colorID=' + colorID);
	
	// Показать продукты
	destination.push('tpl_products');
	ajax_req = 'subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=' + color_group_list + '&colorID=' + colorID + '&assortment_id=' + assortment_id + '&target=neworder_jalousie_products';
	cache.push(ajax_req);
	getAjaxRequest();
}

function ColorGroup_Click(oForm)
{
	UpdateVariables();
	
	document.getElementById('color_group_0').checked = false;
	
	CreateColorGroupList(oForm);
	//PHPtoDIV('tpl_products', '/includes/_neworder_jalousie_products.php?subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=' + color_group_list + '&colorID=' + colorID);
	
	// Показать продукты
	destination.push('tpl_products');
	ajax_req = 'subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=' + color_group_list + '&colorID=' + colorID + '&assortment_id=' + assortment_id + '&target=neworder_jalousie_products';
	cache.push(ajax_req);
	getAjaxRequest();
}

function ReloadForm(subgroup_id, firm_id, type_id, product_id)
{
	//PHPtoDIV('tpl_forms', '/includes/_neworder_form.php?product_id=' + product_id);
	PHPtoDIV('tpl_forms', '/includes/_neworder_form.php?area_id=' + area_id + '&group_id=' + group_id + '&subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&product_id=' + product_id);
	//destination.push('tpl_forms');
	//ajax_req = 'product_id=' + product_id + '&target=neworder_form';
	//cache.push(ajax_req);
	//getAjaxRequest();
}

function Firm_Change(oForm)
{
	oForm['chk_filter'][1].checked = true;
	
	UpdateVariables();
	PHPtoDIV('tpl_type', '/includes/_neworder_jalousie_type.php?subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id);

	UpdateVariables();
	PHPtoDIV('tpl_color_group', '/includes/_neworder_jalousie_color_group.php?area_id=' + area_id + '&group_id=' + group_id + '&subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id);

	UpdateVariables();
	//PHPtoDIV('tpl_products', '/includes/_neworder_jalousie_products.php?subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=all&colorID=' + colorID);
	// Показать продукты
	destination.push('tpl_products');
	ajax_req = 'subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=' + color_group_list + '&colorID=' + colorID + '&assortment_id=' + assortment_id + '&target=neworder_jalousie_products';
	cache.push(ajax_req);
	getAjaxRequest();

	UpdateVariables();
	PHPtoDIV('tpl_forms', '/includes/_neworder_form.php?area_id=' + area_id + '&group_id=' + group_id + '&subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id);
	
	//UpdateCalculator();
}

function Type_Change(oForm)
{
	oForm['chk_filter'][1].checked = true;
	
	UpdateVariables();
	PHPtoDIV('tpl_model', '/includes/_neworder_jalousie_model.php?type_id=' + type_id);

	UpdateVariables();
	PHPtoDIV('tpl_color_group', '/includes/_neworder_jalousie_color_group.php?area_id=' + area_id + '&group_id=' + group_id + '&subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id);

	UpdateVariables();
	//PHPtoDIV('tpl_products', '/includes/_neworder_jalousie_products.php?subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=all&colorID=' + colorID);
	// Показать продукты
	destination.push('tpl_products');
	ajax_req = 'subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=' + color_group_list + '&colorID=' + colorID + '&assortment_id=' + assortment_id + '&target=neworder_jalousie_products';
	cache.push(ajax_req);
	getAjaxRequest();

	UpdateVariables();
	PHPtoDIV('tpl_forms', '/includes/_neworder_form.php?area_id=' + area_id + '&group_id=' + group_id + '&subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id);
}

function Model_Change(oForm)
{
	oForm['chk_filter'][1].checked = true;
	
	UpdateVariables();	
	PHPtoDIV('tpl_color_group', '/includes/_neworder_jalousie_color_group.php?area_id=' + area_id + '&group_id=' + group_id + '&subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id);
	
	UpdateVariables();	
	//PHPtoDIV('tpl_products', '/includes/_neworder_jalousie_products.php?subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=all&colorID=' + colorID);
	// Показать продукты
	destination.push('tpl_products');
	ajax_req = 'subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=' + color_group_list + '&colorID=' + colorID + '&assortment_id=' + assortment_id + '&target=neworder_jalousie_products';
	cache.push(ajax_req);
	getAjaxRequest();
}

function Assortment_Change(oForm)
{
	
	UpdateVariables();	
	// Показать продукты
	destination.push('tpl_products');
	ajax_req = 'subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=' + color_group_list + '&colorID=' + colorID + '&assortment_id=' + assortment_id + '&target=neworder_jalousie_products';
	cache.push(ajax_req);
	getAjaxRequest();
}


function ChangeFilter(oForm)
{
	if ( oForm['chk_filter'][0].checked  )
	{
		if ( confirm('Do you want to request ?') )
		{
			UpdateVariables();
			document.location.href = cfgRootPath + 'newrequest/' + area_id + '/' + group_id + '/' + subgroup_id + '/';
		}
		else
		{
			oForm['chk_filter'][1].checked = true;
		}
		// Remove filter
		/*
		document.getElementById("firm_id").options[0].selected = true;
		
		UpdateVariables();
		PHPtoDIV('tpl_type', '/includes/_neworder_jalousie_type.php?subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id);
		
		UpdateVariables();
		PHPtoDIV('tpl_model', '/includes/_neworder_jalousie_model.php?type_id=' + type_id);

		UpdateVariables();	
		PHPtoDIV('tpl_color_group', '/includes/_neworder_jalousie_color_group.php?area_id=' + area_id + '&group_id=' + group_id + '&subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id);
		
		UpdateVariables();	
		PHPtoDIV('tpl_products', '/includes/_neworder_jalousie_products.php?subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=all&colorID=' + colorID);
		*/
	}
	else
	{
		
	}
}

function SelectProduct(product_id)
{
	//alert(".בחירתך מופיעה מימין  \n  .המשך במילוי ובחירה בטופס או עבור לסוף הטופס לקבלת יעוץ והצעות");
	
	// Обновим блок с информацией о выбранном продукте
	destination.push('tpl_selected_product');
	ajax_req = 'product_id=' + product_id + '&target=neworder_select_product';
	cache.push(ajax_req);
	getAjaxRequest();
	
	// Второй блок (дублирует первый)
	destination.push('tpl_selected_product_second');
	cache.push(ajax_req);
	getAjaxRequest();
	
	// Покажем форму для заполнения параметров выбранноко продукта
	ReloadForm(subgroup_id, firm_id, type_id, product_id);
	
	// Сдвинуть документ в окне к верхнему блоку с выбранным продуктом
	document.location = '#selected_product';
}

function Change_Cornice()
{
	if ( document.getElementById('cornice_id') )
	{
		var cornice_id = parseInt( document.getElementById('cornice_id').value );
		
		if ( cornice_id == 215 || cornice_id == 242 )
		{
			document.getElementById('block_cornice_size').style.display = 'block';
		}
		else
		{
			document.getElementById('block_cornice_size').style.display = 'none';
		}
	}
	
	UpdateCalculator();
}

function Change_AdditiveTape()
{
	if ( document.getElementById('additive_tape') )
	{
		if ( document.getElementById('additive_tape').checked == true )
		{
			document.getElementById('div_additive_tape').style.display = 'block';
		}
		else
		{
			document.getElementById('div_additive_tape').style.display = 'none';
		}
	}
	
	UpdateCalculator();
}

function SelectMechamism(id)
{
	var mechanism_type_1  = document.getElementById('mechanism_type_1');
	var mechanism_type_2  = document.getElementById('mechanism_type_2');
	var mechanism_type_3  = document.getElementById('mechanism_type_3');
	
	var block_mechanism_1 = document.getElementById('block_mechanism_1');
	var block_mechanism_2 = document.getElementById('block_mechanism_2');
	var block_mechanism_3 = document.getElementById('block_mechanism_3');
	
	if ( isNaN(mechanism_type_1) )
	{
		mechanism_type_1.checked = false;
		block_mechanism_1.style.display = 'none';
	}
	if ( isNaN(mechanism_type_2) )
	{
		mechanism_type_2.checked = false;
		block_mechanism_2.style.display = 'none';
	}
	if ( isNaN(mechanism_type_3) )
	{
		mechanism_type_3.checked = false;
		block_mechanism_3.style.display = 'none';
	}
	
	if ( id == 1 )
	{
		if ( isNaN(mechanism_type_1) )
		{
			mechanism_type_1.checked = true;
			block_mechanism_1.style.display = 'inline';
		}
	}
	else if ( id == 2 )
	{
		if ( isNaN(mechanism_type_2) )
		{
			mechanism_type_2.checked = true;
			block_mechanism_2.style.display = 'inline';
		}
	}
	else if ( id == 3 )
	{
		if ( isNaN(mechanism_type_3) )
		{
			mechanism_type_3.checked = true;
			block_mechanism_3.style.display = 'inline';
		}
	}
	
	UpdateCalculator();
}

function ColorCombination(checked)
{
	if ( checked )
	{
		document.getElementById('additive_color_combination').disabled = false;
		document.getElementById('additive_color_combination_text').disabled = false;
		document.getElementById('block_additive_color_combination').style.display = 'block';
	}
	else
	{
		document.getElementById('additive_color_combination').disabled = true;
		document.getElementById('additive_color_combination_text').disabled = true;
		document.getElementById('block_additive_color_combination').style.display = 'none';
	}
	//UpdateCalculator();
}

function CropRight(checked)
{
	if ( checked )
	{
		document.getElementById('crop_right_height').disabled = false;
		document.getElementById('crop_right_width').disabled = false;
		document.getElementById('block_crop_right').style.display = 'block';
	}
	else
	{
		document.getElementById('crop_right_height').disabled = true;
		document.getElementById('crop_right_width').disabled = true;
		document.getElementById('block_crop_right').style.display = 'none';
	}
	//UpdateCalculator();
}

function CropLeft(checked)
{
	if ( checked )
	{
		document.getElementById('crop_left_height').disabled = false;
		document.getElementById('crop_left_width').disabled = false;
		document.getElementById('block_crop_left').style.display = 'block';
	}
	else
	{
		document.getElementById('crop_left_height').disabled = true;
		document.getElementById('crop_left_width').disabled = true;
		document.getElementById('block_crop_left').style.display = 'none';
	}
	//UpdateCalculator();
}

function AdditiveTape(checked)
{
	if ( checked )
	{
		document.getElementById('div_additive_tape').style.display = 'block';
	}
	else
	{
		document.getElementById('div_additive_tape').style.display = 'none';
	}
	//UpdateCalculator();
}

function IsInstall()
{
	if ( parseInt(document.getElementById('is_install').value) == 0 )
	{
		document.getElementById('install_to').disabled = true;
		document.getElementById('install_to_text').disabled = true;
		document.getElementById('block_install').style.display = 'none';
	}
	else
	{
		document.getElementById('install_to').disabled = false;
		document.getElementById('install_to_text').disabled = false;
		document.getElementById('block_install').style.display = 'block';
	}
	UpdateCalculator();
}

function SearchColor()
{
	UpdateVariables();
	//PHPtoDIV('div_color_name', '/includes/_neworder_jalousie_color_name.php?colorID=' + colorID);
	//PHPtoDIV('tpl_products', '/includes/_neworder_jalousie_products.php?subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=all&colorID=' + colorID);
	
	if ( colorID != '' )
	{
		// Найти название цвета по введенному коду
		destination.push('div_color_name');
		ajax_req = 'colorID=' + colorID + '&target=neworder_color_name';
		cache.push(ajax_req);
		getAjaxRequest();
	
		// Показать все продукты, у которых соответствующий код цвета
		destination.push('tpl_products');
		ajax_req = 'subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=all&colorID=' + colorID + '&assortment_id=' + assortment_id + '&target=neworder_jalousie_products';
		cache.push(ajax_req);
		getAjaxRequest();
	}
	else
	{
		alert('הקלד מספר קטלוגי. תודה');	
	}
	
	return false;	
}

function SearchColor_Clear()
{
	document.getElementById('search_color').value = '';
	document.getElementById('div_color_name').innerHTML = '';
	
	UpdateVariables();
	
	// Показать все продукты, у которых соответствующий код цвета
	destination.push('tpl_products');
	ajax_req = 'subgroup_id=' + subgroup_id + '&firm_id=' + firm_id + '&type_id=' + type_id + '&model_id=' + model_id + '&color_group_list=' + color_group_list + '&colorID=' + colorID + '&assortment_id=' + assortment_id + '&target=neworder_jalousie_products';
	cache.push(ajax_req);
	getAjaxRequest();
	
	return false;
}

function ShowInfo(category, id)
{
	var e = window.event;
	
	nav = navigator.appName;
	if (nav != "Netscape") 
	{
		var w = document.body.clientWidth;
		var h = document.body.clientHeight;
	}
	else
	{
		var w = window.innerWidth;
		var h = window.innerHeight;
	}
	
	var e = window.event; 
	if (e.pageX || e.pageY) 
	{ 
		mouse_x = e.pageX; 
		mouse_y = e.pageY; 
	} 
	else if (e.clientX || e.clientY) 
	{ 
		mouse_x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft; 
		mouse_y = e.clientY + (document.documentElement.scrollTop  || document.body.scrollTop) - document.documentElement.clientTop; 
	} 

	var div_x = (w-700)/2 - 12;
	var div_y = mouse_y + 15;
	var div_w = 700;

	document.getElementById('tpl_info').style.left  = div_x;
	document.getElementById('tpl_info').style.top   = div_y;
	document.getElementById('tpl_info').style.width = div_w;
	
	PHPtoDIV('tpl_info', '/includes/_showinfo.php?category=' + category + '&id=' + id);

	return false;
}

function CloseInfo()
{
	document.getElementById('tpl_info').style.display = 'none';
	document.getElementById('tpl_info').innerHTML = '';
	return false;
}


function ZoomProduct(id)
{
	var e = window.event; 
	if (e.pageX || e.pageY) 
	{ 
		//x = e.pageX;
		y = e.pageY; 
	} 
	else if (e.clientX || e.clientY) 
	{ 
		//x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft; 
		//y = e.clientY + (document.documentElement.scrollTop  || document.body.scrollTop) - document.documentElement.clientTop;
		y = (document.documentElement.scrollTop  || document.body.scrollTop) - document.documentElement.clientTop + 100;
	}
	x = 100;

	document.getElementById('tpl_zoom').style.left = x;
	document.getElementById('tpl_zoom').style.top  = y;
	
	PHPtoDIV('tpl_zoom', '/includes/_neworder_jalousie_zoomproduct.php?product_id=' + id);
}

function CloseZoomProduct()
{
	document.getElementById('tpl_zoom').style.display = 'none';
	document.getElementById('tpl_zoom').innerHTML = '';
	//return false;
}

function ZoomProductImage(id)
{

	//document.getElementById('tpl_zoom_image').style.left = x;
	//document.getElementById('tpl_zoom_image').style.top  = y;

	PHPtoDIV('tpl_zoom_image', '/includes/_neworder_jalousie_zoomproduct_image.php?product_id=' + id);
}

function CloseZoomProductImage()
{
	document.getElementById('tpl_zoom_image').style.display = 'none';
	document.getElementById('tpl_zoom_image').innerHTML = '';
	//return false;
}

// Сохранить заказ
function SaveOrder()
{
	if ( isNaN(document.getElementById('selected_product_id')) )
	{
		//var selected_product_id = document.getElementById('selected_product_id').value;
		if ( USER_ID == 0 )
		{
			// Посетитель не зарегистрирован
			document.getElementById('is_save_order').value = '0';
			document.frm_Order.submit();
		}
		else
		{
			// Посетитель зарегистрирован
			document.getElementById('is_save_order').value = '1';
			document.frm_Order.submit();
		}
			
	}
	else
	{
		alert('! אנא, בחר גוון');	
	}
	return false;
}

function getField(field)
{
	if ( document.getElementById(field) )
	{
		return document.getElementById(field);
	}
	return false;
}

function getFieldPrice(field, value)
{
	// Default price
	var price = value;
	
	// Если указанное поле существует
	if ( document.getElementById(field) )
	{
		// Если переменная существует
		if ( field in this )
		{
			var arr = eval(field);
			
			// Если это массив
			if ( arr.join )
			{
				var v = document.getElementById(field).value;
				var price = arr[v];
			}
		}
	}
	
	return parseFloat(price);
}

function getFieldValue(field, value)
{
	var n = value;
	// Если указанное поле существует, то вернем его значение, а иначе - переданное значение "value"
	if ( document.getElementById(field) )
	{
		n = document.getElementById(field).value;
	}
	
	return n;
}

function setFieldValue(field, value)
{
	// Если указанное поле существует, то вернем его значение, а иначе - переданное значение "value"
	if ( document.getElementById(field) )
	{
		document.getElementById(field).value = value;
	}
	else
	{
		return false;
	}
}

function setElementDisplay(field, value)
{
	// Если указанное поле существует, то установиме его видимость (display)
	if ( document.getElementById(field) )
	{
		document.getElementById(field).style.display = value;
	}
	else
	{
		return false;
	}
}

function isChecked(field)
{
	// Если чекбокс существует и помечен, то вернем 1, иначе - 0
	if ( document.getElementById(field) )
	{
		if ( document.getElementById(field).checked )
		{
			return 1;
		}
	}
	return 0;
}

function ChangeField(obj)
{
	switch(obj.name)
	{
		case "vertical_selection":
			if ( parseInt(obj.value) == 523 )
			{
				// מסילה אלכסונית/ שיפועית
				setElementDisplay('block_mechanism_track_vertically_diagonal', 'block');
				setElementDisplay('block_mechanism_track_vertically_diagonal_d', 'block');

				setElementDisplay('block_size_height', 'block');
				setElementDisplay('block_mechanism_track_vertically_rounded', 'none');
				setElementDisplay('block_mechanism_track_vertically_rounded_h', 'none');
				setElementDisplay('block_mechanism_track_vertically_rounded_d', 'none');
				
				// ручной подъемник
				setElementDisplay('block_mechanism_track_id', 'none');
				setElementDisplay('block_mechanism_track_diagonal', 'block');
				setElementDisplay('block_mechanism_track_orbicular', 'none');
				
				// электрический подъемник 24V
				setElementDisplay('block_mechanism_electric_track_24V', 'none');
				setElementDisplay('block_mechanism_track_electric_diagonal', 'block');
				setElementDisplay('block_mechanism_electric_track_orbicular_24V', 'none');
			}
			else if ( parseInt(obj.value) == 522 )
			{
				// מסילה מעוגלת
				setElementDisplay('block_mechanism_track_vertically_diagonal', 'none');
				setElementDisplay('block_mechanism_track_vertically_diagonal_d', 'none');
				
				setElementDisplay('block_size_height', 'none');
				setElementDisplay('block_mechanism_track_vertically_rounded', 'block');
				setElementDisplay('block_mechanism_track_vertically_rounded_h', 'block');
				setElementDisplay('block_mechanism_track_vertically_rounded_d', 'block');
				
				// ручной подъемник
				setElementDisplay('block_mechanism_track_id', 'none');
				setElementDisplay('block_mechanism_track_diagonal', 'none');
				setElementDisplay('block_mechanism_track_orbicular', 'block');

				// электрический подъемник 24V
				setElementDisplay('block_mechanism_electric_track_24V', 'none');
				setElementDisplay('block_mechanism_track_electric_diagonal', 'none');
				setElementDisplay('block_mechanism_electric_track_orbicular_24V', 'block');
			}
			else
			{
				// מסילה ישרה
				setElementDisplay('block_mechanism_track_vertically_diagonal', 'none');
				setElementDisplay('block_mechanism_track_vertically_diagonal_d', 'none');
				
				setElementDisplay('block_size_height', 'block');
				setElementDisplay('block_mechanism_track_vertically_rounded', 'none');
				setElementDisplay('block_mechanism_track_vertically_rounded_h', 'none');
				setElementDisplay('block_mechanism_track_vertically_rounded_d', 'none');
				
				// ручной подъемник
				setElementDisplay('block_mechanism_track_id', 'block');
				setElementDisplay('block_mechanism_track_diagonal', 'none');
				setElementDisplay('block_mechanism_track_orbicular', 'none');

				// электрический подъемник 24V
				setElementDisplay('block_mechanism_electric_track_24V', 'block');
				setElementDisplay('block_mechanism_track_electric_diagonal', 'none');
				setElementDisplay('block_mechanism_electric_track_orbicular_24V', 'none');
			}
			
			break;
			

	}
	
	UpdateCalculator();
}

function InitCalculator()
{
	// Месила
	ChangeField( getField('vertical_selection') );	
	
	// Update calculator
	UpdateCalculator();
}

function selectComboValue(field, id)
{
	if ( getField(field) )
	{
		obj = getField(field);

		for (i=0; i<obj.length; i++)
		{
			if (obj.options[i].value == id)
			{
				obj.selectedIndex = i
			}
		}
	}
}

function selectCheckbox(field, status)
{
	if ( getField(field) )
	{
		obj = getField(field);
		obj.checked = status;
	}
}

function UpdateCalculator()
{
	var form_id = 0;
	var product_id = parseInt(getFieldValue('selected_product_id', 0));
	var price = parseFloat(getFieldValue('calculator_site_price', 0));
	
	if ( getField('sochecim_price') )
	{
		price = parseFloat(getFieldPrice('sochecim_price', 0));
	}

	//-----------------------------------------------------------------------------
	var size_height = parseFloat(getFieldValue('size_height', 0)) / 100;

	var size_width  = parseFloat(getFieldValue('size_width', 0)) / 100;
	if ( size_width < 1 )
	{
		size_width = 1;
	}
	
	//------------------------------------------------------
	// Определим - какое из полей "количество" есть на форме
	var qty_field = '';
	
	if ( getField('size_qty') )
	{
		// כמות למטר מרובע* 
		qty_field = 'size_qty';
	}
	else if ( getField('size_qty_unit') )
	{
		// כמות ליחידות* 
		qty_field = 'size_qty_unit';
	}
	else if ( getField('size_qty_vertical_sqm_orbicular') )
	{
		
		qty_field = 'size_qty_vertical_sqm_orbicular';
	}
	else if ( getField('size_qty_length_general') )
	{
		// כמות מטר רץ כללי 
		qty_field = 'size_qty_length_general';
	}
	else if ( getField('size_qty_length_roller') )
	{
		//
		qty_field = 'size_qty_length_roller';
	}
	else if ( getField('size_qty_length_curtain') )
	{
		//
		qty_field = 'size_qty_length_curtain';
	}
	var size_qty = parseFloat(getFieldValue(qty_field, 0));

	if ( isNaN(size_width) || isNaN(size_height) )
	{
		size_width  = 0;
		size_height = 0;
	}
	//------------------------------------------------------

	//*****************************************
	// BEGIN: Всякие проверки введенных данных
	// 		  и сообщения для пользователя
	
	// Haclala pnim / Veneziani
	if ( area_id == 9 && group_id == 8 )
	{
		// Проверка на мин. ширину
		if ( size_width != 0 && size_width < (20/100) )
		{
			alert('לא ניתן לייצר רוחב קטן מ- 20 ס"מ');
		}
		// Проверка на макс. ширину
		if ( size_width != 0 && size_width > (300/100) )
		{
			alert('מעל 300 ס"מ חלק רוחב ל- 2 יחידות');
		}
		// Проверка на мин. ширину
		if ( size_height != 0 && size_height < (10/100) )
		{
			alert('גובה לא סביר בדוק שוב');
		}
		// Проверка на макс. высоту
		if ( size_height != 0 && size_height > (300/100) )
		{
			alert('גובה מעל המלצת היצרן. מומלץ לחלקו לשתי יחידות');
		}
	}
	// Haclala pnim / Glila / ...
	if ( area_id == 9 && group_id == 9 )
	{
		if ( isChecked('mechanism_type_1') )
		{
			// Manual
			if (size_width > 3 || size_height > 3.2)
			{
				alert('מעל 300 ס"מ רוחב או 320 ס"מ גובה נבחר מנגנון חשמלי מתאים');
				selectCheckbox('mechanism_type_3',true);
				SelectMechamism(3);
				
			}
			else if ( (size_width > 2.5 || size_height > 2.6) && (firm_id == 8 || firm_id == 7) && 
					   parseInt(getFieldValue('mechanism_mechanical_id', 0)) != 283 )
			{
				// Tzilon || Orgon
				// 283 - שרשרת 45 מ"מ
				alert('לרוחב מעל 250 ס"מ או גובה מעל 260 ס"מ נדרש צינור 45 ס"מ');
				selectComboValue('mechanism_mechanical_id','283');
			}
			else if ( (size_width > 2.5 || size_height > 2.6) && 
					   firm_id == 10 && 
					   parseInt(getFieldValue('mechanism_mechanical_id', 0)) != 474 )
			{
				// Domus
				// 474 - שרשרת 50 מ"מ מוטורה
				alert('לרוחב מעל 250 ס"מ או גובה מעל 260 ס"מ נדרש צינור 50 ס"מ');
				selectComboValue('mechanism_mechanical_id','474');
			}
			else if ( (size_width > 1.8 || size_height > 1.7) && 
					   (
					   parseInt(getFieldValue('mechanism_mechanical_id', 0)) == 73 || 
					   parseInt(getFieldValue('mechanism_mechanical_id', 0)) == 74 || 
					   parseInt(getFieldValue('mechanism_mechanical_id', 0)) == 281) )
			{
				// 73  - שרשרת 25 מ"מ 
				// 74  - קפיץ 25 מ"מ
				// 281 - שרשרת 28 מ"מ
				alert('שים לב מעל רוחב 180 ס"מ או גובה 170 ס"מ חל שינוי בבחירת הצינור והמנגנון. מעל רוחב 300 ס"מ או גובה 320 ס"מ יבחר מנגנון חשמלי');
				
				if ( parseInt(getFieldValue('mechanism_mechanical_id', 0)) == 73 || 
					 parseInt(getFieldValue('mechanism_mechanical_id', 0)) == 74 || 
					 parseInt(getFieldValue('mechanism_mechanical_id', 0)) == 281)
				{
					// From 25sm, 28sm to 38sm
					selectComboValue('mechanism_mechanical_id','282');
				}
				
			}
		}
		else if ( isChecked('mechanism_type_3') )
		{
			// Electric 220V
			if ( size_width > 6 || size_height > 16 )
			{
				alert('לא ניתן לייצר וילון גלילה מעל 600 ס"מ רוב או 1600 ס"מ גובה. חלק למספר וילונות במקרים אלו');
			}
			else if ( (size_width > 5.5 || size_height > 13.5) && parseInt(getFieldValue('tzinor', 0)) != 115 )
			{
				alert('לרוחב מעל 550 ס"מ או גובה מעל 1350 ס"מ נדרש צינור 130 ס"מ');
				selectComboValue('tzinor','115');
			}
			else if ( (size_width > 4.5 || size_height > 11) && 
					   parseInt(getFieldValue('tzinor', 0)) != 114 && 
					   parseInt(getFieldValue('tzinor', 0)) != 115 )
			{
				alert('לרוחב מעל 450 ס"מ או גובה מעל 1100 ס"מ נדרש צינור 110 ס"מ');
				selectComboValue('tzinor','114');
			}
			else if ( (size_width > 4 || size_height > 8.5) && 
					   parseInt(getFieldValue('tzinor', 0)) != 113 && 
					   parseInt(getFieldValue('tzinor', 0)) != 114 && 
					   parseInt(getFieldValue('tzinor', 0)) != 115 )
			{
				alert('לרוחב מעל 400 ס"מ או גובה מעל 850 ס"מ נדרש צינור 89 ס"מ');
				selectComboValue('tzinor','113');
			}
			else if ( (size_width > 3.2 || size_height > 7.5) && 
					   parseInt(getFieldValue('tzinor', 0)) != 112 && 
					   parseInt(getFieldValue('tzinor', 0)) != 113 && 
					   parseInt(getFieldValue('tzinor', 0)) != 114 && 
					   parseInt(getFieldValue('tzinor', 0)) != 115 )
			{
				alert('לרוחב מעל 320 ס"מ או גובה מעל 750 ס"מ נדרש צינור 70 ס"מ');
				selectComboValue('tzinor','112');
			}
			else if ( (size_width > 2.6 || size_height > 4.5) && 
					   parseInt(getFieldValue('tzinor', 0)) != 111 && 
					   parseInt(getFieldValue('tzinor', 0)) != 112 && 
					   parseInt(getFieldValue('tzinor', 0)) != 113 && 
					   parseInt(getFieldValue('tzinor', 0)) != 114 && 
					   parseInt(getFieldValue('tzinor', 0)) != 115 )
			{
				alert('לרוחב מעל 260 ס"מ או גובה מעל 450 ס"מ נדרש צינור 60 ס"מ');
				selectComboValue('tzinor','111');
			}
		}
	}
	
	// END:   Всякие проверки введенных данных
	// 		  и сообщения для пользователя
	//*****************************************

	//*****************************************
	// BEGIN: Площадь
	// (либо м.кв., либо метр погонный)
	var area = 0;
	
	if ( qty_field == 'size_qty' )
	{
		area = size_width * size_height;
		if ( area < 1 )
		{
			// Min площадь - 1 м.кв.
			area = 1;
		}
		area = area * size_qty;
	}
	// END: Площадь
	//*****************************************

	//*****************************************
	// BEGIN: Корниз
	var price_cornice = 0;
	price_cornice = getFieldPrice('cornice_id', 0) * size_width * size_qty;
	// END: Корниз
	//*****************************************
	
	//*****************************************
	// BEGIN: Промежуточная сумма 
	// (площадь * цену товара)
	var price_sum = 0;
	
	if ( qty_field == 'size_qty' )
	{
		price_sum = price * area;
	}
	else if ( qty_field == 'size_qty_length_general' || qty_field == 'size_qty_length_roller' || qty_field == 'size_qty_length_curtain' )
	{
		price_sum = price * size_qty * size_width;
	}
	else if ( qty_field == 'size_qty_unit' )
	{
		price_sum = price * size_qty;
	}
	// END: Промежуточная сумма 
	//*****************************************
	
	//*****************************************
	// BEGIN: Общая длина  
	var calculator_lm_fabric;
	calculator_lm_fabric = size_qty * size_width;
	// END: Общая длина
	//*****************************************
	
	var size_cables = isChecked('size_cables');
	var cables_price = 0;
	if ( size_cables == 1 )
	{
		cables_price = price_sum * 10 / 100;
	}


	//*****************************************
	// BEGIN: Подъемный механизм
	var mechanism_price = 0;

	if ( isChecked('mechanism_type_1') == 1 )
	{
		//************************************
		// Manual
		//************************************
		var mechanism_type_id		= 1;
		var mechanism_mechanical_id	= getFieldValue('mechanism_mechanical_id', 0);
		var mechanism_engine_id		= 0;
		
		mechanism_price = getFieldPrice('mechanism_mechanical_id', 0);
		
		// Месила ядани
		if ( getFieldValue('vertical_selection', 0) == 523 )
		{
			// מסילה אלכסונית/ שיפועית
			mechanism_price = mechanism_price + getFieldPrice('mechanism_track_diagonal', 0) * size_width;
		}
		else if ( getFieldValue('vertical_selection', 0) == 522 )
		{
			// מסילה מעוגלת
			mechanism_price = mechanism_price + getFieldPrice('mechanism_track_orbicular', 0) * size_width;
		}
		else
		{
			// מסילה ישרה
			mechanism_price = mechanism_price + getFieldPrice('mechanism_track_id', 0) * size_width;
		}
	}
	else if ( isChecked('mechanism_type_2') == 1 )
	{
		//************************************
		// 24V
		//************************************
		var mechanism_type_id		= 2;
		var mechanism_mechanical_id	= 0;
		var mechanism_engine_id		= getFieldValue('mechanism_engine_id_2', 0);
		
		mechanism_price  = getFieldPrice('mechanism_engine_id_2', 0); 			// Двигатель
		mechanism_price += getFieldPrice('mechanism_transformer_id_2', 0); 		// Трансформатор
		mechanism_price += getFieldPrice('mechanism_rc_id_2', 0); 				// Пульт ДУ
		mechanism_price += getFieldPrice('mechanism_timer_id_2', 0); 			// Таймер
		mechanism_price += getFieldPrice('mechanism_receiver_id_2', 0); 		// Ресивер

		// Месила хашмали
		if ( getFieldValue('vertical_selection', 0) == 523 )
		{
			// מסילה אלכסונית/ שיפועית
			mechanism_price = mechanism_price + getFieldPrice('mechanism_track_electric_diagonal', 0) * size_width;
		}
		else if ( getFieldValue('vertical_selection', 0) == 522 )
		{
			// מסילה מעוגלת
			mechanism_price = mechanism_price + getFieldPrice('mechanism_electric_track_orbicular_24V', 0) * size_width;
		}
		else
		{
			// מסילה ישרה
			mechanism_price = mechanism_price + getFieldPrice('mechanism_electric_track_24V', 0) * size_width;
		}
	}
	else if ( isChecked('mechanism_type_3') == 1 )
	{
		//************************************
		// 220V
		//************************************
		var mechanism_type_id		= 3;
		var mechanism_mechanical_id	= 0;
		var mechanism_engine_id		= getFieldValue('mechanism_engine_id_3', 0);
		
		mechanism_price  = getFieldPrice('mechanism_engine_id_3', 0); 			// Двигатель
		mechanism_price += getFieldPrice('mechanism_controller_id_3', 0); 		// Контроллер
		mechanism_price += getFieldPrice('mechanism_timer_id_3', 0); 			// Таймер
		mechanism_price += getFieldPrice('mechanism_receiver_id_3', 0); 		// Ресивер
		mechanism_price += getFieldPrice('roller_mechanism_adapter_for2', 0); 	// 
		mechanism_price += getFieldPrice('mechanism_weather_vane_sensor', 0); 	// 
		mechanism_price += getFieldPrice('mechanism_weather_vane', 0); 			// 
		mechanism_price += getFieldPrice('mechanism_rc_id_3', 0); 				// Пульт ДУ
		mechanism_price += getFieldPrice('tzinor_electric', 0); 				//
	}
	mechanism_price = mechanism_price * size_qty;
	
	// END: Подъемный механизм
	//*****************************************
	
	// Дополнительные цвета
	var color_combination_price = 0;
	
	var color_combination = parseInt(getFieldValue('additive_color_combination', 0));
	if ( color_combination == 407 )
	{
		// 10%
		color_combination_price = price_sum * 10 / 100;
	}
	else if ( color_combination == 408 )
	{
		// 20%
		color_combination_price = price_sum * 20 / 100;
	}
	else if ( color_combination == 409 )
	{
		// 30%
		color_combination_price = price_sum * 30 / 100;
	}

	// Вырезы
	if ( isChecked('is_crop_right') == 1 )
	{
		var crop_right = 1;
	}
	else
	{
		var crop_right = 0;
	}
	if ( isChecked('is_crop_left') == 1 )
	{
		var crop_left = 1;
	}
	else
	{
		var crop_left = 0;
	}
	
	//*****************************************
	// BEGIN: Установка
	var install_type_id = parseInt(getFieldValue('install_type_id', 0));
	
	var install_price = 0;
	
	if ( getField('install_type_id') )
	{
		install_price = getFieldPrice('install_type_id', 0) * size_qty;
	}
	else if ( getField('install_type_id_length') )
	{
		install_price = getFieldPrice('install_type_id_length', 0) * size_qty * size_width;
	}
	else if ( getField('install_type_id_sm') )
	{
		install_price = getFieldPrice('install_type_id_sm', 0) * area;
	}
	// END: Установка
	//*****************************************
	
	// Тосафот
	var additions_price = 0;
	additions_price +=  getFieldPrice('sewing_curtain_fabric_ratio_linen', 0) + 
						getFieldPrice('sewing_curtain_ring_color', 0) + 
						getFieldPrice('bind_curtain_selection', 0) + 
						getFieldPrice('mikado_curtain_bitna_sewing', 0) + 
						getFieldPrice('calculator_mikado_curtain_bitna_fabric', 0) + 
						getFieldPrice('sochecim_small_roof_atkana', 0) + 
						getFieldPrice('sochecim_small_roof', 0) + 
						getFieldPrice('sochecim_graphics', 0) + 
						getFieldPrice('sochecim_dofen_side', 0) + 
						getFieldPrice('sochecim_dofen_side_atkana', 0) + 
						getFieldPrice('arm_overlapping_sochecim', 0) + 
						getFieldPrice('tzinor', 0) + 
						price_cornice + 
						getFieldPrice('mikado_romi_tfirat_seret', 0);
						
	// Лента из ткани
	if( isChecked('additive_tape') == 1 )
	{
		additions_price += getFieldPrice('additive_tape_width', 0) * area;
	}
	
	// Итоговая сумма
	// !!! ВНИМАНИЕ !!! Не забыть здесь прибавлять к итоговой сумме промежуточные суммы !!!
	var total_price = price_sum + mechanism_price + cables_price + color_combination_price + install_price + additions_price;
	
	var total_price_full = total_price + (total_price * 15 / 100);
	
	//-----------------------------------------------------------------------------
	// Внести информацию в поля калькулятора
	//-----------------------------------------------------------------------------
	setFieldValue('calculator_qty', size_qty );
	setFieldValue('calculator_lm_fabric', number_format(calculator_lm_fabric, 2, ".", ",") );
	setFieldValue('calculator_sm', number_format(area, 2, ".", ",") );
	setFieldValue('calculator_sm_sum', number_format(price_sum, 2, ".", ",") );
	setFieldValue('calculator_mechanism', number_format(mechanism_price, 2, ".", ",") );
	setFieldValue('calculator_size_cables', number_format(cables_price, 2, ".", ",") );
	setFieldValue('calculator_additive_color_combination', number_format(color_combination_price, 2, ".", ",") );
	setFieldValue('calculator_install_type_id', number_format(install_price, 2, ".", ",") );
	setFieldValue('calculator_additions', number_format(additions_price, 2, ".", ",") );
	
	// Итоговая сумма
	setFieldValue('total_price', number_format(total_price, 2, ".", ",") );
	setFieldValue('total_price_full', number_format(total_price_full, 2, ".", ",") );
}
