var keyEvent = $browser.ie || $browser.webkit ? "onKeyDown" : "onKeyPress";
var DEBUG = true;

function $post(url, obj) {
	if (typeof url == "object") {
		obj = url;
		url = window.location.pathname;
	}
	PostQuick({ url: url, data: obj})
	return false;
}

var $ajaxClass =  Class(Ajax, {
	init: function (_config) {
		_config = _config || {};
		_config.url = _config.url || '/l';
		Ajax.prototype.init.call(this, _config);
		this.createEvent(["onGoodError"])
		this.onSuccess = function(data) {
			var code = data.parseJSON();
			if (!code) {
				this.onError("PARSE: " + data);
				return;
			}
			if (code.error) {
				if (code.errorType == "good") {
					if (!this.config.silent) {
						UI.alert(code.errorText);
					}
					this.onGoodError(code.errorText);
				} else {
					this.onError("SERVER: (" + code.errorType + ") " + code.errorText);
				}
				return;
			}
			this.fireEvent("onSuccess", [code, data]);
		}
		this.onError = function(err) {
			var data = "";
			if (typeof this.config.data == "object") {
				for (var i in this.config.data) {
					data += i + " -> " + this.config.data[i] + "\n";
				}
			} else {
				data = "{NULL}";
			}
			if (DEBUG) {
				UI.alert(err + "\nFROM: " + (this.config.from || "AJAX") + "\nDATA:" + data);
			}
			this.fireEvent("onError", [err]);
		};
	}
});

function $ajax(_conf) {
	var res = new $ajaxClass(_conf);
	res.send();
	return res;
}

function addToCart(id, link) {
	$ajax({
		data: {
			action: 'add_to_basket_ajax',
			id: id
		},
		onSuccess: function (code, raw) {
			$(link).insertSiblingNext($c('span', {className: 'button'}, 'Уже в <a href="/basket">корзине</a>'));
			link.removeElement();
			$("#cartInner").innerHTML = code.html;
		}
	});
	return false;
}

function delFromCart(id) {
	alert('prepare to delete ' + id);
	$ajax({
		data: {
			action: 'delete_basket_goods_ajax',
			id: id
		},
		onSuccess: function (code, raw) {
			alert('deleted');
			$("#cart").innerHTML = code.html;
		}
	});
	return false;
}

function changeWindowState(obj) {
	$(obj).toggleClass('window-closed');
	return false;
}

function checkIndexLen(index, url) {
	if($('#Step3Index').value.length<6)
	{
		$('#Step3CityDiv').hide();
		$('#Step3AutonomDiv').hide();
		$('#Step3RegionDiv').hide();
	}
}

function visibleFalse(index, url) {	
		$('#Step3CityDiv').hide();
		$('#Step3AutonomDiv').hide();
		$('#Step3RegionDiv').hide();
		$('#next').disabled = true;
}

function checkIndexError(index, url) {
	$('#IndexErrorDiv').hide();
	$('#IndexErrorDiv').innerHTML='';
	$('#check').disabled = false;
}

function checkButtonClick(index, url) {
	if($('#Step3Index').value.length<6)
	{
		$('#Step3CityDiv').hide();
		$('#Step3AutonomDiv').hide();
		$('#Step3RegionDiv').hide();
		$('#IndexErrorDiv').show();
		$('#IndexErrorDiv').innerHTML='Индекс должен состоять из 6 цифр';
		$('#check').disabled = true;
		
	}
	else
		checkIndex(index, url);
}

