function ensureInt(event) {
	if (event.ctrlKey || event.altKey) {
		return true;
	}

	var key = (typeof event.charCode == 'undefined' ? event.keyCode : event.charCode);
	if (key < 32) {
		return true;
	}

	return /\d/.test(String.fromCharCode(key));
}

function getIdByForm(form) {
	var action = form.action;
	return action.substring(action.lastIndexOf("/") + 1);
}

function setTimepicker(html_id) {
	$("#" + html_id).datepicker({
		autoSize: true,
		dateFormat: "yy-mm-dd",

		constrainInput: false,
		duration: "",

		timeFormat: " hh:ii",
		showTime: true,
		stepMinutes: 1,
		stepHours: 1,
		altTimeField: "",
		time24h: true
	});
}

var errors_count = new Array();
function initializeErrorCount(product_id, amount_id) {
	if (typeof errors_count[product_id] == 'undefined') {
		errors_count[product_id] = new Array();
	}
	return $.inArray(amount_id, errors_count[product_id]);
}
function toggleErrorText(product_id) {
	var error_container = $("#error-"+product_id);
	if (errors_count[product_id].length > 0) {
		error_container.show("fast");
	} else {
		error_container.hide("fast");
	}
}
function incErrorCount(product_id, amount_id) {
	var idx = initializeErrorCount(product_id, amount_id);
	if (idx < 0) {
		errors_count[product_id].push(amount_id);
	}
	toggleErrorText(product_id, amount_id);
}
function decErrorCount(product_id, amount_id) {
	var idx = initializeErrorCount(product_id, amount_id);
	if (idx >= 0) {
		errors_count[product_id].splice(idx, 1);
	}
	toggleErrorText(product_id, amount_id);
}
function checkMultiplicity(input, amount_id, divider) {
	var value = parseInt(input.value);
	var rest = value % divider;
	var product_id = getIdByForm(input.form);
	input = $(input);
	if (rest > 0) {
		input.addClass("error");
		input.attr("title", "После обновления формы количество станет равным " + (value + divider - rest));
		incErrorCount(product_id, amount_id);
	} else {
		input.removeClass("error");
		input.removeAttr("title");
		decErrorCount(product_id, amount_id);
	}

	return true;
}

function showAjaxText(div_id, text, p_class) {
	var container = $("<p style=\"display:none;\"></p>").text(text);
	if (p_class.length > 0) {
		container.addClass(p_class);
	}
	container = $("#" + div_id).wrapInner(container);

	container = container.children();
	container.fadeIn("slow");
	if (container.offset()["top"] < jQuery(window).scrollTop()) {
		$.scrollTo(container, {axis: "y", duration: "fast"});
	}
}

function clickNewsLink(link) {
	var url = link.href + '/json';
	$.ajax({
		url: url,
		cache: false,
		dataType: "json",
		type: "POST",
		beforeSend: function() {
			showAjaxText("products", "Подгрузка данных...", "loading");
			$("#pager").text("");
		},
		error: function() {
			showAjaxText("products", "Подгрузка данных завершилась неудачей. Пожалуйста, повторите попытку.", "");
		},
		success: function(data) {
			var products = "";

			if (data.products != null) {
				products += data.products;
			}

			if (data.pager != null) {
				$("#pager").html(data.pager);
			}

			$("#products").html(products);
		}
	});

	return false;
}

function disableTree() {
	$("#items-0 a").addClass("noajax").removeClass("active").removeClass("current");
	$("#items-0 > li.active").removeClass("active");
}

function enableTree() {
	$("#items-0 a").removeClass("noajax");
}

function loadCatalogData(url) {
	$.ajax({
		url: url,
		cache: false,
		dataType: "json",
		type: "POST",
		beforeSend: function() {
			disableTree();
			showAjaxText("right", "Подгрузка данных...", "loading");
			$("#pager").text("");
		},
		error: function() {
			showAjaxText("right", "Подгрузка данных завершилась неудачей. Пожалуйста, повторите попытку.", "");
			enableTree();
		},
		success: function(data) {
			if (data.is_catalog_disabled != null) {
				$("#right").html(data.disabled_text);
			}

			enableTree();

			if (data.page_title != null) {
				document.title = data.page_title;
			}

			if (data.header != null) {
				$("#header-bg-right")[0].className = data.header;

				var href = "/files/blank_" + data.header + ".xls";

				var elem = $("#blank_xls");
				if (elem.length > 0) {
					elem.attr("href", href);
				}

				elem = $("#blank_zip");
				if (elem.length > 0) {
					elem.attr("href", href + ".zip");
				}
			}

			if (data.is_catalog_disabled == null) {
				var right = '';
				if (data.crumb != null) {
					right = right + data.crumb;
				}
				if (data.brends != null) {
					right = right + data.brends;
				} else if (data.products != null) {
					right = right + data.products;
				}

				if (data.pager) {
					right = right + '<div class="pager_place"></div>';
					$("#pager").html(data.pager);
				} else {
					$("#pager").html("");
				}

				$("#right").html(right);
			}

			if (data.tree_id != null) {
				var link = $("#item-"+data.tree_id);

				var ul = $("#items-"+data.tree_id);
				if (ul.length > 0 && data.tree != null) {
					ul.html(data.tree);
				} else if (ul.length > 0) {
					ul.remove();
				} else if (data.tree != null) {
					ul = $("<ul/>").attr("id", "items-"+data.tree_id).html(data.tree);
					link.after(ul);
				}

				if (link.length > 0) {
					var li = null;
					do {
						if (link.get(0).tagName != 'A') {
							link = link.prev();
						}
						link.addClass("active");
						li = link.parent();
						link = li.parent();
					} while (link.attr("id") != "items-0");
					li.addClass("active");
				}
			}
		}
	});
	return;
}

