function clearOnFocus(obj) {
	obj.onfocus = Function.empty;
	obj.onblur = function () { setOnBlur(obj); };
	obj.defaultValue = obj.value;
	obj.value = '';
}

function setOnBlur(obj) {
	if (obj.value == '') {
		obj.value = obj.defaultValue;
		obj.onfocus = function () { clearOnFocus(obj); };
		obj.onblur = Function.empty;
	}
}

function addToCart(id, link) {
	L4F.AjaxQuick({
		data: {
			action: 'add_to_basket_ajax',
			id: id
		},
		onSuccess: function (code, raw) {
			$(link).insertSiblingNext($c('span', {className: 'button button-cart'}, 'Уже в <a href="/basket">корзине</a>'));
			link.removeElement();
			$("#cartInner").innerHTML = code.html;
		}
	});
	return false;
}

function giftAddToCart(id, link) {
	L4F.AjaxQuick({
		data: {
			action: 'gift_add_to_basket_ajax',
			id: id
		},
		onSuccess: function (code, raw) {
			$(link, '<div.buy').addClass('buyIn');
			$(link).insertSiblingNext($c('span', {className: 'button button-cart'}, '<a href="/gift/basket">В корзине</a>'));
			link.removeElement();
			$("#cartInner").innerHTML = code.html;
		}
	});
	return false;
}

function prikolyAddToCart(id, link) {
	L4F.AjaxQuick({
		data: {
			action: 'prikoly_add_to_basket_ajax',
			id: id
		},
		onSuccess: function (code, raw) {
			$(link).insertSiblingNext($c('span', {className: 'button button-cart'}, 'Уже в <a href="/prikoly/basket">корзине</a>'));
			link.removeElement();
			$("#cartInner").innerHTML = code.html;
		}
	});
	return false;
}

function addToFavorites(id, link) {
	L4F.AjaxQuick({
		data: {
			action: 'add_to_favorites',
			id: id
		},
		onSuccess: function (code, raw) {
			$(link).insertSiblingNext($c('a', {className: 'button', href: '#', onclick: "return L4F.post({action: 'delete_from_favorites', id: '" + id + "'})"}, 'Удалить из избранного'));
			$(link).insertSiblingNext($c('span', {className: 'button button-cart'}, 'В <a href="/shop/favorites">избранном</a>'));
			link.removeElement();
// 			$("#cartInner").innerHTML = code.html;
		}
	});
	return false;
}

function giftAddToFavorites(id, link) {
	L4F.AjaxQuick({
		data: {
			action: 'gift_add_to_favorites',
			id: id
		},
		onSuccess: function (code, raw) {
			$(link).insertSiblingNext($c('a', {className: 'button', href: '#', onclick: "return L4F.post({action: 'gift_delete_from_favorites', id: '" + id + "'})"}, 'Удалить из избранного'));
			$(link).insertSiblingNext($c('span', {className: 'button button-cart'}, 'В <a href="/gift/shop/favorites">избранном</a>'));
			link.removeElement();
// 			$("#cartInner").innerHTML = code.html;
		}
	});
	return false;
}

function prikolyAddToFavorites(id, link) {
	L4F.AjaxQuick({
		data: {
			action: 'prikoly_add_to_favorites',
			id: id
		},
		onSuccess: function (code, raw) {
			$(link).insertSiblingNext($c('a', {className: 'button', href: '#', onclick: "return L4F.post({action: 'prikoly_delete_from_favorites', id: '" + id + "'})"}, 'Удалить из избранного'));
			$(link).insertSiblingNext($c('span', {className: 'button button-cart'}, 'В <a href="/prikoly/shop/favorites">избранном</a>'));
			link.removeElement();
// 			$("#cartInner").innerHTML = code.html;
		}
	});
	return false;
}

function delFromCart(id) {
	alert('prepare to delete ' + id);
	L4F.AjaxQuick({
		data: {
			action: 'delete_basket_goods_ajax',
			id: id
		},
		onSuccess: function (code, raw) {
			alert('deleted');
			$("#cart").innerHTML = code.html;
		}
	});
	return false;
}