function checkIndex(index, url) {
	$('#Step3City').readOnly = true;
	$('#Step3Autonom').readOnly = true;
	$('#Step3Region').readOnly = true;
	
	if($('#Step3Index').value.length<6)
	{
		$('#Step3CityDiv').hide();
		$('#Step3AutonomDiv').hide();
		$('#Step3RegionDiv').hide();
	}
	else if($('#Step3Index').value.length>6)
	{
		$('#IndexErrorDiv').show();
		$('#IndexErrorDiv').innerHTML='Индекс некорректен';
		$('#Step3CityDiv').hide();
		$('#Step3AutonomDiv').hide();
		$('#Step3RegionDiv').hide();
	}
	else
	$ajax({
		url: url+'/'+index,
		method: 'get',
		onSuccess: function (code, raw) {
			if ((code.wrong)&&($('#Step3Index').value.length==6))
			{
				$('#IndexErrorDiv').show();
				$('#IndexErrorDiv').innerHTML='Индекс некорректен';
				$('#check').disabled = true;
			}
			if (code.denied)
			{
				$('#IndexErrorDiv').show();
				$('#IndexErrorDiv').innerHTML='Невозможна доставка почты по данному индексу';
				$('#check').disabled = true;
			}
			if (code.not_found)
			{
				$('#IndexErrorDiv').show();
				$('#IndexErrorDiv').innerHTML='Индекс некорректен';
				$('#check').disabled = true;
			}
			if (code.INDEX) {
				$('#IndexErrorDiv').hide();
				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;
				$('#check').disabled = true;
				$('#Step3Index').blur();
			}
		}
	});
	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({
		url: url + index,
		method: "get",
		cache: true,
		onSuccess: function (data, raw) {
			child.value = data.city;
			parent.disabled = false;
		}
	});
}

function ask(str, func) {
	if (confirm(str)) {
		if (typeof func == "string") {
			(Function(func))();
		} else if (typeof func == "function") {
			func();
		}
		return true;
	}
	return false;
}

var UI = {
	alert: function (a) { alert(a); return false; },
	ask: ask
};

function addToFavorites(id, link) {
	$ajax({
		data: {
			action: 'add_to_favorites',
			id: id
		},
		onSuccess: function (code) {
			$(link).insertSiblingNext($c('span', {className: 'button'}, 'В <a href="/shop/favorites">избранном</a>'));
			link.removeElement();
		}
	});
	return false;
}

var post = {
	vote: function (id, obj) {
		$ajax({
			data: {
			}
		});
	},
	fav: function (id, type, add, obj) {
		$ajax({
			data: {
			}
		});
	},
	sled: function (id, type, add, obj) {
		$ajax({
			data: {
			}
		});
	}
};

var comment = {
	currentReply: -1,
	currentAuthor: '',
	reply: function (parent) {
		var form = $("#replyComment"),
			comment = $('#message' + parent);
		if (this.currentReply != parent) {
			this.currentReply = parent;
			var text = $("#replyCommentText").value;
			if (text.substr(0, this.currentAuthor.length + 1) == (this.currentAuthor + ",")) {
				$("#replyCommentText").value = text.substr(this.currentAuthor.length + 1).trim();
				this.currentAuthor = '';
			}
			var author = this.currentAuthor = $('#message' + parent + ' a.user').innerHTML;
			$("#replyCommentParent").value = parent;
			$("#replyCommentText").value = author + ', ' + $("#replyCommentText").value
			form.removeElement();
			form.className = 'lvl' + (parseInt(comment.className.match(/lvl(\d+)/)[1]) + 1);
			comment.insertSiblingNext(form);
		} else {
			this.currentReply = -1;
			$("#replyCommentParent").value = '';
			var text = $("#replyCommentText").value;
			if (text.substr(0, this.currentAuthor.length + 1) == (this.currentAuthor + ",")) {
				$("#replyCommentText").value = text.substr(this.currentAuthor.length + 1).trim();
				this.currentAuthor = '';
			}
			form.removeElement();
			form.className = '';
			$("#replyCommentContainer").appendChild(form);
		}
		return false;
	}
};

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;
	}
}