function clickCatalogLink(link) {
	if (link.className == 'noajax') {
		return false;
	}
	var href = link.href;
	var url = href.substring(0, href.lastIndexOf(".")) + '.json';

	loadCatalogData(url);
	return false;
}

function clickProductPage(link, page) {
	var href = link.href;
	var url = href.substring(0, href.lastIndexOf("."));
	if (page != 1) {
		url += '/page' + page;
	}
	url += '.json';

	loadCatalogData(url);
	return false;
}

function openPopup(href, slug) {
	if (!window.popups) {
		window.popups=[];
	}

	var window_popup = window.popups[slug];
	if (window_popup && !window_popup.closed) {
		window_popup.focus();
	} else {
		window_popup = window.open(href, slug, "width=630,height=530,left=20,top=20,toolbar=0,location=0,directories=0,menubar=0,scrollbars=1,resizable=0,status=0,fullscreen=0");
		window_popup.focus();
		window.popups[slug] = window_popup;
	}

	return false;
}

function clickProductLink(link) {
	var slug = link.href;
	slug = slug.substring(slug.lastIndexOf("/")+1, slug.lastIndexOf("."));

	// о великий и могучий ИЕ, ты убожество!
	slug = slug.replace(/-/g,"_");

	openPopup(link.href, slug);

	return false;
}

function loadProductPriceData(id, send_data) {
	var url = "/price/shopping-cart/edit1/" + id;
	if (send_data == null) {
		var s_type = "GET";
	} else {
		var s_type = "POST";
	}
	$.ajax({
		url: url,
		cache: false,
		dataType: "json",
		data: send_data,
		type: s_type,
		success: function(data) {
			if (data.product_id != null) {
				var id = data.product_id;
				var elem = null;

				if (data.price != null) {
					elem = $("#price-" + id);
					if (elem.length > 0) {
						elem.text(data.price);
					}
				}

				if (data.amount != null) {
					elem = $("#amount-" + id);
					if (elem.length > 0) {
						elem.text(data.amount);
					}
				}

				if (data.order_str != null) {
					elem = $("#order-str-" + id);
					if (elem.length > 0) {
						elem.text(data.order_str);
					}
				}

				if (data.cart_count != null) {
					elem = $("#cart_count");
					if (elem.length > 0) {
						elem.html(data.cart_count);
					}
				}

				if (data.order != null) {
					$("#order-" + id).html(data.order);
				}

			}

			if (data.is_item_disabled != null) {
				location.reload(true);
			}
		},
		error: function(data) { }
	});
}

function clickProductPriceLink(link) {
	var id = link.firstChild.id;
	id = id.substring(id.lastIndexOf("-") + 1);

	var href = $("#price-" + id).parent();
	var order = $("#order-" + id);
	if (order.length == 0) {
		order = $("<div/>").attr("id", "order-"+id).addClass("product_price").css("display", "none").html("Подгрузка данных...");
		href.after(order);
		loadProductPriceData(id, null);
	}
	order.slideToggle("fast");
	href.toggleClass("open");

	return false;
}

function submitProductPriceForm(form) {
	var id = getIdByForm(form);

	var elem = $("#price-" + id);
	if (elem.length > 0) {
		elem.text("");
	}
	elem = $("#amount-" + id);
	if (elem.length > 0) {
		elem.text("");
	}
	elem = $("#order-str-" + id);
	if (elem.length > 0) {
		elem.text("");
	}

	loadProductPriceData(id, $("#shopping-cart-product-" + id).serialize());

	form.parentNode.innerHTML = "Обновление данных...";

	return false;
}

function resetProductPriceForm(form) {
	// обнулим все тектовые поля
	$("#"+form.id).find("input:text").val('');
	// и обновим корзину
	return submitProductPriceForm(form);
}

function loadShoppingCartData(id, send_data) {
	var url = "/price/shopping-cart/edit2/" + id;
	if (send_data == null) {
		var s_type = "GET";
	} else {
		var s_type = "POST";
	}
	$.ajax({
		url: url,
		cache: false,
		data: send_data,
		dataType: "json",
		type: s_type,
		success: function(data) {
			if (data.product_id != null) {
				var id = data.product_id;
				var elem = null;

				if (data.price != null) {
					elem = $("#price-" + id);
					if (elem.length > 0) {
						elem.text(data.price);
					}
				}

				if (data.amount != null) {
					elem = $("#amount-" + id);
					if (elem.length > 0) {
						elem.text(data.amount);
					}
				} else {
					$("#amount-"+id).parent().parent().remove();
				}

				if (data.order != null) {
					$("#order-" + id).html(data.order);
				}

				recalcTotals(data);
			}

			if (data.is_item_disabled != null) {
				location.reload(true);
			}
		}
	});
}

