eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(7($){$.8.9=7(d){g e=$.v({},$.8.9.k,d);g f=e.l;2.w(7(){5(!$(2).3(\'4\')||$(2).3(\'4\')=="#"){$(2).3(\'4\',j.x.4)}5(!$(2).3(\'6\')){$(2).3(\'6\',y.6)}5($.h.z){$(2).3(\'m\',$(2).3(\'4\')).3(\'4\',\'\').3(\'4\',\'A:B(0)\').3(\'C\',\'$.8.9.n(2,"\'+$(2).3(\'6\')+\'","\'+$(2).3(\'m\')+\'")\')}i{$(2).o(p)}});7 p(a){g b=$(2).3(\'4\');g c=$(2).3(\'6\');b=b.E("q:///","F://q/");5($.h.G){j.H.I(b,c)}i 5($.h.J){j.r.K(c,b,\'\')}i 5(L.M.N().O(\'P\')>-1){s(f)}i 5($.h.Q){s(f)}a.R()};t 2};$.8.9.k={l:\'S "T + D" U "V + D" W X, u Y 2 Z u 10 11.\'};$.8.9.n=7(e,a,b){e.12="r";e.6=a;e.4="";e.4=b;e.o();t 13}})(14);',62,67,'||this|attr|href|if|title|function|fn|jFav|||||||var|browser|else|window|defaults|msg|link|OperaBookmark|click|addToFavorites|file|sidebar|alert|return|to|extend|each|location|document|opera|javascript|void|onClick||replace|http|msie|external|AddFavorite|mozilla|addPanel|navigator|userAgent|toLowerCase|indexOf|chrome|safari|preventDefault|Press|Ctrl|or|CMD|for|MAC|add|page|your|bookmarks|rel|false|jQuery'.split('|'),0,{}));

Number.prototype.plural = function(titles){
	var cases = [2, 0, 1, 1, 1, 2];  
    return titles[ (this%100>4 && this%100<20)? 2 : cases[(this%10<5)?this%10:5] ];  
}

String.prototype.plural = function(titles) {
	return parseInt(this).plural(title);
}

function bind_cart_button()
{
	$(".cart_button").click(function() {
		var input = $(this).parent().find(".order_count_catalog");
		var name = input.attr('name');
		var value = input.val();
		var element = $(this).parent();
		element.html('<img src="/i/loading.gif">');
		$.post('/catalog', {action: 'add', name: name, value: value, ajax: 'true'}, function(data) {
			if (!data.hasOwnProperty('error')) {
				element.html('<span class="added_to_cart">Товар добавлен в <a href="/cart">корзину</a>.</span>');
				console.log(data);
				$(".cart_count").html('В корзине:<br />' + data.total + ' ' + data.total.plural(['товар', 'товара', 'товаров']));
			} else {
				element.html('<span class="added_to_cart">Ошибка при добавлении товара.</span>');
			}
		}, "json").error(function(event){
			element.html('<span class="added_to_cart">Ошибка при добавлении товара.</span>');
		});
		
		return false;
	});
}

var update_announces_height = function(){
	$('#home_products').each(function(){
		var max_height = 0;
		$(this).find('.wnd>.l>.r>.t>.b>.lt>.rt>.lb>.rb>.content').css('height', 'auto').each(function(){
			var height = $(this).height();
			if (height > max_height) max_height = height;
		});
		$(this).find('.wnd>.l>.r>.t>.b>.lt>.rt>.lb>.rb>.content').css('height', max_height+'px');
	});
};

$(window).load(function(){
	update_announces_height();
});

var resizeTimer;
$(window).resize(function(){
	clearTimeout(resizeTimer);
	resizeTimer = setTimeout(update_announces_height, 50);
});

$(document).ready(function(){
	$('#category_items li:nth-child(2n+1)').addClass('linefeed');
	
	$('.payment_methods_placeholder strong').click(function(){
		$(this).parent().find('.payment_methods').toggle();
	});

/*
	$('.tech_info .toggle').click(function(){
		$(this).closest('.tech_info').find('.content').slideToggle(300);
	});
*/
/*
	$('.carousel').jcarousel({
        visible: 1,
		wrap: 'circular',
		scroll: 1,
		auto: 5
    });
*/
	$('.mail_tracking').click(function(){
		var code = $(this).text();
		var form = $('#tracking_form');
		form.find('input[name=BarCode]').val(code);
		form.submit();
		return false;
	});

	$('#cash_on_delivery').change(function(){
		if ($(this).is(':checked')) {
			$('.price_standard').hide();
			$('.price_cod').show();
			var radio = $('input:radio[value=3]');
			if (radio.is(':checked')) {
				radio.attr('checked', '');
				$('input:radio[value=0]').attr('checked', 'checked');
			}
			radio.attr('disabled', 'disabled');
		} else {
			$('.price_cod').hide();
			$('.price_standard').show();
			$('input:radio[value=3]').attr('disabled', '');
		}
	}).change();

	$('.activate_lightbox').click(function(){
		$('ol.thumbs li:first-child a').click();
		return false;
	});

	$('.unfoldable_block .title').click(function(){
		$(this).parent().find('.content').slideToggle('fast');
	});
	$('.add_to_favorites').jFav();
	
	$(".remove_from_cart").click(function(){
		var id = $(this).attr('rel');
		var elem = $(this).parent().parent();
		$.post('/catalog', {action: 'remove', id: id, ajax: 'true'}, function(data) {
			if (data.error == false)
			{
				elem.remove();
				$(".cart_price_total").html(data.price_total);
				var total_str = (data.total > 0) ? 'товаров в корзине:  '+data.total : 'ваша корзина пуста';
				$(".cart_count").html(total_str);
			}
		}, "json").error(function(event){
			elem.remove();
		});
	});
	
	// отображение дополнительных полей для юр.лиц
	$("input[name=utype]").click(function() {
		if ($(this).is(":checked"))
		{
			$("#b_company").show();
		} else
		{
			$("#b_company").hide();
		}
	});
	
	// отображение дополнительных полей в регистрационной форме
	if ($("input[name=utype]").is(":checked"))
	{
		$("#b_company").show();
	} else
	{
		$("#b_company").hide();
	}
	
	
	var check_reg_form = function(){
		clearTimeout(validation_timeout);
		var elem = this;
		validation_timeout = setTimeout(function(){
			$.post('/auth/register/ajax', {field: $(elem).attr('name'), value: $(elem).val()}, function(response){
				if (response != 'ok'){
					$(elem).parent().parent().find('.status').html(response);
				} else {
					$(elem).parent().parent().find('.status').html('<img src="/i/ok.gif">');
				}
			});
		}, 500);
	};
	
	/*
	$(".forminput.textfield input").keyup(check_reg_form);
	$(".forminput.textfield input").blur(check_reg_form);
	*/
	
	$(".order_count").click(function(){
		if($(this).val() == '1') $(this).val('');
	});
	
	$(".order_count").blur(function(){
		if($(this).val() == '') $(this).val('1');
	});
	
	$("#usersearchbox #query").focus(function(){
		if ($(this).val() == 'Поиск')
		{
			$(this).val('');
		}
	});
	
	$("#usersearchbox #query").blur(function(){
		if ($(this).val() == '')
		{
			$(this).val('Поиск');
		}
	});
	
	$("img.captcha").click(function(){
		$(this).attr('src', '/api/captcha/'+Math.random());
	});
	
	var fancybox_options = {
		'titlePosition'	: 'inside',
		'overlayColor'		: '#000',
		'overlayOpacity'	: 0.3,
		'mouseWheelNavigation' : true
	};

	$('.attachments a').fancybox(fancybox_options);
	
	var thumbs = $('#product .thumbs a');
	if (thumbs.length) {
		$('#product .thumbs a').fancybox(fancybox_options);
	} else {
		$('.activate_lightbox').unbind('click').fancybox(fancybox_options);
	}
	
	fancybox_options["mouseWheelNavigation"] = false;
	
	$('.tech_info a.toggle').fancybox(fancybox_options);
	
	fancybox_options["width"] = 600;
	fancybox_options["height"] = 500;
	fancybox_options["autoDimensions"] = false;
	
	$('.popup a.toggle').fancybox(fancybox_options);

	bind_cart_button();
});