var blogpost = {
	mark: function (id, act, obj, add, link) {
		$ajax({
			data: { action: act, post_id: id, type: add ? 1 : -1, obj: obj },
			onSuccess: function () {
				link.onclick = function () { return blogpost.mark(id, act, obj, !add, link); };
				$(link)[add ? 'addClass': 'removeClass']('active');
			}
		});
		return false;
	},
	vote: function (id, link) {
		$ajax({
			data: { action: 'rating', how: 1, type: 0, post_id: id},
			onSuccess: function () {
				link.onclick = function () { return false; }
				var obj = $("#postVotes")
				var v = eval(obj.innerHTML + '+1');
				$(link).addClass('active');
				obj.parentNode.innerHTML = '<strong>' + v + '</strong> голос' + padeg(v, '', 'а', 'ов');
			}
		});
		return false;
	}
};

function padeg(n, s1, s2, s5) {
	if (n == 0)
		return s5;
	if (n == 1)
		return s1;
	if (n < 5)
		return s2;
	if (n < 20)
		return s5;
	if (n < 100)
		return get_padeg(n % 10, s1, s2, s5);
	return get_padeg(n % 100, s1, s2, s5);	
}

var PM = {
	checkAll: function (checked) {
		$$("input.mail").each( function (obj) { obj.checked = checked; } );
	},
	check: function () {
		var checked = true;
		$$("input.mail").each( function (obj) { checked = obj.checked && checked; } );
		$("#mailAll").checked = checked;
	},
	reply: function (id, obj) {
		obj = $(obj, "<div.message");
		var subj = $(obj, "h3 a").innerHTML, form = $("#sendMail");
		form.removeElement();
		var re = subj.match(/(Re(\((\d+)\))?:)?(.*)/);
		subj = re[1] ? (re[3] ? "Re(" + (parseInt(re[3]) + 1) + "):" + re[4] : "Re(2):" + re[4]) : "Re: " + subj;
		obj.insertSiblingNext(form)
		form.show();
		$("#sendMailSubject").value = subj;
		return false;
	},
	again: function (id, obj) {
		this.reply(id, obj);
		$("#sendMailSubject").value = $(obj, "<div.message h3 a").innerHTML
		return false;
	},
	del: function (id, obj) {
		UI.ask('Удалить сообщение?', function () { $ajax({
			data: { action: 'pm_delete_act', delete_pm_id: id },
			onSuccess: function(data) { $(obj, "<div.message").removeElement(); }
		}); });
		return false;
	},
	toFriend: function (obj) {
		$("#sendMailRecepient").value = obj.options[obj.selectedIndex].value;
	},
	delFromList: function (id) {
		$post({ action: 'pm_delete_act', delete_pm_id: id });
		return false;
	},
	replyFromList: function (id) {
		var message = $('#message' + id);
		this.reply(id, $(message, '>'));
	},
	againFromList: function (id) {
		var message = $('#message' + id);
		this.again(id, $(message, '>'));
	}
}



function toggleInlineForm(id) {
	var form = $('#o_' + id);
	form.toggle();
	var foc = false;
	var inps = $$(form, "input");
	for (var i = 0; i < inps.length; i++) {
		if ((inps[i].type != 'hidden') && (inps[i].type != 'button')) {
			inps[i].select();
			inps[i].focus();
			foc = true;
			break;
		}
	}
	$('#link_' + id).toggle();
	var value = $('#value_' + id);
	if (value) {
		value.toggle();
	}
	return false;
}

function updateField(form, id) {
	var a = ajaxByForm(form);
	a.addEventListener({
		onSuccess: function(data) {
			$('#o_' + id).toggle();
			$('#link_' + id).toggle();
			var value = $('#value_' + id);
			if (value) {
				value.innerHTML = data.value;
				value.toggle();
			}
			var container = $('#container_' + id);
			if (container) {
				if (data.value == '') {
					container.addClass('editEmpty');
				} else {
					container.removeClass('editEmpty');
				}
			}
		}
	});
	a.send();
	return false;
}

