/* РАБОТА С AJAX */
/*-----------------------------------------------------------------------------------------------------*/
var request;

function createRequest()
{
	try
	{
		request = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try
		{
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try
			{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				request = false;
			}
		}
	}
}

createRequest();

if (!request)
	alert("Error initializing XMLHttpRequest!");
	
/*-----------------------------------------------------------------------------------------------------*/

/* РАБОТА С COOKIE */
/*-----------------------------------------------------------------------------------------------------*/

/* Чтение cookie */
function getCookie(name)
{
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

/* Создание cookie */
function setCookie (name, value, expires, path, domain, secure)
{
	document.cookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
}

/* Удаление cookie */
function deleteCookie(name)
{
	if (getCookie(name))
	{
		document.cookie = name + "=" + 
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

/* Проверка возможности работать с cookie */
function SetIsCookie()
{
	setCookie("test", "set");
	if (getCookie("test"))
		return true;
	else
		return false;
}

/*-----------------------------------------------------------------------------------------------------*/

/* Добавление дочернего элемента в узел */
function append( parent, elem ){
       var node = elem && elem.constructor == String ?
                       document.createTextNode(elem) : elem;
       parent.appendChild(node);
}

/* Удаление дочерних элементов узла node (передается ID узла) */
function removeChildrenRecursively(node)
{
	if (!node) return;
	while (node.hasChildNodes()) {
		removeChildrenRecursively(node.firstChild);
		node.removeChild(node.firstChild);
    }
}

/*-----------------------------------------------------------------------------------------------------*/

/* Удаление узла (передается ID узла) */
function removeElementById(nodeId) {
	document.getElementById(nodeId).parentNode.removeChild(document.getElementById(nodeId));
}

/* Вывод параграфа в листе заказа */
function showContentParagraph(id, title, count, price)
{
	var price1 = price * count;
	var txtstring = title+"<br />"+count+" шт. - <span class=\"pink\">"+price1+"</span> руб.<a onclick=\"javascript:addOk("+id+");\"><img class=\"button\" src=\"img/button_add.gif\" /></a><a onclick=\"javascript:subOk("+id+");\"><img class=\"button\" src=\"img/button_sub.gif\" /></a><a onclick=\"javascript:deleteOk("+id+");\"><img class=\"button\" src=\"img/button_close.gif\" /></a>";
	return txtstring;
}

// создание полной суммы заказа
function createFullSum()
{
	var full_sum = 0; // сумма всего заказа
	var order_array = document.cookie.split("; ");
	for (i=0; i<order_array.length; i++)
	{
		if (order_array[i].indexOf("c-sushi") == 0)
		{
			var sushi_id = order_array[i].substring(7, order_array[i].indexOf("="));
			var sushi_params = unescape(order_array[i].substring(order_array[i].indexOf("=")+4));
			sushi_params = sushi_params.split("|");
			var sushi_title = sushi_params[0];
			var sushi_count = sushi_params[1];
			var sushi_price  = sushi_params[2];
			var sushi_price1 = sushi_price * sushi_count;
			if (sushi_count > 0)
				full_sum = full_sum + sushi_price1;
		}
	}
	return full_sum;
}

function createFormDateTime()
{
	var result = "";
	var currentdate = new Date();
	var current_day = currentdate.getDate();
	var current_month = currentdate.getMonth();
	current_month++;
	var current_year = currentdate.getFullYear();
	var current_hour = currentdate.getHours();
	var i = 0;
	// день
	result = result + "<select name=\"day\">";
	for (i=1; i<32; i++)
	{
		if (i == current_day)
			result = result + "<option value=\""+i+"\" selected>"+i+"</option>";
		else
			result = result + "<option value=\""+i+"\">"+i+"</option>";
	}
	result = result + "</select>";
	// месяц
	result = result + "<select name=\"month\">";
	result = result + "<option value=\"1\">января</option>";
	result = result + "<option value=\"2\">февраля</option>";
	result = result + "<option value=\"3\">марта</option>";
	result = result + "<option value=\"4\">апреля</option>";
	result = result + "<option value=\"5\">мая</option>";
	result = result + "<option value=\"6\">июня</option>";
	result = result + "<option value=\"7\">июля</option>";
	result = result + "<option value=\"8\">августа</option>";
	result = result + "<option value=\"9\">сентября</option>";
	result = result + "<option value=\"10\">октября</option>";
	result = result + "<option value=\"11\">ноября</option>";
	result = result + "<option value=\"12\">декабря</option>";
	result = result + "</select>";
	// год
	result = result + "<select name=\"year\">";
	result = result + "<option value=\""+current_year+"\">"+current_year+"</option>";
	current_year++;
	result = result + "<option value=\""+current_year+"\">"+current_year+"</option>";
	result = result + "</select>";
	result = result + "&nbsp;&nbsp;&nbsp;&nbsp;";
	// час
	result = result + "<select name=\"hour\">";
	for (i=12; i<25; i++)
	{
		if (i == current_hour + 1)
			result = result + "<option value=\""+i+"\" selected>"+i+"</option>";
		else
			result = result + "<option value=\""+i+"\">"+i+"</option>";
	}
	result = result + "</select>";
	result = result + "&nbsp;:&nbsp;";
	// минута
	result = result + "<select name=\"minute\">";
	result = result + "<option value=\"00\">00</option>";
	result = result + "<option value=\"15\">15</option>";
	result = result + "<option value=\"30\">30</option>";
	result = result + "<option value=\"45\">45</option>";
	result = result + "</select>";
	return result;
}

function createFormPersons()
{
	var i = 0;
	var result = "<select name=\"persons\">";
	for (i=1; i<21; i++)
		result = result + "<option value=\""+i+"\">"+i+"</option>";
	result = result + "</select>";
	return result;
}

function createOrderIDs()
{
	var full_sum = 0; // сумма всего заказа
	var order_array = document.cookie.split("; ");
	var arrayIDs = '';
	for (i=0; i<order_array.length; i++)
	{
		if (order_array[i].indexOf("c-sushi") == 0)
		{
			var sushi_id = order_array[i].substring(7, order_array[i].indexOf("="));
			var sushi_params = unescape(order_array[i].substring(order_array[i].indexOf("=")+4));
			sushi_params = sushi_params.split("|");
			var sushi_title = sushi_params[0];
			var sushi_count = sushi_params[1];
			var sushi_price  = sushi_params[2];
			var sushi_price1 = sushi_price * sushi_count;
			if (sushi_count > 0)
			{
//				arrayIDs = arrayIDs+"|"+sushi_id+"|"+sushi_count;
				arrayIDs = arrayIDs + "\n"+sushi_title+" ("+sushi_count+" шт.) - "+sushi_price1+" руб.";
				full_sum = full_sum + sushi_price1;
			}
		}
	}
	arrayIDs = arrayIDs + "\n\nОбщая сумма заказа - "+full_sum+" руб.";
	return arrayIDs;
}

// добавить в заказ/увеличить количество
function addOk(id) // на входе - ID товара
{
	var count_cookie = 0;
	if (getCookie("c-sushi"+id))
	{
		var array_cookie = getCookie("c-sushi"+id);
		var array_cookie = array_cookie.split("|");
		var title_cookie = array_cookie[1];
		var count_cookie = array_cookie[2];
		var price_cookie = array_cookie[3];
	} else {
		var title_cookie = document.getElementById("sushi_title"+id);
		title_cookie = title_cookie.firstChild.nodeValue;
		var price_cookie = document.getElementById("sushi_price"+id);
		price_cookie = price_cookie.firstChild.nodeValue;
	}
	
	count_cookie++;
	setCookie("c-sushi"+id, "|"+title_cookie+"|"+count_cookie+"|"+price_cookie); // в cookie товара вписываем количество
	// отображаем это на экране
	if (document.getElementById("c-sushi"+id))
		document.getElementById("c-sushi"+id).innerHTML = count_cookie;
	// правим лист заказа
	if (!document.getElementById(id))
	{
		var p_id = document.createElement("p");
		p_id.id = ""+id+"";
		p_id.appendChild(document.createTextNode(""));
		document.getElementById("sushi_order_list").appendChild(p_id);
	}
	document.getElementById(id).innerHTML = showContentParagraph(id, title_cookie, count_cookie, price_cookie);
	// меняем общую сумму заказа
	if (document.getElementById("full_sum"))
		document.getElementById("full_sum").innerHTML = "<br />Сумма заказа без скидки:<br />"+createFullSum()+" руб.";
}

// уменьшить количество
function subOk(id) // на входе - ID товара
{
	var array_cookie = getCookie("c-sushi"+id);
	array_cookie = array_cookie.split("|");
	title_cookie = array_cookie[1];
	count_cookie = array_cookie[2];
	price_cookie = array_cookie[3];
	if (count_cookie > 0)
	{
		count_cookie--;
		setCookie("c-sushi"+id, "|"+title_cookie+"|"+count_cookie+"|"+price_cookie); // в cookie товара вписываем количество
		// отображаем это на экране
		if (document.getElementById("c-sushi"+id))
			document.getElementById("c-sushi"+id).innerHTML = count_cookie;
		// меняем общую сумму заказа
		if (document.getElementById("full_sum"))
			document.getElementById("full_sum").innerHTML = "<br />Сумма заказа без скидки:<br />"+createFullSum()+" руб.";
		// правим лист заказа
		if (count_cookie == 0)
		{
			removeElementById(id);
			deleteCookie("c-sushi"+id);
		} else {
			document.getElementById(id).innerHTML = showContentParagraph(id, title_cookie, count_cookie, price_cookie);
		}
	}
}

// удалить товар из заказа
function deleteOk(id) // на входе - ID товара
{
	if (document.getElementById("c-sushi"+id))
		document.getElementById("c-sushi"+id).innerHTML = 0;
	setCookie("c-sushi"+id, "");
	removeElementById(id);
	deleteCookie("c-sushi"+id);
	// меняем общую сумму заказа
	if (document.getElementById("full_sum"))
		document.getElementById("full_sum").innerHTML = "<br />Сумма заказа без скидки:<br />"+createFullSum()+" руб.";
	return true;
}

/* Очистка заказа */
function clearOrder()
{
	var id = 0;
	var order_array = document.cookie.split("; ");
	var cnt = order_array.length;
	for (i=0; i<order_array.length; i++)
	{
		if (order_array[i].indexOf("c-sushi") == 0) // если это cookie товара
		{
			id = order_array[i].substring(7, order_array[i].indexOf("="));
			setCookie("c-sushi"+id, "");
		}
	}
}

function clearOrder1()
{
	clearOrder();
	window.location.reload(true);
}

/* Вывод листа заказа */
function showOrderInMenu()
{
	var name = getCookie("test");
	if (name != null) // если есть возможность работать с cookies
	{
		var order_array = document.cookie.split("; ");
		document.write("<div id=\"sushi_order\">");
			document.write("<img src=\"img/order_header.png\" />");
			document.write("<div id=\"sushi_order_list\">");
			for (i=0; i<order_array.length; i++)
			{
				if (order_array[i].indexOf("c-sushi") == 0)
				{
					var sushi_id = order_array[i].substring(7, order_array[i].indexOf("="));
					var sushi_params = unescape(order_array[i].substring(order_array[i].indexOf("=")+4));
					sushi_params = sushi_params.split("|");
					var sushi_title = sushi_params[0];
					var sushi_count = sushi_params[1];
					var sushi_price  = sushi_params[2];
					if (sushi_count > 0)
					{
						var txtstring = "<p id=\""+sushi_id+"\">" + showContentParagraph(sushi_id, sushi_title, sushi_count, sushi_price) + "</p>";
						document.write(txtstring);
					}
				}
			}
			document.write("</div>");
		document.write("<div id=\"sushi_order_footer\"><p id=\"full_sum\"><br />Сумма заказа без скидки:<br />"+createFullSum()+" руб.</p><a href=\"order.php\"><img src=\"img/order_list_submit.gif\" /></a></div>");
		document.write("</div>");
	}
}

/* Вывод листа заказа в разделе "Ваш заказ" */
function showOrderList()
{
	var full_sum = 0; // сумма всего заказа
	var order_array = document.cookie.split("; ");
	document.write("<div id=\"sushi_order1\">");
	document.write("<table id=\"full_order\" cellpadding=\"0\" cellspacing=\"1\">");
		for (i=0; i<order_array.length; i++)
		{
			if (order_array[i].indexOf("c-sushi") == 0)
			{
				var sushi_id = order_array[i].substring(7, order_array[i].indexOf("="));
				var sushi_params = unescape(order_array[i].substring(order_array[i].indexOf("=")+4));
				sushi_params = sushi_params.split("|");
				var sushi_title = sushi_params[0];
				var sushi_count = sushi_params[1];
				var sushi_price  = sushi_params[2];
				var sushi_price1 = sushi_price * sushi_count;
				if (sushi_count > 0)
				{
					document.write("<tr><td class=\"title\">"+sushi_title+"</td><td>"+sushi_count+" шт.</td><td>"+sushi_price1+" руб.</td></tr>");
					full_sum = full_sum + sushi_price1;
				}
			}
		}
	document.write("<tr><td colspan=\"2\" class=\"itog\">Сумма заказа без скидки:</td><td><b><span class=\"pink\">"+full_sum+" руб.</span></b></td></tr>");
	document.write("</table>");
	document.write("</div>");
}

function sendForm()
{
	if (document.forms[0].name2.value == "")
	{
		alert('Не все обязательные поля были заполнены');
		document.mailform.name.focus();
		return false;
	}
	if (document.forms[0].phone.value == "")
	{
		alert('Не все обязательные поля были заполнены');
		document.mailform.name.focus();
		return false;
	}
	if (document.forms[0].street.value == "")
	{
		alert('Не все обязательные поля были заполнены');
		document.mailform.name.focus();
		return false;
	}
	if (document.forms[0].house.value == "")
	{
		alert('Не все обязательные поля были заполнены');
		document.mailform.name.focus();
		return false;
	}
	if (document.forms[0].office.value == "")
	{
		alert('Не все обязательные поля были заполнены');
		document.mailform.name.focus();
		return false;
	}
	document.getElementById("client_order_form").submit();
	clearOrder();
}

/* Вывод формы для контактных данных */
function showOrderForm()
{
	var datetime = createFormDateTime();
	var persons = createFormPersons();
	var order_ids = createOrderIDs();
	document.write("<form id=\"client_order_form\" method=\"post\"><table class=\"order_form\">");
	document.write("<tr><td class=\"order_form_title\">Фамилия:</td><td><input type=\"Text\" name=\"name1\" maxlength=\"50\" size=\"37\" /></td></tr>");
	document.write("<tr><td class=\"order_form_title\"><span class=\"pink\">*</span> Имя:</td><td><input type=\"Text\" name=\"name2\" maxlength=\"50\" size=\"37\" /></td></tr>");
	document.write("<tr><td class=\"order_form_title\">Отчество:</td><td><input type=\"Text\" name=\"name3\" maxlength=\"50\" size=\"37\" /></td></tr>");
	document.write("<tr><td class=\"order_form_title\"><span class=\"pink\">*</span> Телефон:</td><td><input type=\"Text\" name=\"phone\" maxlength=\"50\" size=\"37\" /></td></tr>");
	document.write("<tr><td class=\"order_form_title\"><span class=\"pink\">*</span> Улица:</td><td><input type=\"Text\" name=\"street\" maxlength=\"50\" size=\"37\" /></td></tr>");
	document.write("<tr><td class=\"order_form_title\"><span class=\"pink\">*</span> Дом:</td><td><input type=\"Text\" name=\"house\" maxlength=\"10\" size=\"10\" /></td></tr>");
	document.write("<tr><td class=\"order_form_title\"><span class=\"pink\">*</span> Квартира (офис):</td><td><input type=\"Text\" name=\"office\" maxlength=\"4\" size=\"4\" /></td></tr>");
	document.write("<tr><td class=\"order_form_title\">Дата и время доставки:</td><td>"+datetime+"</td></tr>");
	document.write("<tr><td class=\"order_form_title\">Количество персон:</td><td>"+persons+"</td></tr>");
	document.write("<tr><td class=\"order_form_title\">Примечания:</td><td><textarea name=\"comment\" rows=\"3\" cols=\"35\"></textarea></td></tr>");
	document.write("<tr><td colspan=\"2\" align=\"right\"><i><span class=\"pink\">*</span> - обязательно для заполнения&nbsp;&nbsp;&nbsp;</i></td></tr>");
	document.write("<tr><td>&nbsp;</td><td><input type=\"Button\" class=\"button\" value=\"Отправить заказ\" onclick=\"sendForm();\" />&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"Reset\" class=\"button\" value=\"Отменить заказ\" onclick=\"javascript:clearOrder1();\" /></td></tr>");
	document.write("</table><input type=\"HIdden\" name=\"order_ids\" value=\""+order_ids+"\" /><input type=\"Hidden\" name=\"action\" value=\"create_order\" /></form>");
}

function addSmallFormOrder(id)
{
	var title_cookie = '';
	var count_cookie = '';
	if (name != null) // если есть возможность работать с cookies
	{
		if (getCookie("c-sushi"+id))
		{
			var array_cookie = getCookie("c-sushi"+id);
			array_cookie = array_cookie.split("|");
			title_cookie = array_cookie[1];
			count_cookie = array_cookie[2];
		} else {
			count_cookie = 0;
		}
		
		document.write("<div class=\"small_form_order\">");
		document.write("Заказать: ");
		document.write("<span class=\"white_bg\" id=\"c-sushi"+id+"\">"+count_cookie+"</span>");
		document.write("<a onclick=\"javascript:addOk("+id+");\"><img src=\"img/button_add.gif\" /></a>");
		document.write("<a onclick=\"javascript:subOk("+id+");\"><img src=\"img/button_sub.gif\" /></a>");
		document.write("</div>");
	}
}

/* LIGHTBOX */
/*-----------------------------------------------------------------------------------------------------*/

// Размер документа по вертикали
function getDocumentHeight()
{
	return (document.body.scrollHeight > document.body.offsetHeight)?document.body.scrollHeight:document.body.offsetHeight;
}

// Размер документа по горизонтали
function getDocumentWidth()
{
	return (document.body.scrollWidth > document.body.offsetWidth)?document.body.scrollWidth:document.body.offsetWidth;
}

function showLightBox(id)
{
	var width = document.documentElement.clientWidth;
	var height = document.documentElement.clientHeight;
	if (document.getElementById("body"))
	{
		var div_id = document.createElement("div");
		div_id.id = "gray_layer";
		div_id.style.height = height+"px";
		document.getElementById("body").appendChild(div_id);
		
		div_id = document.createElement("div");
		div_id.id = "sushi_info";
		div_id.style.top = (height / 2) - 100 +"px";
		div_id.style.left = (width / 2) - 275 +"px";
		document.getElementById("body").appendChild(div_id);
		document.getElementById("sushi_info").innerHTML = "test.php";
	}
}

/*-----------------------------------------------------------------------------------------------------*/
