(function(e) {
	e.suggest = function(j, a) {
		function m() {
			g.offset();
			c.css({
				width : g.width() - 0
			})
		}
		function q(b) {
			if (/27$|38$|40$/.test(b.keyCode) && c.is(":visible")
					|| /^13$|^9$/.test(b.keyCode) && k()) {
				b.preventDefault && b.preventDefault();
				b.stopPropagation && b.stopPropagation();
				b.cancelBubble = true;
				b.returnValue = false;
				switch (b.keyCode) {
				case 38:
					($currentResult = k()) ? $currentResult.removeClass(
							a.selectClass).prev().addClass(a.selectClass) : c
							.children("li:last-child").addClass(a.selectClass);
					break;
				case 40:
					($currentResult = k()) ? $currentResult.removeClass(
							a.selectClass).next().addClass(a.selectClass) : c
							.children("li:first-child").addClass(a.selectClass);
					break;
				case 9:
				case 13:
					r();
					break;
				case 27:
					c.hide()
				}
			} else if (g.val().length != s) {
				n && clearTimeout(n);
				n = setTimeout(u, a.delay);
				s = g.val().length
			}
		}
		function u() {
			var b = e.trim(g.val());
			if (b.length >= a.minchars)
				(cached = v(b)) ? t(cached.items) : e.get(a.source, {
					q : b
				}, function(d) {
					c.hide();
					var f = w(d, b);
					t(f);
					for (d = d.length; h.length && o + d > a.maxCacheSize;) {
						var i = h.pop();
						o -= i.size
					}
					h.push({
						q : b,
						size : d,
						items : f
					});
					o += d
				});
			else
				c.hide()
		}
		function v(b) {
			for ( var d = 0; d < h.length; d++)
				if (h[d].q == b) {
					h.unshift(h.splice(d, 1)[0]);
					return h[0]
				}
			return false
		}
		function t(b) {
			if (b)
				if (b.length) {
					for ( var d = "", f = 0; f < b.length; f++)
						d += "<li"
								+ (b[f].key != "" ? ' id="s_' + b[f].key + '"'
										: "") + ">" + b[f].value + "</li>";
					c.html(d).show();
					c.children("li").mouseover(function() {
						c.children("li").removeClass(a.selectClass);
						e(this).addClass(a.selectClass)
					}).click(function(i) {
						i.preventDefault();
						i.stopPropagation();
						r()
					})
				} else
					c.hide()
		}
		function w(b, d) {
			for ( var f = [], i = b.split(a.delimiter), p = 0; p < i.length; p++) {
				var l = e.trim(i[p]).split(a.dataDelimiter);
				if (l.length > 1) {
					token = l[0];
					key = l[1]
				} else {
					token = l[0];
					key = ""
				}
				if (token) {
					token = token.replace(RegExp(d, "ig"), function(x) {
						return '<span class="' + a.matchClass + '">' + x
								+ "</span>"
					});
					f[f.length] = {
						value : token,
						key : key
					}
				}
			}
			return f
		}
		function k() {
			if (!c.is(":visible"))
				return false;
			var b = c.children("li." + a.selectClass);
			b.length || (b = false);
			return b
		}
		function r() {
			if ($currentResult = k()) {
				g.val($currentResult.attr("id").replace("s_", ""));
				c.hide();
				e(a.dataContainer)
						&& e(a.dataContainer).val(
								$currentResult.attr("id").replace("s_", ""));
				a.onSelect && a.onSelect.apply(g[0])
			}
		}
		var g = e(j).attr("autocomplete", "off"), c, n = false, s = 0, h = [], o = 0;
		if (!a.attachObject)
			a.attachObject = e(document.createElement("ul")).appendTo("body");
		c = e(a.attachObject);
		c.addClass(a.resultsClass);
		m();
		e(window).load(m).resize(m);
		g.blur(function() {
			setTimeout(function() {
				c.hide()
			}, 200)
		});
		try {
			c.bgiframe()
		} catch (y) {
		}
		e.browser.mozilla ? g.keypress(q) : g.keydown(q)
	};
	e.fn.suggest = function(j, a) {
		if (j) {
			a = a || {};
			a.source = j;
			a.delay = a.delay || 150;
			a.resultsClass = a.resultsClass || "ac_results";
			a.selectClass = a.selectClass || "ac_over";
			a.matchClass = a.matchClass || "ac_match";
			a.minchars = a.minchars || 2;
			a.delimiter = a.delimiter || "\n";
			a.onSelect = a.onSelect || false;
			a.maxCacheSize = a.maxCacheSize || 65536;
			a.dataDelimiter = a.dataDelimiter || "\t";
			a.dataContainer = a.dataContainer || "#SuggestResult";
			a.attachObject = a.attachObject || null;
			this.each(function() {
				new e.suggest(this, a)
			});
			return this
		}
	}
})(jQuery);

