var xmlHttp = null;
var menu_div = null;

function ajax_connect()
{
	if (!xmlHttp)
	{
		try
		{
			// Для всех, кроме IE6 и позже
			xmlHttp = new XMLHttpRequest();
		}
		catch(e)
		{
			var xmlVers = new Array ("MSXML2.XMLHTTP.6.0",
																"MSXML2.XMLHTTP.5.0",
																"MSXML2.XMLHTTP.4.0",
																"MSXML2.XMLHTTP.3.0",
																"MSXML2.XMLHTTP",
																"Microsoft.XMLHTTP");
			// Перебираем возможные варианты, пока не получится
			for (var i=0; i<xmlVers.length && !xmlHttp; i++)
			{
				try
				{
					xmlHttp = new ActiveXObject(xmlVers[i]);
				}
				catch(e) {}
			}
		}
	}

	if (!xmlHttp)
	{
		alert ("К сожалению, Ваш браузер не поддерживает технологию Ajax, с помощью которой реализована отправка быстрого заказа. Позвоните, пожалуйста, нашим менеджерам по телефону и выскажите им все лично.");
		return false;
	}

	return true;
}

function ajax_get_query_string(in_query_array)
{
	var p_query = "";
	for (var i in in_query_array)
	{
		p_query = p_query + "&" + i + "=" + in_query_array[i];
	}

	return p_query;
}

function send_FastOrder()
{
	if (!xmlHttp)
	{
		if (!ajax_connect())
			return false;
	}

	var query = new Array();
	query["txt_usermsg"] = document.getElementById("user_msg").value;
	query["txt_usercontact"] = document.getElementById("txt_contact").value;
	query["operation"] = "";
	query["type"] = "";

	var r_count = document.getElementsByName("r_operation").length;
	for (var i = 0; i < r_count; i++)
	{
		if (document.getElementsByName("r_operation").item(i).checked)
		{
			query["operation"] = document.getElementsByName("r_operation").item(i).value;
			break;
		}
	}

	var r_count = document.getElementsByName("r_type").length;
	for (var i = 0; i < r_count; i++)
	{
		if (document.getElementsByName("r_type").item(i).checked)
		{
			query["type"] = document.getElementsByName("r_type").item(i).value;
			break;
		}
	}

	if ((!query["txt_usermsg"]) || (!query["txt_usercontact"]))
	{
		if (((!query["txt_usermsg"]) && (!query["txt_usercontact"])))
			alert ('Опишите, пожалуйста, заявку в поле "Комментарий" и оставьте удобные контактные данные в поле "Для контакта"');
		else if (!query["txt_usermsg"])
			alert ('Опишите, пожалуйста, заявку в поле "Комментарий"');
		else
			alert ('Оставьте, пожалуйста, удобные контактные данные в поле "Для контакта"');
		return false;
	}
	else
	{
		if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
		{
			var p_query = ajax_get_query_string(query);

			xmlHttp.open("post", "/_inc/fast_order.php", true);
			xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=windows-1251");
			xmlHttp.onreadystatechange = resp_FastOrder;

			xmlHttp.send(p_query);

			return true;
		}
		else
		{
			// Повторяем через секунду
			setTimeout("send_FastOrder(" + xmlHttp + ")", 1000);
		}
	}

	return true;
}

function resp_FastOrder()
{
	if (xmlHttp.readyState == 4)
	{ try {
		if (xmlHttp.status == 200)
		{
			if (xmlHttp.responseText == "Good")
			{
				document.getElementById("quick_form").style.display = "none";
				document.getElementById("quick_form_result").style.display = "block";
			}
			else
			{
				alert (xmlHttp.responseText);
			}
		}
		else
				alert('Ошибки во время транзакции ' + xmlHttp.statusText);
	} catch(e)
		{ alert (e.toString()); }
	}
}


function send_MenuQuery()
{
	if (!xmlHttp)
	{
		if (!ajax_connect())
			return false;
	}

	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
	{
		xmlHttp.open("post", "/_inc/get_menu.php", true);
		xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=windows-1251");
		xmlHttp.onreadystatechange = resp_MenuQuery;

		xmlHttp.send();

		return true;
	}
	else
	{
		// Повторяем через секунду
		setTimeout("send_MenuQuery()", 1000);
	}


	return true;
}

