function submitDiscount(id)
{
	document.discountForm.id.value = id;
	document.discountForm.discount.value = document.discountForm["discount"+id].value;
	document.discountForm.submit();
}


function toggle() {
	for (var i = 0; i < arguments.length; i++) {
		var obj = $(arguments[i]);
		obj.style.display = (obj.style.display == 'none' ? '' : 'none');
	}
}

function hide() {
	for (var i = 0; i < arguments.length; i++) {
		$(arguments[i]).style.display = 'none';
	}
}

function show() {
	for (var i = 0; i < arguments.length; i++) {
		$(arguments[i]).style.display = '';
	}
}

function ask(str, func) {
	if (confirm(str)) {
		if (typeof func == "string") {
			(Function(func))();
		} else if (typeof func == "function") {
			func();
		}
		return true;
	}
	return false;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return {x: curleft, y: curtop};
}

function mousePos(e) {
	var pos = {x: 0, y: 0};
	if (arguments.length > 1) {
		pos = findPos(arguments[1]);
	}
	if ($isdef(e.pageX)) {
		return { x: e.pageX - pos.x, y: e.pageY - pos.y };
	} else {
		if ($isdef(document.documentElement.scrollTop)) {
			return { x: e.clientX + document.documentElement.scrollLeft - pos.x, y: e.clientY + document.documentElement.scrollTop - pos.y };
		} else {
			return { x: e.clientX + document.body.scrollLeft - pos.x, y: e.clientY + document.body.scrollTop - pos.y };
		}
	}
}

function mouseIsOut(_e, obj) {
	var e = $event(_e);
	var x = e.toElement;
	while (x) {
		if (x == obj) {
			return false;
		}
		x = x.parentNode;
	}
	return true;
}

function addToCart(isbn, url, obj) {
	//alert(isbn+url);
	obj = $(obj);
	$ajax.request({
		"url": url+'/addtobasket/'+isbn,
		method: 'get',
		onSuccess: function (code, raw) {
			if (code == null) {
				alert("Server error: \n" + raw);
			} else {
				if (code.error) {
					alert("Ошибка " + code.errorType + ": " + code.errorText);
				} else {
					obj.innerHTML = "Уже в корзине";
					obj.changeTag("b", {className: "button addToCart"});
					alert("Товар добавлен в корзину");
					$('cart').innerHTML="<h5><a href=" + code.link + ">Ваша Корзина</a></h5>Количество товаров:  <b>" + code.count + "</b><br />Стоимость:  <b>" + code.cost +" р.</b>";
				}
			}
		}
	});
	return false;
}

function checkIndexLen(index, url) {
	if($('Step3Index').value.length<6)
	{
		$('Step3CityDiv').style.display = 'none';
		$('Step3AutonomDiv').style.display = 'none';
		$('Step3RegionDiv').style.display = 'none';
	}
}

function visibleFalse(index, url) {	
		$('Step3CityDiv').style.display = 'none';
		$('Step3AutonomDiv').style.display = 'none';
		$('Step3RegionDiv').style.display = 'none';
		$('next').disabled = true;
		$('deliveryIndexInfo').style.display='';
}

function checkIndexError(index, url) {
	$('IndexErrorDiv').style.display='none';
	$('IndexErrorDiv').innerHTML='';
	$('check').disabled = false;
}

function checkButtonClick(index, url) {
	if($('Step3Index').value.length<6)
	{
		$('Step3CityDiv').style.display = 'none';
		$('Step3AutonomDiv').style.display = 'none';
		$('Step3RegionDiv').style.display = 'none';
		$('IndexErrorDiv').style.display='';
		$('IndexErrorDiv').innerHTML='Индекс должен состоять из 6 цифр';
		$('check').disabled = true;
		$('deliveryIndexInfo').style.display='';
		
	}
	else
		checkIndex(index, url);
}