function toggleIntableForm(id) {
	$('#o_' + id).toggle();
	$('#link_' + id).toggle();
	var i = 0, val, vali, form = $('#form_' + id);
	while (val = $('#value_' + id + '_' + i)) {
		val.toggle();
		i++;
	}
	i = 0;
	while (vali = $('#input_' + id + '_' + i)) {
		if (vali.nodeName == 'SELECT') {
			for (var j = 0; j < vali.options.length; j++) {
				if (vali.options[j].value == form[vali.name].value) {
					vali.selectedIndex = j;
					break;
				}
			}
		} else {
			vali.value = form[vali.name].value;
		}
		vali.toggle();
		i++;
	}
	return false;
}

function updateTableField(form, id) {
	var i = 0, vali;
	while (vali = $('#input_' + id + '_' + i)) {
		if (vali.nodeName == 'SELECT') {
			form[vali.name].value = vali.options[vali.selectedIndex].value;
		} else {
			form[vali.name].value = vali.value;
		}
		vali.disabled = true;
		i++;
	}
	var a = ajaxByForm(form);
	function enabler() {
		var i = 0, vali;
		while (vali = $('#input_' + id + '_' + i)) {
			vali.disabled = false;
			i++;
		}
	}
	a.addEventListener({
		onSuccess: function(data) {
			$('#o_' + id).toggle();
			$('#link_' + id).toggle();
			var i = 0, val, vali;
			while (val = $('#value_' + id + '_' + i)) {
				val.innerHTML = data.value[i];
				val.toggle();
				i++;
			}
			i = 0;
			while (vali = $('#input_' + id + '_' + i)) {
				vali.toggle();
				i++;
			}
			enabler();
		},
		onError: enabler,
		onGoodError: enabler
	});
	a.send();
	return false;
}

function ajaxByForm(obj) {
	var data = {};
	var inputs = $$(obj, "input"), selects = $$(obj, "select"), tareas = $$(obj, "textarea");
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].name != "") {
			switch (inputs[i].type) {
				case "checkbox":
				case "radio":
					if (inputs[i].checked) {
						data[inputs[i].name] = inputs[i].value;
					}
					break;
				default:
					data[inputs[i].name] = inputs[i].value;
			}
		}
		inputs[i].state = inputs[i].disabled;
		inputs[i].disabled = true;
	}
	for (var i = 0; i < selects.length; i++) {
		if (selects[i].name != "") {
			data[selects[i].name] = selects[i].options[selects[i].selectedIndex].value;
		}
		selects[i].state = selects[i].disabled;
		selects[i].disabled = true;
	}
	for (var i = 0; i < tareas.length; i++) {
		if (tareas[i].name != "") {
			data[tareas[i].name] = tareas[i].value;
		}
		tareas[i].state = tareas[i].disabled;
		tareas[i].disabled = true;
	}
	function enableForm() {
		for (var i = 0; i < inputs.length; i++) {
			inputs[i].disabled = inputs[i].state;
		}
		for (var i = 0; i < selects.length; i++) {
			selects[i].disabled = selects[i].state;
		}
		for (var i = 0; i < tareas.length; i++) {
			tareas[i].disabled = tareas[i].state;
		}
	}
	return new $ajaxClass({
		data: data,
		onSuccess: enableForm,
		onGoodError: enableForm,
		onError: enableForm
	});
}

window.curTab = false;
function openTab(name) {
	if (curTab != name) {
		if (curTab) {
			$('#' + curTab + 'Tab').hide();
			$('#' + curTab + 'Btn').removeClass('selected');
		}
		curTab = name;
		$('#' + name + 'Tab').show();
		$('#' + name + 'Btn').addClass('selected')
	}
	return false;
}