function resp_MenuQuery()
{
	if (xmlHttp.readyState == 4)
	{
		try {
		if (xmlHttp.status == 200)
		{
			//alert (xmlHttp.responseText);

			eval(xmlHttp.responseText);
			var div_body = '<div style="float: left; position: relative; width: 55%; padding: 5px;"><div>Введите текст, с которого должна быть ссылка или оставьте поле пустым, чтобы текстом стало название пункта<br><input type="text" style="width: 95%" id="txt_link_text"></div>';
			for(i in full_menu)
			{
				div_body = div_body + '<div style="padding-left: ' + (parseInt(full_menu[i].level) * 15) + 'px;">' +
					'<span onclick="GetLinkTag(' + i + ');"><u>' + full_menu[i].Name + '</u></span></div>';
			}

			div_body = div_body + '</div><div style="float: left; position: relative; width: 40%; padding: 5px;">Нажмите на выбранный пункт меню и вставьте код, который появится в окне ниже, в нужное место документа.<br><textarea id="txt_link_tag" style="width: 95%; height: 200px;"></textarea></div>';

			div_body = div_body + '<p style="clear: both;" align="right"><small onclick="hide_menu_div();">закрыть</small></p>';

			document.getElementById("menu_div").innerHTML = div_body;


			/*
			if (xmlHttp.responseText == "Good")
			{
				document.getElementById("quick_form").style.display = "none";
				document.getElementById("quick_form_result").style.display = "block";
			}
			else
			{
				alert (xmlHttp.responseText);
			}*/
		}
		else
				alert('Ошибки во время транзакции ' + xmlHttp.statusText);
	} catch(e)
		{ alert (e.toString()); }
	}
}

function GetLinkTag(in_elem)
{
	// Получает тег для построения ссылки с выбранным элементом in_elem
	var area_body = '<a href="' + full_menu[in_elem].Address + '">';
	if (document.getElementById("txt_link_text").value)
		area_body = area_body + document.getElementById("txt_link_text").value;
	else
		area_body = area_body + full_menu[in_elem].Name;

	area_body = area_body + "</a>"

	document.getElementById("txt_link_tag").value = area_body;

}

function show_menu_div()
{
	if (!menu_div)
	{
		send_MenuQuery();
		menu_div = document.createElement('div');
		var div_body = '<p align="center"><img src="/_img/wait.gif"><br>Подождите, идет загрузка</p>' +
									'<p align="right"><small onclick="hide_menu_div();">закрыть</small></p>';
		menu_div.innerHTML = div_body;
		document.getElementById("menu_div").appendChild(menu_div);
	}
	document.getElementById("menu_div").style.display = 'block';

	return true;
}

function hide_menu_div()
{
	document.getElementById("menu_div").style.display = 'none';
}

function btn_NewFastOrder()
{
	document.getElementById("div_FastOrder").style.display = "block";
	document.getElementById("good_FastOrder").style.display = "none";
	document.getElementById("fast_order_err").innerHTML = "";
	document.getElementById("txt_usertext").value = '';
	document.getElementById("txt_usercontact").value = '';
}

function OffsetPos(obj)
{
	// Определяет координаты объекта
  var currleft = 0;
  var currtop = 0;
  // parentNode
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      currleft += obj.offsetLeft;
      currtop += obj.offsetTop;
      obj = obj.offsetParent;
    }
  }
  else
  {
  	 if (obj.x) currleft += obj.x;
  	 if (obj.y) currtop += obj.y;
  }

  return {Left: currleft, Top: currtop};
}

function ShowMe(in_show_obj, in_parent_obj)
{
	var my_parent_pos = OffsetPos(in_parent_obj);
	in_show_obj.style.left = parseInt(my_parent_pos.Left) - 1 + "px";
	in_show_obj.style.top = parseInt(my_parent_pos.Top) + parseInt(in_parent_obj.offsetHeight) - 14 + "px";
	if (!in_show_obj.style.width)
	{
		if (in_show_obj.offsetWidth < in_parent_obj.offsetWidth)
			in_show_obj.style.width = in_parent_obj.offsetWidth + "px";
		else
			in_show_obj.style.width = in_show_obj.offsetWidth + "px";

	}
	var pole = parseInt((document.body.offsetWidth - 1000) / 2);

	if ((parseInt(in_show_obj.offsetWidth) + parseInt(my_parent_pos.Left)) > (document.body.offsetWidth - pole))
	{
		var new_left = (my_parent_pos.Left - ((in_show_obj.offsetWidth / 2)- in_parent_obj.offsetWidth)) + 2;

		if ((new_left + parseInt(in_show_obj.offsetWidth)) > (document.body.offsetWidth - pole))
			new_left = new_left - (in_show_obj.offsetWidth / 2);
		if (new_left < 0)
			in_show_obj.style.left = "10px";
		else
			in_show_obj.style.left = new_left + "px";
	}


	//alert (in_show_obj.offsetWidth);
	in_show_obj.style.visibility = "visible";



	return true;
}