function checkIndex(index, url) {
	$('Step3City').readOnly = true;
	$('Step3Autonom').readOnly = true;
	$('Step3Region').readOnly = true;
	
	if($('Step3Index').value.length<6)
	{
		$('Step3CityDiv').style.display = 'none';
		$('Step3AutonomDiv').style.display = 'none';
		$('Step3RegionDiv').style.display = 'none';
		$('deliveryIndexInfo').style.display='';
	}
	else if($('Step3Index').value.length>6)
	{
		$('IndexErrorDiv').style.display='';
		$('IndexErrorDiv').innerHTML='Индекс некорректен';
		$('Step3CityDiv').style.display = 'none';
		$('Step3AutonomDiv').style.display = 'none';
		$('Step3RegionDiv').style.display = 'none';
		$('deliveryIndexInfo').style.display='';
	}
	else
	$ajax.request({
		"url": url+'/'+index,
		method: 'get',
		onSuccess: function (code, raw) {
			if (code == null) {
				alert("Server error: \n" + raw);
			} else {
				if ((code.wrong)&&($('Step3Index').value.length==6))
				{
					$('IndexErrorDiv').style.display='';
					$('IndexErrorDiv').innerHTML='Индекс некорректен';
					$('check').disabled = true;
					$('deliveryIndexInfo').style.display='';
				}
				if (code.denied)
				{
					$('IndexErrorDiv').style.display='';
					$('IndexErrorDiv').innerHTML='Невозможна доставка почты по данному индексу';
					$('check').disabled = true;
					$('deliveryIndexInfo').style.display='';
				}
				if (code.not_found)
				{
					$('IndexErrorDiv').style.display='';
					$('IndexErrorDiv').innerHTML='Индекс некорректен';
					$('check').disabled = true;
					$('deliveryIndexInfo').style.display='';
				}
				if (code.INDEX) {
					$('IndexErrorDiv').style.display='none';
					if(code.CITY!='')
					{
						$('Step3CityDiv').style.display = '';
						$('Step3City').value = code.CITY;
					}
					else
						$('Step3CityDiv').style.display = 'none';
						
					if(code.AUTONOM!='')
					{
						$('Step3AutonomDiv').style.display = '';
						$('Step3Autonom').value = code.AUTONOM;
					}
					else
						$('Step3AutonomDiv').style.display = 'none';
						
					if(code.REGION!='')
					{
						$('Step3RegionDiv').style.display = '';
						$('Step3Region').value = code.REGION;
					}
					else
						$('Step3RegionDiv').style.display = 'none';
					$('next').disabled = false;
					$('check').disabled = true;
					$('deliveryIndexInfo').style.display='none';
				}
				$('Step3Index').blur();
			}
		}
	});
	return false;
}

function addToFavorites(isbn, url, obj) {
	obj = $(obj);
	$ajax.request({
		"url": url,
		data: {
			action: "add_to_favorites",
			"isbn": isbn
		},
		onSuccess: function (code, raw) {
			if (code == null) {
				alert("Server error: \n" + raw);
			} else {
				if (code.error) {
					alert("Ошибка " + code.errorType + ": " + code.errorText);
				} else {
					obj.remove();
					alert("Книга добавлена в закладки");
				}
			}
		}
	});
	return false;
}

function deleteFromFavorites(isbn, url) {
	form = $('deleteFromFavoritesForm');
	form.isbn.value = isbn;
	form.submit();
	return false;
}

function clearFavorites(url) {
	$ajax.request({
		"url": url,
		data: {
			action: "clear_favorites"
		},
		onSuccess: function (code, raw) {
			if (code == null) {
				alert("Server error: \n" + raw);
			} else {
				if (code.error) {
					alert("Ошибка " + code.errorType + ": " + code.errorText);
				} else {
					alert("Закладки очищены");
				}
			}
		}
	});
	return false;
}

function ajaxUrl() { return '/l' + window.location.pathname; }

function $post(url, obj) {
	if (typeof url == "object") {
		obj = url;
		url = window.location.pathname;
	}
	var innForm = '';
	for (var i in obj) {
		innForm += '<input type="hidden" name="' + i + '" value="' + obj[i] + '" />';
	}
	var postForm = $c('form', { method: "post", action: url}, innForm);
	postForm.style.display = 'none';
	document.body.appendChild(postForm);
	postForm.submit();
	return false;
}



