﻿//---------------------------------------------------------------------------------
// радактирование "моих данных"
function editMyData(action, obj)
{
	if (obj.src.indexOf('edit') > 0) // если "изменить"
	{
		var src = obj.src.replace('edit', 'save');
		obj.src = src;
		obj.alt = 'сохранить';
		obj.title = 'сохранить';
		
		var fields = new Array('name', 'email', 'phone', 'post_index', 'address', 'region');
		for (var i = 0; i < fields.length; i++)
		{
			document.getElementById(fields[i]).className = 'text_wide';
			document.getElementById(fields[i]).nextSibling.className = 'value_hide';
		}
	}
	else // если "сохранить"
	{
		var src = obj.src.replace('save', 'edit');
		obj.src = src;
		obj.alt = 'изменить';
		obj.title = 'изменить';
		
		var sBody = '';
		var field = '';
		var fields = new Array('name', 'email');
		for (var i = 0; i < fields.length; i++)
		{
			field = document.getElementById(fields[i]).value;
			if (trim(field) == '') { alert('Заполните поле "' + document.getElementById(fields[i]).previousSibling.innerHTML + '"'); document.getElementById(fields[i]).focus(); return; }
			sBody += '&' + fields[i] + '=' + encodeURIComponent(field);
		}
		sBody += '&phone=' + encodeURIComponent(document.getElementById('phone').value);
		sBody += '&post_index=' + encodeURIComponent(document.getElementById('post_index').value);
		sBody += '&address=' + encodeURIComponent(document.getElementById('address').value);
		sBody += '&region=' + encodeURIComponent(document.getElementById('region').value);
		
		var oXmlHttp = zXmlHttp.createRequest();
		oXmlHttp.open('POST', action, true);
		oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		oXmlHttp.onreadystatechange = function () {
			if (oXmlHttp.readyState == 4)
			{
				if (oXmlHttp.status == 200) 
				{ //alert(oXmlHttp.responseText);
					if (oXmlHttp.responseText == '')
					{
						var val = '';
						var fields = new Array('name', 'email', 'phone', 'post_index', 'address', 'region');
						for (var i = 0; i < fields.length; i++)
						{
							val = document.getElementById(fields[i]).nextSibling;
							field = document.getElementById(fields[i]);
							
							val.innerHTML = field.value;
							field.className = 'text_hide';
							val.className = 'value';
						}
						closePopup('popup-text');
						window.location.reload();
						alert('Данные успешно изменены!');
					}
					else // если ошибка
					{
						closePopup('popup-text');
						alert("Ошибка!\n\n" + oXmlHttp.responseText);
					}
				}
				else
					alert("Ошибка!\n\n" + oXmlHttp.statusText);
			}	
		}; oXmlHttp.send(sBody);
		showPopup('popup-text', 'Идет обработка данных...');
	}
}
//---------------------------------------------------------------------------------
// добавление товара в корзину
function addToBasket(action)
{
	showPopup('popup-text', 'Идет добавление в корзину...');
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open('GET', action, true);
	oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4)
		{
			if (oXmlHttp.status == 200) 
			{ //alert(oXmlHttp.responseText);
				closePopup('popup-text');
				if (oXmlHttp.responseText == '')
				{
					// изменение цифры рядом с ссылкой "корзина" в верхнем меню
					var last = document.getElementById('basket').innerHTML;
					var temp = last == '' ? 0 : parseInt(document.getElementById('basket').innerHTML.substring(1));
					document.getElementById('basket').innerHTML = '(' + (temp + 1) + ')';
					// вариант с всплывающим окном
					//showPopup('popup-add-to-basket');
					// вариант без окна
					window.location.reload();
				}
				else // если ошибка
					alert("Ошибка!\n\n" + oXmlHttp.responseText);
			}
			else
				alert("Ошибка!\n\n" + oXmlHttp.statusText);
		}	
	}; oXmlHttp.send(null);
}
//---------------------------------------------------------------------------------
// удаление товара из корзины
function delOutOfBasket(action, obj)
{
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open('GET', action, true);
	oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4)
		{
			if (oXmlHttp.status == 200) 
			{ //alert(oXmlHttp.responseText);
				var cost_and_count = oXmlHttp.responseText.split('|');
				if (cost_and_count[0] != null && cost_and_count[1] != null)
				{
					obj.parentNode.parentNode.removeChild(obj.parentNode);
					document.getElementById('all_count').innerHTML = cost_and_count[0];
					document.getElementById('all_cost').innerHTML = cost_and_count[1] + ' р.';
					// изменение цифры рядом с ссылкой "корзина" в верхнем меню
					var last = document.getElementById('basket').innerHTML;
					var temp = last == '' ? 1 : parseInt(document.getElementById('basket').innerHTML.substring(1));
					document.getElementById('basket').innerHTML = '(' + (temp - 1) + ')';
					// --
					closePopup('popup-text');
				}
				else // если ошибка
					alert("Ошибка!\n\n" + oXmlHttp.responseText);
			}
			else
				alert("Ошибка!\n\n" + oXmlHttp.statusText);
		}	
	}; oXmlHttp.send(null);
	showPopup('popup-text', 'Идет удаление покупки из корзины...');
}
//---------------------------------------------------------------------------------
// пересчитывание покупки
function reCount()
{
	var recount = document.forms['recount'].elements;
	if (recount.length < 1)
	{
		alert('Корзина пуста!');
		return;
	}
	for (var i = 0; i < recount.length; i++)
	{
		var temp = parseInt(recount.item(i).value);
		if (isNaN(temp) || temp == 0) temp = 1;
		recount.item(i).value = temp < 0 ? (0 - temp) : temp;
	}
	
	var oForm = document.forms['recount'];
	var sBody = getRequestBody(oForm);
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open('POST', oForm.action, true);
	oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4)
		{
			if (oXmlHttp.status == 200) 
			{ //alert(oXmlHttp.responseText);
				var cost_and_count = oXmlHttp.responseText.split('|');
				if (cost_and_count[0] != null && cost_and_count[1] != null)
				{
					document.getElementById('all_count').innerHTML = cost_and_count[0];
					document.getElementById('all_cost').innerHTML = cost_and_count[1] + ' р.';
					closePopup('popup-text');
				}
				else // если ошибка
					alert("Ошибка!\n\n" + oXmlHttp.responseText);
			}
			else
				alert("Ошибка!\n\n" + oXmlHttp.statusText);
		}	
	}; oXmlHttp.send(sBody);
	showPopup('popup-text', 'Идет пересчитывание покупки...');
}
//---------------------------------------------------------------------------------
// вход в магазин
function enterToShop(action, myData)
{
	var login = document.getElementById('login').value;
	var password = document.getElementById('password').value;
	var save = document.getElementById('save').checked == true ? 1 : 0;
	
	if (trim(login) == '') { alert('Заполните поле "' + document.getElementById('login').previousSibling.innerHTML + '"'); return; }
	if (trim(password) == '') { alert('Заполните поле "' + document.getElementById('password').previousSibling.innerHTML + '"'); return; }
	
	var sBody = 'login=' + encodeURIComponent(login) + '&password=' + encodeURIComponent(password) + '&save=' + save;
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open('POST', action, true);
	oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4)
		{
			if (oXmlHttp.status == 200) 
			{ //alert(oXmlHttp.responseText);
				if (oXmlHttp.responseText == '')
				{
					if (myData == null)
						window.location = action + '?step3';
					else
						window.location.reload();
				}
				else // если ошибка
				{
					closePopup('popup-text');
					alert("Ошибка!\n\n" + oXmlHttp.responseText);
					document.getElementById('login').value = '';
					document.getElementById('password').value = '';
					document.getElementById('login').focus();
				}
			}
			else
				alert("Ошибка!\n\n" + oXmlHttp.statusText);
		}	
	}; oXmlHttp.send(sBody);
	showPopup('popup-text', 'Проверка введенных данных...');
}
//---------------------------------------------------------------------------------
// напоминание пароля
function rePass(action)
{
	var email = document.getElementById('remail').value;
	
	if (trim(email) == '') { alert('Заполните поле "' + document.getElementById('email').previousSibling.innerHTML + '"'); return; }
	
	var sBody = 'remail=' + encodeURIComponent(email);
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open('POST', action, true);
	oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4)
		{
			if (oXmlHttp.status == 200) 
			{ //alert(oXmlHttp.responseText);
				closePopup('popup-text');
				if (oXmlHttp.responseText == '')
				{
					alert('Пароль отправлен на указанный e-mail.');
				}
				else // если ошибка
				{
					closePopup('popup-text');
					alert("Ошибка!\n\n" + oXmlHttp.responseText);
					document.getElementById('remail').value = '';
					document.getElementById('remail').focus();
				}
			}
			else
				alert("Ошибка!\n\n" + oXmlHttp.statusText);
		}	
	}; oXmlHttp.send(sBody);
	showPopup('popup-text', 'Проверка введенных данных...');
}
//---------------------------------------------------------------------------------
// быстрая покупка или регистрация
function registrationAndBuying(action, myData)
{
	var fname = document.getElementById('fname').value;
	var lname = document.getElementById('lname').value;
	var email = document.getElementById('email').value;
	var act = document.getElementById('act').checked == true ? 1 : 2;
	var region = document.getElementById('region').value;
	
	if (trim(fname) == '') { alert('Заполните поле "' + document.getElementById('fname').previousSibling.innerHTML + '"'); return; }
	if (trim(lname) == '') { alert('Заполните поле "' + document.getElementById('lname').previousSibling.innerHTML + '"'); return; }
	if (region == 0) { alert('Выберите регион'); return; }
	if (trim(email) == '') { alert('Заполните поле "' + document.getElementById('email').previousSibling.innerHTML + '"'); return; }
	
	var sBody = 'fname=' + encodeURIComponent(fname) + '&lname=' + encodeURIComponent(lname) + '&region=' + encodeURIComponent(region) + '&email=' + encodeURIComponent(email);
	
	if (act == 2) // если регистрация
	{
		var pass1 = document.getElementById('pass1').value;
		var pass2 = document.getElementById('pass2').value;
		if (trim(pass1) == '') { alert('Заполните поле "' + document.getElementById('pass1').previousSibling.innerHTML + '"'); return; }
		if (trim(pass2) == '') { alert('Заполните поле "' + document.getElementById('pass2').previousSibling.innerHTML + '"'); return; }
		if (trim(pass1) != trim(pass2)) { alert('Введенные пароли не совпадают'); return; }
		sBody += '&pass=' + encodeURIComponent(pass1);
	}
	
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open('POST', action, true);
	oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4)
		{
			if (oXmlHttp.status == 200) 
			{ //alert(oXmlHttp.responseText);
				if (oXmlHttp.responseText == '')
				{
					if (myData == null)
						window.location = action + '?step3';
					else
						window.location.reload();
				}
				else // если ошибка
				{
					closePopup('popup-text');
					alert("Ошибка!\n\n" + oXmlHttp.responseText);
				}
			}
			else
				alert("Ошибка!\n\n" + oXmlHttp.statusText);
		}	
	}; oXmlHttp.send(sBody);
	showPopup('popup-text', 'Обработка введенных данных...');
}
//---------------------------------------------------------------------------------
// расчет цены с учетом доставки
function changeCost(add_cost)
{
	var cost = parseFloat(document.getElementById('cost').innerHTML);
	var all_cost = cost + parseFloat(add_cost);
	var all_cost_int = cost + parseInt(add_cost);
	var cop = (all_cost - all_cost_int) * 100;
	document.getElementById('all_cost').innerHTML = all_cost_int + ' р. ' + (cop ? (parseInt(cop) + ' коп.') : '');
	document.getElementById('and_text_delivery').innerHTML = '&nbsp;с учетом доставки';
}
//---------------------------------------------------------------------------------
// изменение полей при оформлении покупки
function changeField(code)
{
	document.getElementById(code + '1').className = 'hide';
	document.getElementById(code + '2').className = 'comments';
	document.getElementById(code + '3').className = 'hide';
	document.getElementById(code + '4').innerHTML = document.getElementById(code + '3').innerHTML;
	document.getElementById(code + '4').className = 'order_comments';
}
//---------------------------------------------------------------------------------
// оформление заказа
function completeOrder(action)
{
	var delivery = document.forms['delivery'].elements;
	for (var i = 0; i < delivery.length; i++)
	{
		if (delivery.item(i).checked == true)
		{
			var delivery_id = delivery.item(i).value;
			break;
		}
	}

	var cost = parseInt(document.getElementById('cost').innerHTML);
	var phone = document.getElementById('phone2').value;
	var post_index = document.getElementById('post_index2').value;
	var address = document.getElementById('address2').value;
	var comments = document.getElementById('comments').value;
	
	if (delivery_id == null) { alert('Выберите способ оплаты и доставки'); return; }
	if (trim(phone) == '') { alert('Введите телефон'); return; }
	if (trim(post_index) == '') { alert('Введите почтовый индекс'); return; }
	if (trim(address) == '') { alert('Введите адрес доставки'); return; }
	
	var sBody = 'delivery=' + parseInt(delivery_id) + '&phone=' + encodeURIComponent(phone) + '&post_index=' + encodeURIComponent(post_index) + '&address=' + encodeURIComponent(address) + '&cost=' + encodeURIComponent(cost);
	
	if (trim(comments) != '') sBody += '&comments=' + encodeURIComponent(comments);
	
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open('POST', action, true);
	oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4)
		{
			if (oXmlHttp.status == 200) 
			{ //alert(oXmlHttp.responseText);
				if (oXmlHttp.responseText == '')
				{
					window.location = action + '?step4';
				}
				else // если ошибка
				{
					closePopup('popup-text');
					alert("Ошибка!\n\n" + oXmlHttp.responseText);
					window.location = action + '?step1';
				}
			}
			else
				alert("Ошибка!\n\n" + oXmlHttp.statusText);
		}	
	}; oXmlHttp.send(sBody);
	showPopup('popup-text', 'Идет обработка покупки...');
}
//---------------------------------------------------------------------------------
// добавление комментария
function addComment(action)
{
	var name = document.getElementById('name').value;
	var where = document.getElementById('where').value;
	var comment = document.getElementById('comment').value;
	var code = document.getElementById('code').value;
	
	if (trim(name) == '') { alert('Заполните поле "' + document.getElementById('name').previousSibling.innerHTML + '"'); return; }
	//if (trim(where) == '') { alert('Заполните поле "' + document.getElementById('where').previousSibling.innerHTML + '"'); return; }
	if (trim(comment) == '') { alert('Заполните поле "' + document.getElementById('comment').previousSibling.innerHTML + '"'); return; }
	if (trim(code) == '') { alert('Введите код на картинке.'); return; }
	
	var sBody = 'name=' + encodeURIComponent(name) + '&where=' + encodeURIComponent(where) + '&comment=' + encodeURIComponent(comment) + '&code=' + encodeURIComponent(code);
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open('POST', action, true);
	oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4)
		{
			if (oXmlHttp.status == 200) 
			{ //alert(oXmlHttp.responseText);
				if (oXmlHttp.responseText.slice(0,4) == '<div')
				{
					var temp = document.getElementById('comments').innerHTML;
					document.getElementById('comments').innerHTML = oXmlHttp.responseText + temp;
					document.getElementById('name').value = '';
					document.getElementById('where').value = '';
					document.getElementById('comment').value = '';
					closePopup('popup-text');
					alert('Спасибо за ваш отзыв!');
				}
				else // если ошибка
				{
					closePopup('popup-text');
					alert("Ошибка!\n\n" + oXmlHttp.responseText);
				}
			}
			else
				alert("Ошибка!\n\n" + oXmlHttp.statusText);
		}	
	}; oXmlHttp.send(sBody);
	showPopup('popup-text', 'Идет добавление отзыва...');
}
//---------------------------------------------------------------------------------
// открытие всплывающего окна
function showPopup(id, text)
{
	block = document.getElementById(id);
	if (text != null) block.innerHTML = text;
	block.style.display = 'block';
	var pos = getElementPosition(id);
	
	if (pos.height < getClientWidth())
		block.style.left = getBodyScrollLeft() + (getClientWidth() - pos.width) / 2 + 'px';
	else
		block.style.left = getBodyScrollLeft() + 10 + 'px';
	
	if (pos.height < getClientHeight())
		block.style.top = getBodyScrollTop() + (getClientHeight() - pos.height) / 2 + 'px';
	else
		block.style.top = getBodyScrollTop() + 10 + 'px';
	
	var transp = document.getElementById('transparency') != null ? document.getElementById('transparency') : document.createElement('DIV');
	transp.id = 'transparency';
	transp.style.height = getDocumentHeight() + 'px';
	transp.style.display = 'block';
	document.body.appendChild(transp);
}
//---------------------------------------------------------------------------------
// закрытие всплывающего окна
function closePopup(id)
{
	if (document.getElementById(id) == null) return;
	document.getElementById(id).style.display = 'none';
	if (document.getElementById('transparency') != null)
	{
		document.getElementById('transparency').style.height = '0px';
		document.getElementById('transparency').style.display = 'none';
	}
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
function ltrim(txt)
{
  var spacers = " \t\r\n";
  while (txt.length>0 && spacers.indexOf(txt.charAt(0)) != -1)
  {
    txt = txt.substr(1);
  }
  return(txt);
}
function rtrim(txt)
{
  var spacers = " \t\r\n";
  while (txt.length>0 && spacers.indexOf(txt.charAt(txt.length-1)) != -1)
  {
    txt = txt.substr(0,txt.length-1);
  }
  return(txt);
}
function trim(txt)
{
  return(ltrim(rtrim(txt)));
}
function getDocumentWidth()
{
	return (document.body.scrollWidth > document.body.offsetWidth) ? document.body.scrollWidth : document.body.offsetWidth;
}
function getDocumentHeight()
{
	return (document.body.scrollHeight > document.body.offsetHeight) ? document.body.scrollHeight : document.body.offsetHeight;
}
function getClientWidth()
{
  return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientWidth : document.body.clientWidth;
}
function getClientHeight()
{
  return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientHeight : document.body.clientHeight;
}
function getBodyScrollLeft()
{
	return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);
}
function getBodyScrollTop()
{
	return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}
function getElementPosition(elemId)
{
    var elem = document.getElementById(elemId);
	
    var w = elem.offsetWidth;
    var h = elem.offsetHeight;
	
    var l = 0;
    var t = 0;
	
    while (elem)
    {
        l += elem.offsetLeft;
        t += elem.offsetTop;
        elem = elem.offsetParent;
    }

    return {"left":l, "top":t, "width": w, "height":h};
}
//---------------------------------------------------------------------------------
//кодирование данных формы для отсылки на сервер
function getRequestBody(form)
{
	var params = new Array();
	for (var i = 0; i < form.elements.length; i++)
	{
		var param = encodeURIComponent(form.elements[i].name);
		param += '=';
		if (form.elements[i].attributes != null && form.elements[i].getAttribute('type') == 'radio')
		{
			if (form.elements[i].checked) param += encodeURIComponent(form.elements[i].value); else continue;
		}
		else if (form.elements[i].attributes != null && form.elements[i].getAttribute('type') == 'checkbox')
		{
			if (form.elements[i].checked) param += '1'; else param += '0';
		}
		else
		{
			param += encodeURIComponent(form.elements[i].value);
		}
		params.push(param);
	}
	return params.join('&');
}