function HideMe(in_obj)
{
	in_obj.style.visibility = "hidden";

	return true;
}

function AllPict()
{
	var p_Images = new Array();
	var p_cur_index = 0;
	var p_Div = null;

	function p_showimg()
	{
		// Показывает с заданным индексом
		p_Div.style.backgroundImage = "url('" + p_Images[p_cur_index]["Name"] + "')";
		p_Div.style.width = p_Images[p_cur_index]["Width"] + "px";
		p_Div.style.height = p_Images[p_cur_index]["Height"] + "px";
		if (p_Images[p_cur_index]["BigName"] != "/")
		{
			p_Div.style.cursor = "pointer";
			p_Div.innerHTML = '<img src="/_img/plus.png" width="11" height="11" alt="big" style="position:relative; top: ' + (parseInt(p_Images[p_cur_index]["Height"]) - 20) + 'px; left: ' + (parseInt(p_Images[p_cur_index]["Width"]) - 20) + 'px;">';
			//alert ('<img src="/_img/plus.png" width="11" height="11" alt="big" style="position:relative; top: ' + (parseInt(p_Images[p_cur_index]["BigHeight"]) - 20) + 'px; left: ' + (parseInt(p_Images[p_cur_index]["BigWidth"]) - 20) + 'px;">');
			p_Div.onclick = function()
			{
				window.open(p_Images[p_cur_index]["BigName"], '_blank','width=' + p_Images[p_cur_index]["BigWidth"] + ', height='+ p_Images[p_cur_index]["BigHeight"] +', titlebar=no, toolbar=no, location=no, status=no, menubar=no, scrollbars=no, resizable=no');
				return false;
			}
		}
		else
		{
			p_Div.style.cursor="auto";
			p_Div.onclick = null;
			p_Div.innerHTML = '';
		}

	}

	this.AddPict = function(in_imgName, in_imgWidth, in_imgHeight, in_imgNameBig, in_imgWidthBig, in_imgHeightBig)
	{
		var new_img_index = parseInt(p_Images.length);
		p_Images[new_img_index] = new Array();
		p_Images[new_img_index]["Name"] = in_imgName;
		p_Images[new_img_index]["Width"] = in_imgWidth;
		p_Images[new_img_index]["Height"] = in_imgHeight;
		p_Images[new_img_index]["BigName"] = in_imgNameBig;
		p_Images[new_img_index]["BigWidth"] = in_imgWidthBig;
		p_Images[new_img_index]["BigHeight"] = in_imgHeightBig;

		return true;
	}

	this.MoveNext = function()
	{
		p_cur_index = p_cur_index + 1;
		if (p_cur_index == p_Images.length)
			p_cur_index = 0;

		p_showimg();
	}

	this.MovePrev = function()
	{
		p_cur_index = p_cur_index - 1;
		if (p_cur_index < 0)
			p_cur_index = p_Images.length - 1;

		p_showimg();
	}

	this.ShowImg = function(in_div_id)
	{
		p_Div = document.getElementById(in_div_id);
		p_showimg();
	}
}

function AttrCollection(in_div_name)
{
	var p_Attrs = new Array();
	this.Div = document.getElementById(in_div_name);

	this.AddAttr = function(in_id, in_Title, in_Name, in_Value)
	{
		p_Attrs[in_id] = new OneAttr(in_id, in_Title, in_Name, in_Value);

		return true;
	}

	this.ShowAll = function()
	{
		var show_ct = "";
		for (var i in p_Attrs)
		{
			show_ct = show_ct + p_Attrs[i].ADiv;
		}

		this.Div.innerHTML = show_ct;

		return true;
	}

}

function OneAttr(in_id, in_Title, in_Name, in_Value)
{
	this.AName = in_Name;
	this.id_A = in_id;
	this.ATitle = in_Title;
	this.AValue = in_Value;

	this.ADiv = '<div class="form_capt">' + this.ATitle + '</div><input type="text" name="' + this.AName + '[' + this.id_A + ']" style="width: 100%;" value="' + this.AValue + '" id="' + this.AName + this.id_A + '"/>';

}