function hash(a) {
	if (typeof a == "string")
		return '\"' + a.replace(/\\/g, '\\\\').replace(/\"/g, '\\"') + '"';
	if (typeof a == "number")
		return a;
	if (typeof a == "boolean")
		return a;
	if (typeof a == "object") {
		var res = 'obj';
		for (var i in a) {
			res += i + ' = ' + a[i] + '<br />'
		}
		return res;
	}
	return 'false';
}


function formCheck() {
	if (arguments.length < 2)
		return true;
	var form = arguments[0];
	var inputs = arguments[1];
	var alrt = arguments.length > 2 ? arguments[2] : false;
	for (var i in inputs) {
		var a = inputs[i];
		var v = form[i].value;
		var err = a.text ? a.text : "Ошибка";
		var len_err = a.len_text ? a.len_text : err;
		var line_err = a.line_text ? a.line_text : err;
		if (a.maxlen) {
			if (v.length > a.maxlen) {
				return formChechError(a.maxlen_text ? a.maxlen_text : len_err, a.hint, alrt);
			}
		}
		if (a.minlen) {
			if (v.length < a.minlen) {
				return formChechError(a.minlen_text ? a.minlen_text : len_err, a.hint, alrt);
			}
		}
		if (a.maxline) {
			if (v.split("\n").length > a.maxline) {
				return formChechError(a.maxline_text ? a.maxline_text : line_err, a.hint, alrt);
			}
		}
		if (a.minline) {
			if (v.split("\n").length < a.minline) {
				return formChechError(a.minline_text ? a.minline_text : line_err, a.hint, alrt);
			}
		}
		if (a.chars) {
			for (var j = 0; j < v.length; j++) {
				if (a.chars.indexOf(v.charAt(j)) == -1) {
					return formChechError(a.chars_text ? a.chars_text : err, a.hint, alrt);
				}
			}
		}
		if (a.check) {
			if (form[i].checked != a.check) {
				return formChechError(a.check_text ? a.check_text : err, a.hint, alrt);
			}
		}
		if (a.natural) {
			if (!v.isNatural()) {
				return formChechError(a.natural_text ? a.natural_text : err, a.hint, alrt);
			}
		}
		if (a.select) {
			if (form[i].selectedIndex == 0) {
				return formChechError(a.select_text ? a.select_text : err, a.hint, alrt);
			}
		}
	}
	return true;
}

function formChechError(text, hint, alrt) {
	if (!$isdef(text))
		return false;
	if ($isdef(hint)) {
		$(hint).innerHTML = text;
	}
	if ($isdef(alrt)) {
		if (alrt)
			alert(text);
	}
	return false;
}

function getRegion(parent, child, url) {
	parent = $(parent);
	child = $(child);
	var index = parent.value;
	if (length(index)<6) {
// 		child.clearOptions();
		return;
	}
	if (!$isdef(url)) url = "/l/regions/";
// 	if (!$isdef(dflt)) dflt = "";
	parent.disabled = true;
	$ajax.request({
		"url": url + index,
		method: "get",
		cache: true,
		onSuccess: function (data, raw) {
			if (data == null) {
				alert("Server error: " + raw);
			} else {
// 				child.clearOptions();
// 				child.appendOption(dflt, "");
// 				for (var i in data) {
// 					child.appendOption(data[i].real_name, i);
// 		  		}
				child.value=data.city;
			}
			parent.disabled = false;
			}
	});
}

$extend($Element.Methods, {
	changeTag: function(tag) {
		var prop = {};
		if (arguments.length > 1)
			prop = arguments[1];
		var el = $c(tag, prop, this.innerHTML);
		this.insertPrev(el);
		this.remove();
		return el;
	},
	insertPrev: function(el) {
		$(this, "parent").insertBefore(el, this);
	}
});

function appearNull(obj)
{
	//if(obj.value=='0')
	obj.value=(!parseInt(obj.value))?(0):parseInt(obj.value);
}
function deleteNull(obj)
{
	if(obj.value=='0')
		obj.value='';
}

function copyText(from,into)
{
	into.value=from.value;
}