$(function() {

	$("a.popup").fancybox({
		'titlePosition' : 'inside',
		'padding' : '20',
		'overlayColor' : '#000'
	});

	var $searchBox = $(".search_box");
	var $searchText = $searchBox.find('.text');

	var emptyText = 'Введите фразу для поиска';

	$searchText.suggest('/autocomplete', {
		attachObject : '#search_box_autocomplete'
	}).click(function() {
		var $this = $(this);
		if ($this.val() == emptyText) {
			$this.val('');
		}
	}).blur(function() {
		var $this = $(this);
		if (!$this.val()) {
			$this.val(emptyText);
		}
	})

	if (!$searchText.val() || $searchText.val() == emptyText) {
		$searchText.val(emptyText);
	}
	$searchBox.find(".help a").click(function(e) {
		e.preventDefault();
		$searchText.val($(this).text())
	})

	

	$(".add_to_cart").click(function(e) {
		e.preventDefault();

		var $this = $(this);
		var addUrl = $this.data('link');
	
		if (!addUrl)
			return false;
id = $this.data('item');
name = $this.data('name');
$(".item" + id).html('Товар добавлен в <a href="/cart/"><b>корзину</b></a>');
$(".inner").html('<p>Товар "' + name + '" добавлен в корзину</p><p><a href="/cart">Перейти в корзину</a> <span>или</span> <a href="#" class="close">продолжить покупки</a></p>');

var $cartMessage = $(".cart_message");
var $cartMessageA = $(".cart_message .inner a");
// var cartTimeout;

$cartMessageA.click(function() {
	$cartMessage.fadeOut(400);
}).find(".close").click(function(e) {
	e.preventDefault();
})
		$.get(addUrl, function(response) {
			// clearTimeout(cartTimeout);
			var thisPrice = $this.data('price');
			var allPrice = $('.gprice').data('price');
			var goodCount = $('.gcount').data('amount');
			$('.gprice').text(number_format(thisPrice+allPrice,0,'.',' ')).data('price',thisPrice+allPrice);
			$('.gcount').text(goodCount+1).data('amount',goodCount+1);
			//gprice
			$cartMessage.fadeIn(400);
			/*
			 * .css({ left: e.pageX + "px", top: e.pageY + "px" })
			 */

			// cartTimeout = setTimeout(function(){
			// $cartMessage.fadeOut("slow");
			// }, 2500)
		})
	})
})

function number_format(number, decimals, dec_point, thousands_sep) { 
	var i, j, kw, kd, km;
	// input sanitation & defaults
	if (isNaN(decimals = Math.abs(decimals))) {
		decimals = 2;
	}
	if (dec_point == undefined) {
		dec_point = ",";
	}
	if (thousands_sep == undefined) {
		thousands_sep = ".";
	}
	i = parseInt(number = (+number || 0).toFixed(decimals)) + "";
	if ((j = i.length) > 3) {
		j = j % 3;
	} else {
		j = 0;
	}
	km = (j ? i.substr(0, j) + thousands_sep : "");
	kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
	// kd = (decimals ? dec_point + Math.abs(number -
	// i).toFixed(decimals).slice(2) : "");
	kd = (decimals ? dec_point
			+ Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2)
			: "");
	return km + kw + kd;
}