var htc = {
	hover: function (element) {
		element.attachEvent("onmouseover", function () { htc.IEHoverOn.call(element); });
		element.attachEvent("onmouseout", function () { htc.IEHoverOff.call(element); });
		element.htcHover = {};
		return 1;
	},
	focus: function (element) {
		element.attachEvent("onfocus", function () { htc.IEFocusOn.call(element); });
		element.attachEvent("onblur", function () { htc.IEFocusOff.call(element); });
		element.htcFocus = {};
		return 1;
	},
	trgif: '/images/tr.gif',
	png: function (img) {
		img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + img.src + '", sizingMethod="crop")';
		img.src = htc.trgif;
		img.htcPNG = {}
		return 1;
	},
	IEHoverGetClass: function (element) {
		if (element.className == "") {
			return " hover";
		} else {
			return " " + element.className.split(/\s/g)[0] + "-hover hover";
		}
	},
	IEHoverOn: function () {
		if (this.IE_HOVER) {
			if (!this.IE_HOVER.hover) {
				this.className += this.IE_HOVER.className;
				this.IE_HOVER.hover = true;
			}
		} else {
			this.IE_HOVER = { className: htc.IEHoverGetClass(this), hover: true };
			this.className += this.IE_HOVER.className;
		}
	},
	IEHoverOff: function () {
		if (this.IE_HOVER) {
			if (this.IE_HOVER.hover) {
				var obj = window.event.toElement;
				while (obj) {
					if (obj == this) {
						return;
					}
					obj = obj.parentNode;
				}
				var pos = this.className.indexOf(this.IE_HOVER.className);
				this.className = this.className.substr(0, pos) + this.className.substr(pos + this.IE_HOVER.className.length);
				this.IE_HOVER.hover = false;
			}
		} else {
			this.IE_HOVER = { className: htc.IEHoverGetClass(this), hover: false };
		}
	},
	IEFocusGetClass: function(element) {
		if (element.className == "") {
			return " focus";
		} else {
			return " " + element.className.split(/\s/g)[0] + "-focus focus";
		}
	},
	IEFocusOn: function() {
		if (this.IE_FOCUS) {
			if (!this.IE_FOCUS.focus) {
				this.className += this.IE_FOCUS.className;
				this.IE_FOCUS.focus = true;
			}
		} else {
			this.IE_FOCUS = { className: htc.IEFocusGetClass(this), focus: true };
			this.className += this.IE_FOCUS.className;
		}
	},
	IEFocusOff: function() {
		if (this.IE_FOCUS) {
			if (this.IE_FOCUS.focus) {
				var pos = this.className.indexOf(this.IE_FOCUS.className);
				this.className = this.className.substr(0, pos) + this.className.substr(pos + this.IE_FOCUS.className.length);
				this.IE_FOCUS.focus = false;
			}
		} else {
			this.IE_FOCUS = { className: htc.IEFocusGetClass(this), focus: false };
		}
	}
}

function getWindowSize() {
	var res = {
		width: window.innerWidth,
		height: window.innerHeight,
		scrollTop: window.pageYOffset,
		scrollLeft: window.pageXOffset
	};
	if ($browser.ie) {
		res = {
			width: document.documentElement.clientWidth,
			height: document.documentElement.clientHeight,
			scrollTop: document.documentElement.scrollTop,
			scrollLeft: document.documentElement.scrollLeft
		};
	}
	res.clientWidth = document.body.clientWidth;
	res.clientHeight = document.body.clientHeight;
	res.scrollWidth = res.clientWidth - res.width;
	res.scrollHeight = res.clientHeight - res.height;
	return res;
}

var Pictures = {
	bigImage: {}
};