function clickShoppingCartLink(link) {
	var id = link.firstChild.id;
	id = id.substring(id.lastIndexOf("-") + 1);

	var del = $("#del-" + id);
	var order = $("#order-" + id);
	if (order.length == 0) {
		order = $("<div/>").attr("id", "order-"+id).addClass("product_price").css("display", "none").html("Подгрузка данных...");
		del.after(order);

		loadShoppingCartData(id, null);
	}
	order.slideToggle("fast");
	jQuery(link).toggleClass("open");

	return false;
}

function submitShoppingCartForm(form) {
	var id = getIdByForm(form);

	var elem = $("#price-" + id);
	if (elem.length > 0) {
		elem.text("");
	}
	elem = $("#amount-" + id);
	if (elem.length > 0) {
		elem.text("");
	}

	loadShoppingCartData(id, $("#shopping-cart-product-" + id).serialize());

	form.parentNode.innerHTML = "Обновление данных...";

	return false;
}

function clickShoppingCartDel(obj) {
	if (obj.className == "del noajax") {
		return false;
	}

	obj.className = "del noajax";
	obj.textContent = "Удаление";

	var id = obj.id.replace(/del\-/, "");
	var url = "/price/shopping-cart/delete/" + id;
	$.ajax({
		url: url,
		cache: false,
		data: null,
		dataType: "json",
		type: "POST",
		success: function(data) {
			if (data.is_item_disabled != null) {
				location.reload(true);
			} else {
				recalcTotals(data);
				$(obj).parent().remove();
			}
		},
		error: function(data) {
			obj.className = "del";
			obj.textContent = "Удалить";
		}
	});

	return false;
}

function recalcTotals(data) {
	elem = $("#total_price");
	if (data.total_price != null) {
		elem.text(data.total_price);
	} else {
		elem.text('');
	}

	elem = $("#total_amount");
	if (data.total_amount != null) {
		elem.text(data.total_amount);
	} else {
		elem.text('');
	}

	elem = $("#total_menu_" + data.menu_current);
	if (data.total_menu != null) {
		elem.text(data.total_menu);
	} else {
		elem.text(0);
	}

	if (data.cart_count != null) {
		$("#cart_count").html(data.cart_count);
	}

	return true;
}

function changeOrderStatus(link, order_id) {
	if (confirm("Вы уверены, что хотите подтвердить заказ " + order_id + "?")) {
		var url = "/price/orders/" + order_id + "/status";
		$.ajax({
			url: url,
			cache: false,
			data: null,
			type: "POST",
			beforeSend: function() {
				link.parentNode.removeChild(link);
				$("#o-st-" + order_id).text("Подтверждение...");
			},
			success: function(data) {
				data = unescape(data);
				data = data.split("|");
				$("#o-st-" + order_id).text(data[1]);
			},
			error: function(data) {
				$("#o-st-" + order_id).text("Ошибка");
			}
		});
	}
	return false;
}

function loadOrderData(id) {
	var url = "/price/orders/" + id + "/view";
	$.ajax({
		url: url,
		cache: false,
		data: null,
		type: "POST",
		success: function(data) {
			data = unescape(data);
			$("#o-p-"+id).html(data);
		},
		error: function(data) {
			$("#o-p-"+id).text("Подгрузка данных завершилась неудачей. Пожалуйста, повторите попытку.");
		}
	});
}

function disableForm(form_id) {
	$("#"+form_id+" :input").attr("disabled", "disabled");
}

function enableForm(form_id) {
	$("#"+form_id+" :input").removeAttr("disabled");
}

function submitRating(form) {
	var url = form.action;
	url = url.substr(0, url.lastIndexOf("/"));
	url += "/json";

	var k = form.elements.length
	for (var i = 0; i < k; i++) {
		var element = form.elements[i];
		if (element.name != "") {
			url += "/" + element.name + ":" + element.value;
		}
	}

	$.ajax({
		url: url,
		cache: true,
		dataType: "json",
		data: null,
		type: "POST",
		beforeSend: function() {
			disableForm("RatingFilterAddForm");
			showAjaxText("ratings-list", "Подгрузка данных...", "loading");
		},
		error: function(data) {
			$("#ratings-list").html("<p class=\"lilac\">Подгрузка данных завершилась неудачей. Пожалуйста, повторите попытку.</p>");
			enableForm("RatingFilterAddForm");
		},
		success: function(data) {
			if (data.filters != null) {
				var filter_name;
				var k = data.filters.length;
				for (var i = 0; i < k; i++) {
					filter_name = data.filters[i];

					if (data[filter_name] !== undefined) {
						$("#RatingFilter"+filter_name).html(data[filter_name]);
					}
				}
			}

			$("#ratings-header").html(data.items_title);
			$("#ratings-list").html(data.items);

			enableForm("RatingFilterAddForm");
		}
	});
	return false;
}