function checkIndexLen(index, url) {
	if($('#Step3FormIndex').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;
}

function checkIndexError(index, url) {
	$('#IndexErrorDiv').style.display='none';
	$('#IndexErrorDiv').innerHTML='';
	$('#check').disabled = false;
}

function checkButtonClick(index, url) {
	if($('#Step3FormIndex').value.length<6)
	{
		$('#Step3CityDiv').style.display = 'none';
		$('#Step3AutonomDiv').style.display = 'none';
		$('#Step3RegionDiv').style.display = 'none';
		$('#IndexErrorDiv').style.display='';
		$('#IndexErrorDiv').innerHTML='Индекс должен состоять из 6 цифр';
		$('#check').disabled = true;
		
	}
	else
		checkIndex(index, url);
}


var indexEngine = {
	current: '',
	url: '/check_index',
	check: function () {
		$('#Step3Index').value = $('#Step3Index').value.toString().trim();
		$('#check').disabled = true;
		if ( !/^\d{6}$/.test($('#Step3Index').value) ) {
			this.error('Индекс должен состоять из 6 цифр')
		} else {
			L4F.AjaxQuick({
				url: this.url + '/' + $('#Step3Index').value,
				method: 'get',
				onSuccess: function (code, raw) {
					if (!code) {
						indexEngine.error('Произошла внутренняя ошибка ' + raw);
					} else if (code.wrong || code.not_found) {
						indexEngine.error('Индекс некорректен');
					} else if (code.denied) {
						indexEngine.error('Невозможна доставка почты по данному индексу');
					} else {
					
						indexEngine.error('');
						
						if(code.CITY != '') {
							$('#Step3CityDiv').show();
							$('#Step3City').value = code.CITY;
						} else {
							$('#Step3CityDiv').hide()
						}
						
						if(code.AUTONOM != '') {
							$('#Step3AutonomDiv').show();
							$('#Step3Autonom').value = code.AUTONOM;
						} else {
							$('#Step3AutonomDiv').hide()
						}
							
						if(code.REGION != '') {
							$('#Step3RegionDiv').show();
							$('#Step3Region').value = code.REGION;
						} else {
							$('#Step3RegionDiv').hide()
						}
						
						$('#next').disabled = false;
						
					}
				}
			});
		}
	},
	change: function () {
		if ($('#Step3Index').value != this.current) {
			$('#next').disabled = true;
			$('#check').disabled = false;
			this.hideResult();
			this.error('');
			this.current = $('#Step3Index').value;
		}
	},
	init: function (url) {
		this.current = $('#Step3Index').value;
		this.url = url;
		$('#next').disabled = true;
		$('#Step3City').readonly = true;
		$('#Step3Autonom').readonly = true;
		$('#Step3Region').readonly = true;
		this.hideResult();
		this.check();
		this.error('');
	},
	error: function (entry) {
		if (entry == '') {
			$('#IndexErrorDiv').hide();
		} else {
			this.hideResult();
			$('#IndexErrorDiv').show();
			$('#IndexErrorDiv').innerHTML = 'Индекс некорректен';
		}
	},
	hideResult: function () {
		$('#Step3CityDiv').hide();
		$('#Step3AutonomDiv').hide();
		$('#Step3RegionDiv').hide();
	}
}

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;
	L4F.AjaxQuick({
		url: url + index,
		method: "get",
		cache: true,
		onSuccess: function (data, raw) {
			child.value = data.city;
			parent.disabled = false;
		}
	});
}

window._openImage_trigger = false;

function openImage (link, text) {
	if (window._openImage_trigger) {
		return false;
	}
	
	window._openImage_trigger = true;
	
	var winSize = getWindowSize();
	var cover = $c("div", { style: {
		position: "absolute",
		top: 0,
		left: 0,
		width: winSize.clientWidth + "px",
		height: Math.max(winSize.clientHeight, winSize.height) + "px",
		background: "#000000",
		zIndex: 500
	} });
	
	cover.setOpacity(0);
	
	var container = $c("div", { style: {
		position: "absolute",
		left: 0,
		width: "100%",
		textAlign: "center",
		top: (winSize.scrollTop + 20) + "px",
		zIndex: 501
	} });

	var img;
	
	function imgOnLoad() {
		img.onload = Function.empty;

		container.appendChild(img);
		container.setOpacity(0);
		
		document.body.appendChild(cover);
		document.body.appendChild(container);
		
		container.style.top = ((winSize.scrollTop) + winSize.height / 2 - container.clientHeight / 2) + "px";
				
		[
			(function (t) {
				cover.setOpacity(t * 0.3);
				container.setOpacity(t);
			}).toEffect(500),
			function () {
				container.onclick = cover.onclick = imgClose;
			}
		].toChain().start()
	}
	
	function imgClose() {
		container.onclick = cover.onclick = Function.empty;
		[
			(function (t) {
				cover.setOpacity((1 - t) * 0.3);
				container.setOpacity(1 - t);
			}).toEffect(500),
			function () {
				document.body.removeChild(container);
				document.body.removeChild(cover);
				window._openImage_trigger = false;
			}
		].toChain().start()
	}
	
	img = $c("img", {
		src: link.href,
		title: "Нажмите, чтобы закрыть изображение",
		style: {
			cursor: "pointer",
			padding: "10px",
			background: "#ffffff"
		},
		onload: imgOnLoad
	});

	if (img.complete) {
		img.onload();
	}
	
	return false;
}