var Window = Class({
	init: function (title, id, img, config) {
		config = config || {};
		$extend(this, {
			id: id,
			img: img
		});
		$_eventListener(this);
		var _this = this;
		this.createEvents(["onInit", "onOpen", "onClose"]);
		var buttons = [];
		buttons.push($c("a", { href: "#", className: "button close", onclick: function () { _this.close(); return false; } }, "Закрыть"));
		this.element = $c("div", { className: "floatImage fixed", style: { zIndex: 1000, visibility: "hidden" } }, [
			$c("div", { className: "title" }, title),
			this.container = $c("div", { className: "preview" }),
			$c("div", { className: "buttons" }, buttons)
		]);
		this.opened = false;
		this.config = {};
		$extend(this.config, config);
		this.addEventListener(config);
		this.onInit();
	},
	open: function () {
		var _this = this;
		if (this.current[0] === false) {
			this.current[0] = this;

			var winSize = getWindowSize();
			
			if (!_this.covered[0]) {
				_this.cover.setOpacity(0.8);
				_this.cover.style.height = winSize.height + "px";
				$("body").appendChild(_this.cover);
				_this.covered[0] = true;
			}
			
			var onImageReady = function () {
			
				var img = Pictures.bigImage[_this.id];
				img.onload = Function.empty;
				
				_this.container.appendChild(img);
				
				$("body").appendChild(_this.element);

				var imgHeight = img.clientHeight, imgWidth = img.clientWidth;
				
				if (imgHeight + 70 > winSize.height) {
					img.height = winSize.height - 70;
					img.width = img.height * (imgWidth / imgHeight);
				}
				
				_this.element.applyStyle({
					top: (winSize.height - _this.element.clientHeight) / 2 + "px",
					left: (winSize.width - _this.element.clientWidth) / 2 + "px",
					visibility: "visible"
				});
				
				img.onclick = _this.cover.onclick = function () { _this.close(); };
				img.title = "нажмите Esc, чтобы закрыть изображение";
				var escEvent = $(document).addEvent(keyEvent, function (e) {
					if (e.key == "esc") { _this.close(); }
				});
				
				_this.addEvent("onClose", function () {
					$(document).removeEvent(escEvent);
				});
				
				
				_this.opened = true;
				_this.onOpen();
			};
			
			if (Pictures.bigImage[_this.id]) {
				onImageReady();
			} else {
				var img = Pictures.bigImage[_this.id] = $c("img", {
					src: _this.img,
					onload: onImageReady
				});
				if (img.complete) {
					onImageReady();
				}
			}

		} else {
		}
	},
	close: function () { if (this.opened) {
		var _this = this;
		this.opened = false;
		this.onClose();
		_this.current[0] = false;
		_this.element.removeElement();
		Pictures.bigImage[_this.id].title = '';
		Pictures.bigImage[_this.id].onclick = Function.empty;
		Pictures.bigImage[_this.id].removeElement();
		if (_this.covered[0]) {
			_this.cover.removeElement();
			_this.covered[0] = false;
		}

	} },
	current: [false],
	covered: [false],
	cover: $c("div", { className: "fixed", style: { top: 0, left: 0, width: "100%", height: "100%", background: "#fff", zIndex: 999 } })
})

function openBigImage(title, id, img) {
	(new Window(title, id, img)).open();
	return false;
}

function changeLinkName(id) {
	$("#question_href"+id).innerHTML = $("#question_href"+id).innerHTML == "свернуть" ? 'читать далее' : 'свернуть';
}

var tag = {
	toggle: function (tag, id) {
		var tags_selected = $('#' + id).value.toString().trim()
		if (tags_selected != '') {
			tags_selected = tags_selected.split(/\s*,\s*/);
		} else {
			tags_selected = [];
		}
		if (tags_selected.has($(tag, 'span').innerHTML)) {
			tags_selected.remove($(tag, 'span').innerHTML);
			$(tag).removeClass('selected')
		} else {
			tags_selected.push($(tag, 'span').innerHTML);
			$(tag).addClass('selected')
		}
		$('#' + id).value = tags_selected.join(', ');
		return false;
	},
	toggleList: function (id) {
		var list = $('#' + id + '_tags');
		list.toggle();
		var tags_selected = $('#' + id).value.toString().trim().split(/\s*,\s*/);
		var tags = $$(list, 'div.list a');
		tags.each( function (tag) {
			if (tags_selected.has($(tag, 'span').innerHTML)) {
				tag.addClass('selected');
			} else {
				tag.removeClass('selected');
			};
		} );
	}
}