$(function($) {
	if(window.location.href.indexOf('/ny2012/') == -1){
		$('form.simple_form').simpleForm();
	}
	
	

	$('.subscribe').simpleForm({
		errorNestedCallback: function(errors) {
			for (var fieldName in errors) {
				var errorsText = '';
				var fieldErrors = errors[fieldName];
				for (var errorCode in fieldErrors) {
					errorsText += fieldErrors[errorCode] + '<br>';
				}
				$('.subscribe').find('div.form_error_container').html(errorsText);
				//$('.subscribe').find("[name='"+fieldName+"']").addClass("border_red");
			}
		}
	});

	$('#auth_form').simpleForm({
		'errorArrayCallback': function(errors) {
			$(this.errorContainer, this.form).html(errors.join()).addClass(this.errorMessageClass);
			$('.inp-wrap', this.form).addClass('login_field_wrap');
			$('.inp-in', this.form).addClass('login_field_in');
			//$('input[type=text]', this.form).addClass(this.errorFieldClass);
		}
	});

	var oldCallback = $('#regfrm').simpleForm('option', 'errorNestedCallback');

	var newCallback = function(errors) {
		var oldMessage = this.errorMessageText;
		if ('user[email]' in errors && 'recordFound' in errors['user[email]']) {
			this.errorMessageText = errors['user[email]']['recordFound'];
		}

		oldCallback.call(this, errors);

		this.errorMessageText = oldMessage;
	};

	$('#regfrm').simpleForm('option', 'errorNestedCallback', newCallback);

	$('input.filter_digits').inputFilter('digits');
	$('input.filter_letters[valid_letters]').each(function() {
		var element = $(this);
		element.inputFilter('letters', element.attr('valid_letters'));
	});
});

function getVote() {
	var vote = $('input[name="vote"]');
	for (i = 0; i < vote.length; i++) {
		if (vote[i].checked == true) {
			var ref = $(vote[i]).attr('ref') != '' ? $(vote[i]).attr('ref') : '/';
			var vote_id = $(vote[i]).attr('id');
			var is_blank = $(vote[i]).attr('target');
			$.post('/index/vote/', {vote_id:vote_id}, function(data) {
				if (data && data.status == 'OK') window.location = data.body;
				
			}, 'json');
			if (is_blank == 1) window.open(ref, '_blank');
		}
	}
}

function vacancyForm() {
	var flag_false = 0;
	if (!$('#name').val() ) {
		$('#name').addClass("border_red");
		$('#qqq').show();

		flag_false = 1;
	}

	if (!$('#resume').val()) {
		$('#resume').addClass("border_red");
		$('#qqq').show();
		flag_false = 1;
	}
	if (!$('#surname').val()) {
		$('#surname').addClass("border_red");
		$('#qqq').show();
		flag_false = 1;
	}
	if(flag_false)
		return false;
	return true;
}

function addCatalogCookie(param1, param2) {
	$.cookie(param1, param2, { path: '/'});
	return true;
}

function submitSubscr() {	
	$('form.simple_form').unbind();
	return false;
}

/*function checkSubscr() {
 if($('#subscr_submit').attr('disabled') == true){
 $('#subscr_submit').attr('disabled','');
 }else{
 $('#subscr_submit').attr('disabled', 'disabled');
 };
 }*/

function socialClick(social_name, content_type, content_url, content_id, content_title, content_image) {
	var s1 = '';

	switch (content_type) {
		case 'news':
			s1 = 'Мне понравилась новость ';
			break;
		default:
			s1 = '';
	}

	switch (social_name) {
		case 'twitter':
			if (content_url) {
				content_url += '&utm_source=twitter';
				content_title = content_title.substr(0,591);
				content_title = content_title.substr(0,content_title.lastIndexOf('+')) + '...';
				window.open('http://twitter.com/share?&url='+encodeURIComponent(content_url) + '&text='+ content_title, 'Twitter', "width=800,height=600,left=leftvar,top=topvar,status=no,toolbar=no,menubar=no");
			}
			break;
		case 'facebook':
			if (content_url) {
				content_url += '&utm_source=facebook';
				window.open("http://www.facebook.com/sharer.php?u=" + encodeURIComponent(content_url) + "&t=" + content_title, 'Facebook');
			}
			break;
		case 'vkontakte':
			if (content_url) {
				content_url += '&utm_source=vkontakte';
				if (content_image) {
					content_url = escape(content_url + '&image=' + content_image);
				};
				window.open("http://vkontakte.ru/share.php?url=" + encodeURIComponent(content_url), "displayWindow", "width=800,height=600,left=leftvar,top=topvar,status=no,toolbar=no,menubar=no");
			}
			break;
        case 'odnoklassniki':
			if (content_url) {
				content_url += '&utm_source=odnoklassniki';
				window.open("http://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=0&st._surl=" + encodeURIComponent(content_url), "displayWindow", "width=800,height=600,left=leftvar,top=topvar,status=no,toolbar=no,menubar=no");
			}
			break;
	}
}

// Инициализируем таблицу перевода
var trans = [];
for (var i = 0x410; i <= 0x44F; i++)
	trans[i] = i - 0x350; // А-Яа-я
trans[0x401] = 0xA8;    // Ё
trans[0x451] = 0xB8;    // ё

// Сохраняем стандартную функцию escape()
var escapeOrig = window.escape;

// Переопределяем функцию escape()
window.escape = function(str) {
	var ret = [];
	// Составляем массив кодов символов, попутно переводим кириллицу
	for (var i = 0; i < str.length; i++) {
		var n = str.charCodeAt(i);
		if (typeof trans[n] != 'undefined')
			n = trans[n];
		if (n <= 0xFF)
			ret.push(n);
	}
	return escapeOrig(String.fromCharCode.apply(null, ret));
}

function unsubscribe(id, key, cur_user) {
	$.post('/news/unsubscribe/confirm/yes/', {id:id, key:key, cur_user:cur_user},
			function(data) {
				if (data.body.success == true) {
					$('.unsubscribe').html('Вы успешно отписались от рассылки');
				} else {
					$('.unsubscribe').html('В процессе возникла ошибка. <a href="/pages/feedback">Обратитесь в службу поддержки.</a>');
				}
			}, 'json');
}

function real_valid_email(){

	$(document).ready(function(){
	$('#email').keyup(function(){

var noreg_email = $('#email').val();

	$('#email').blur(function(){
			if(noreg_email != 0)
			{
			if(isValidEmailAddress(noreg_email))
			{
			$("#email").css({
			"border": "1px #ccc solid"
			});
			} else {
			$("#email").css({
		"border": "1px red solid"
			});
			}
		}
	});
			});
		});
	}


function addComment(productId) {
	var data = '';
	var add_comment_comment = $('#comment').val();
	var noreg_email = $('#email').val();
	var noreg_name = $('#name').val();
	var capcha = $('#capcha').val();
	
	var text = $('#comment').val();
	if (text.length >1000){		
		$('#arror_mes').text('Комментарий должел быть максимум 1000 символов');			
		return false;
	}
	
	add_comment_comment = add_comment_comment.replace(/\n+/g,'\n');
	if (add_comment_comment.replace(/ /g, '') != '' && noreg_email != '' && noreg_name != '' && capcha != ''){
		$.post('/comments/add/', {item_id:productId, comment:add_comment_comment, sub_id: 1, name:noreg_name, email:noreg_email, code:capcha}, function(data) {
			$('#comment').val();
			if(data.status == 'ERROR'){
				$('#capcha').css('border', 'solid 1px red');
				d=new Date(); $('#kсaptcha').attr('src', '/dmcaptcha/?rnd=1234&white=1?'+d.getTime());
			}else{
				window.location.reload();
			}
		}, "json");
		}else{
			$('#arror_mes').text('Вы не заполнили все поля:');
	}
}

function addComment_popup(productId) {
	var data = '';
	var add_comment_comment = $('#comment_pu').val();
	var noreg_email = $('#email_pu').val();
	var noreg_name = $('#name_pu').val();
	var capcha = $('#capcha_pu').val();

	add_comment_comment = add_comment_comment.replace(/\n+/g,'\n');
	if (add_comment_comment.replace(/ /g, '') != '' && noreg_email != '' && noreg_name != '' && capcha != ''){
		$.post('/comments/add/', {item_id:productId, comment:add_comment_comment, sub_id: 1, name:noreg_name, email:noreg_email, code:capcha}, function(data) {
			$('#comment_pu').val();
			if(data.status == 'ERROR'){
				$('#capcha_pu').css('border', 'solid 1px red');
				$('#email_pu').css('border', 'solid 1px red');
				$('#new_com_h').text('Ошибка ввода е-mail / проверочного кода');
				$('#new_com_h').css('color' , '#faf2e7');
				d=new Date(); $('#kсaptcha_pu').attr('src', '/dmcaptcha/?rnd=1234?'+d.getTime());
			}else{
				window.location.reload();
				$('#new_comment_popup').fadeOut(500);
			}
		}, "json");
		}else{
			$('#new_com_h').text('Вы заполнили не все поля');
			$('#new_com_h').css('color' , '#faf2e7');
	}
}




function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function sendFreands(content_url, content_title) {
	var data = '';
	var heightClient = getClientHeight() / 2 - 53;
	var widthClient = getClientWidth() / 2 - 142;
	var mail_to = $('#email_to').val();
	var mail_from = $('#email_from').val();
	var url = 'http://' + document.domain + content_url+'/';
	if (mail_to.replace(/ /g, '') != '' && mail_from.replace(/ /g, '') != '') {
		$.post('/news/sendMail/', {mail_to:mail_to, mail_from:mail_from, url:url, messege:content_title}, function(data) {
			if (data.status == "OK") {
				$('#email_to').val('').removeClass('inputSendError');
				$('#send_to_friend').fadeOut(500);
				$('#product_send_ok').css('top', heightClient).css('left', widthClient);
				$('#product_send_ok').fadeIn(500);
				$('#btn1').live('click', function() {
					$('#product_send_ok').fadeOut(500);
				});
				$('#email_from').val('');
				$('.messwarning').hide();
			} else {
				$('#email_to').val('').addClass('inputSendError');
			}
		}, "json");
			$('.messwarning').css('display', 'none');
			$('.block_discript').css('margin-top', '0px');
	}
}

function showText(obj) {
	var oText = $(obj).parents('.review').find('.messwarning');
	var display = oText[0].style.display;
	if (display == "none") {
		oText[0].style.display = "block";
		var vkl = '';
	} else {
		oText[0].style.display = "none";
		var vkl = true;
	}

	if(vkl == ''){
	$('.block_discript').css('margin-top', '100px');
	}else{
	$('.block_discript').css('margin-top', '0px');
	}
	
}

function call_popup_send()
{
	$('#send_to_friend').center();
	$('#send_to_friend').fadeIn(500);
}
function uncall_popup_send()
{
	$('#send_to_friend').fadeOut(500);
}

function showForm(obj) {
	var oForm = $(obj).parents('.add_comment').find('.add_form');
	var display = oForm[0].style.display;
	if (display == "none") {
		oForm[0].style.display = "block";
	} else {
		oForm[0].style.display = "none";
		try {
			document.getElementById("comment").focus();
		} catch(e) {
			//alert(e);
		}
	}
}

jQuery(function($) {

	var inBasketCallback = function() {
		location.href = '/basket/';
		return false;
	};

	$('.in_basket').click(inBasketCallback);

	$('.h-prod_content .to_basket').each(function() {
		var element = $(this);

		var callback = function() {
			var sizeBlock = $('.h-size');
			if (sizeBlock.length > 0 && !sizeBlock.attr('selected')) {
				alert('Вы не выбрали размер!');
				return false;
			}

			Basket.setCount($(this).attr('product_id'), 1);
			element.unbind('click', callback).removeClass('to_basket').addClass('in_basket').click(inBasketCallback);
			element.next().replaceWith(
					'<p style="clear: both;">Товар в наличии <a href="/basket/" style="margin-left:60px; font: bold 11px \'trebuchet ms\'; color: #6AA41E;">Оформить заказ</a></p>'
					);
			Basket.successMessage();
		};
		element.bind('click', callback);
	});
});


/* Обновление каптчи в формах, удаление значения из поля */
$(function($) {
	$('#btnSubmit').click(function() {
		var $email = $('#email').val();
		if ($email) $email = $email.replace(/^\s+/, "").replace(/\s+$/, "");
		$('#email').val($email);
		var $first_name = $('#first_name').val();
		if ($first_name) $first_name = $first_name.replace(/^\s+/, "").replace(/\s+$/, "");
		$('#first_name').val($first_name);
		var $last_name = $('#last_name').val();
		if ($last_name) $last_name = $last_name.replace(/^\s+/, "").replace(/\s+$/, "");
		$('#last_name').val($last_name);
		$("#regfrm").submit();
	});

	$('form.simple_form_captcha').simpleForm({
		afterHandleErrorsCallback: function(errors) {
			$("#capcha").val('');
			$('#updlink').click();
		}
	});
});
/* Обновление каптчи в формах, удаление значения из поля */

jQuery(function($) {

	var BasketButtonSmallClass = function(element) {
		this.element = element;
		this.productId = $(element).attr('product_id');

		this.repeat_order = $(element).attr('repeat');

		var button = this;
		$(element).click(function() {
			return button.click();
		});
	};

	BasketButtonSmallClass.prototype = {
		products: "",
		products_counts: "",

		click: function() {
			var e = $(this.element);

			var method;

			if (e.hasClass('multiple')) {
				method = 'clickMultiple';
			}
			else if (e.hasClass('basket-btn-in')) {
				method = 'clickAdded';
			}
			else if (e.hasClass('basket-btn-none')) {
				method = 'clickBlocked';
			}
			else if (e.hasClass('repeat-order')) {
				method = 'clickRepeatOrder';
				this.products = e.attr('products');
				this.products_counts = e.attr('counts');
			}
			else {
				method = 'clickNotAdded';
			}

			return this[method]();
		},

		clickNotAdded: function() {
			Basket.setCount(this.productId, 1);
			$(this.element).removeClass('to_basket').addClass('basket-btn-in');
			Basket.successMessage();
			return true;
		},

		clickRepeatOrder: function(e) {
			if (this.products != "") {
				Basket.add_products(this.products, this.products_counts);
			}
			return true;
		},

		clickAdded: function() {
			location.href = '/basket/';
			return false;
		},

		clickBlocked: function() {
			return false;
		},

		clickMultiple: function() {
			location.href = '/product/index/id/' + this.productId + '/';
			return false;
		}
	};

	$('.basket-btn, .repeat-order').each(function() {
		new BasketButtonSmallClass(this);
	});

	$('.rating.active img').hover(function() {
		var parent = $(this).parents('.rating');

		parent.find("img").each(function(i) {
			$(this).removeClass('reit_full').addClass('reit_full_null');
		});

		$(this).removeClass('reit_full_null').addClass('reit_full');
		$(this).prevAll().removeClass('reit_full_null').addClass('reit_full');
	}, function() {
		var parent = $(this).parents('.rating');
		$('.rat', parent).removeClass('reit_full').addClass('reit_full_null');
		var res = Math.round(parent.attr('rat'));
		parent.find("img").each(function(i) {
			this.className = "rat";
			if (res <= i) {
				$(this).addClass("reit_full_null");
			} else {
				$(this).addClass("reit_full");
			}
		});
	});


	$('.comm_rating.active img').hover(function() {
		var parent = $(this).parents('.comm_rating');

		parent.find("img").each(function(i) {
			$(this).removeClass('reit2_full').addClass('reit2_full_null');
		});

		$(this).removeClass('reit2_full_null').addClass('reit2_full');
		$(this).prevAll().removeClass('reit2_full_null').addClass('reit2_full');
	}, function() {
		var parent = $(this).parents('.comm_rating');
		$('.rat', parent).removeClass('reit2_full').addClass('reit2_full_null');
		var res = Math.round(parent.attr('rat'));
		parent.find("img").each(function(i) {
			this.className = "rat";
			if (res <= i) {
				$(this).addClass("reit2_full_null");
			} else {
				$(this).addClass("reit2_full");
			}
		});
	});

	$('.blog_rating.active img').hover(function() {
		var parent = $(this).parents('.blog_rating');

		parent.find("img").each(function(i) {
			$(this).removeClass('reit_full').addClass('reit2_full_null');
		});

		$(this).removeClass('reit2_full_null').addClass('reit2_full');
		$(this).prevAll().removeClass('reit2_full_null').addClass('reit2_full');
	}, function() {
		var parent = $(this).parents('.blog_rating');
		$('.rat', parent).removeClass('reit2_full').addClass('reit2_full_null');
		var res = Math.round(parent.attr('rat'));
		parent.find("img").each(function(i) {
			this.className = "rat";
			if (res <= i) {
				$(this).addClass("reit2_full_null");
			} else {
				$(this).addClass("reit2_full");
			}
		});
	});


	$('.rating.active img').click(function() {
		var r = $(this).attr('rating');
		var parent = $(this).parents('.rating');
		$('.rat', parent).unbind();
		var id = parent.attr("product_id");
		$('#new_comment_popup').fadeIn(500);
		$.post("/product/vote/", {rating: r, product_id: id, sub_id: 1}, function(data) {
			var res = Math.round(data.body);
			parent.find("img").each(function(i) {
				this.className = "";
				if (res <= i) {
					$(this).addClass("reit_full_null");
				} else {
					if (res > i) {
						$(this).addClass("reit_full");
					}
				}
			});
		}, "json");

		$('div .rating').removeClass('active');
		$('div .rating').addClass('notactive');

		$("div .rating").qtip("destroy");
		$("div .rating").qtip({
			content: 'Спасибо, вы уже дали оценку этому товару.',
			style: {
				classes: 'ui-tooltip-green',
				tip: 'topLeft'
			}
		});
	});


	$('.comm_rating.active img').click(function() {		
		var r = $(this).attr('comm_rating');
		var parent = $(this).parents('.comm_rating');
		$('.rat', parent).unbind();
		var id = parent.attr("comment_id");
		$.post("/comments/vote/", {comm_rating: r, comment_id: id, sub_id: 1}, function(data) {
			var nr = data.body.split(',');
			var res = Math.round(nr[0]);
			var i;
			parent.find("img").each(function(i) {
				this.className = "";
				if (res <= i) {
					$(this).addClass("reit2_full_null");
				} else {
					if (res > i) {
						$(this).addClass("reit2_full");
					}
				}
				i++;
			});

			slr = ".comm_rat[comment_id='" + id + "']";
			$(slr).text(res + " (" + nr[1] + ")");
		}, "json");
	});


$('.blog_rating.active img').click(function() {	
		var r = $(this).attr('message_rating');
		var parent = $(this).parents('.blog_rating');
		$('.rat', parent).unbind();
		var id = $(this).parents().find('.id_mes').val();

		if(r && id){
			$.post("/blog/vote/", {message_rating: r, message_id: id, sub_id: 1}, function(data) {
				var nr = data.body.split(',');
				var res = Math.round(nr[0]);
				parent.find("img").each(function(i) {
					this.className = "";
					if (res <= i) {
						$(this).addClass("reit2_full_null");
					} else {
						if (res > i) {
							$(this).parent('.blog_rating').attr('class', 'blog_rating noactive');
							blog_star_rating(1);
							$(this).addClass("reit2_full");
						}
					}
				});

				slr = ".message_rat[mess_id='" + id + "']";
				$(slr).text(res + " (" + nr[1] + ")");
			}, "json");
		}
	});
});
function blog_star_rating(user)
{
	var active;
	$('.blog_rating').each(function(){
	if(user == 1){
				active = $(this).attr('class');
				if(active == 'blog_rating active'){
						$(this).attr('title','Проголосуйте за сообщение в блоге.');
					}else{
						$(this).attr('title','Спасибо, вы уже дали оценку этому сообщению.');
					}
				}else{
						$(this).attr('title','Оценивать сообщение могут только авторизованные пользователи!');
				}
	});
	$('.blog_rating').tipTip({ maxWidth: "300px", edgeOffset: 5});
}
/* product_notice */
function getClientWidth() {
	return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientWidth : document.body.clientWidth;
}

function getClientHeight() {
	return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientHeight : document.body.clientHeight;
}

jQuery.fn.center = function () {
	$(this).css({top:'50%',left:'50%',margin:'-'+($(this).height() / 2)+'px 0 0 -'+($(this).width() / 2)+'px'});
	return this;
}

function notice_func(prod_id, prod_name, cu_id, cu_email, ntype, obj) {
	var product_notice = prod_name;
	var user_email = cu_email;
	var product_id = prod_id;
	var user_id = cu_id;
	var ntype = ntype;
	var notice_text = '';

	if (user_email == "") {
		$('#product_notice_nouser').center();
		$('#product_notice_nouser').fadeIn(500);

		$('#product_btn1_nouser').click(function() {
			$('#product_notice_nouser').fadeOut(500);
		});
	}
	else {
		$('#product_popup_notice').center();
		$('#product_popup_notice').fadeIn(500);
		$('#product_notice > span').text(product_notice);

		if (ntype == 1) notice_text = "Уведомить о наличии: ";
		if (ntype == 2) notice_text = "Добавить в избранное ";
		if (ntype == 3) notice_text = "Вы хотите в подарок ";
		if (ntype == 4) notice_text = "Переместить в список отложенных ";
		$('#product_popup_notice #notice_text').html(notice_text);

		$("#product_btn1_notice").unbind();

		$('#product_btn1_notice').click(function() {
			postmsg_notice(user_id, product_id, ntype);
			spasibo(ntype);

			$('.order-notices-links').show();
			setTimeout(function(){postmsg_favorites_lightbox(product_id);}, 1000);
			// кнопка удаления из корзины
			if(obj != null) {
				var tr = $(obj).parent().parent().parent();
				$($(tr).children()[5]).children().click();
			}
		});

		$('#product_btn2_notice').click(function() {
			$('#product_popup_notice').fadeOut(500);
		});
	}
}

function spasibo(ntype)
{
	$('.product_popup_notice_td4').hide();
	if(ntype == 3){
		if(window.location.href.indexOf('/ny2012/') == -1){
		$('#product_popup_notice_name').html('Спасибо! Товар добавлен в ваш список <br> <a style="color: #fff;" href="/profile/wish/">Хочу в подарок</a>');
		$('.product_popup_aquo').css('display', 'none');
		}else{
			$('#product_popup_notice_name').html('Спасибо! Товар добавлен в ваш список <br> <a style="color: #fff;" href="/ny2012/wish/">Хочу в подарок</a>');
			$('.product_popup_aquo').css('display', 'none');
		}
	}
	if(ntype == 2){
		$('#product_popup_notice_name').html('Спасибо! Товар добавлен в ваш список <br><a style="color: #fff;" href="/profile/selected/">Избранное</a>');
		$('.product_popup_aquo').css('display', 'none');
	}
	if(ntype == 1){
		$('#product_popup_notice_name').html('Спасибо! Товар добавлен в ваш список <br> <a style="color: #fff;" href="/profile/notices/">Уведомить о наличии</a>');
		$('.product_popup_aquo').css('display', 'none');
	}
	$('#product_popup_notice #notice_text').hide();
	$('#product_ok').show();
	$('#product_ok').click(function(){
		$('#product_popup_notice').fadeOut(500);
		$('#product_ok').hide();
		$('#product_popup_notice #notice_text').show();
		$('.product_popup_notice_td4').show();
	});
	/*Скрывает кнопку добавить в вишлист для новогодней страницы*/
	$('.ny_add_wish').hide();
	$('.ny_del_wish').show();
}

function postmsg_notice(user_id, product_id, ntype) {
	$.post(
		'/product/notice/',
		{ product_id: product_id, user_id: user_id, ntype: ntype},
		function(data) {},
	'json');

	if(ntype == 1){
		$('.notify_me').hide();
	}
	if(ntype == 3){
		$('.pr-col6').hide();
	}
	if(ntype == 2){
		$('.pr-col7').hide();
	}

}

function postmsg_favorites_lightbox(product_id)
{
	Lib.Ajax.wrap('/profile/selected/ajaxfavorites/id/' + product_id, function(data){
				if(data.favorites_lightbox){
					$('#favorites_lightbox').html(data.favorites_lightbox['html']);
				}
			});
}
/* product_notice */

function slide_print() {
	$('.pr-col4').toggle(function() {
		//$(this).text('Назад');
		$('.nav').slideUp(3000);
		$('#auth_form').fadeOut(1000);
		$('.help-nav').fadeOut(1000);
		$('.basket').fadeOut(1000);
		$('.beta').fadeOut(1000);
		$('.search').fadeOut(1000);
		$('html, body').animate({ scrollTop: 0 }, 1500);
		$('.h-footer').slideUp(1000);
		$('.h-nav-wrap').fadeOut(1000);
		$('.h-subhead-wrap').fadeOut(1000);
		$('.tel1').css('position', 'absolute').css('top', '55px').css('left', '900px');
		$('.tel2').css('position', 'absolute').css('top', '57px').css('left', '750px');
		$('.h-headin').css('margin-top', '40px').css('float', 'right').css('width', '600px');
		$('.pr-col5').fadeOut(1000);
		$('.sec-top').fadeOut(1000);
		$('.sec-bot').fadeOut(1000);
		$('.my-wrap').fadeOut(1000);
		$('.comment').fadeOut(1000);
		$('.pr-col4 h3').text('Вернуться назад');
		$('.h-section-inner').css('border-width', '0px');
		$('.send_repost_print').fadeOut(1000);
		$('.h-carousel5').fadeOut(1000);
		$('.h-carousel6').fadeOut(1000);
		$('.pr-col7').fadeOut(1000);
		$('.pr-col6').fadeOut(1000);
		$('#soc_set_like').fadeOut(1000);
		$('.lightbox_fixed').css('display','none');
		

	}, function() {
		$('.pr-col4 h3').text('Версия для печати');
		$('.nav').fadeIn(1000);
		$('#auth_form').fadeIn(1000);
		$('.help-nav').fadeIn(1000);
		$('.basket').fadeIn(1000);
		$('.beta').fadeIn(1000);
		$('.search').fadeIn(1000);
		$('.h-footer').fadeIn(1000);
		$('.h-nav-wrap').fadeIn(1000);
		$('.h-subhead-wrap').fadeIn(1000);
		$('.tel1').css('position', 'static');
		$('.tel2').css('position', 'static');
		$('.h-headin').css('margin-top', '0px').css('float', 'left').css('width', '729px');
		$('.sec-top').fadeIn(1000);
		$('.sec-bot').fadeIn(1000);
		$('.h-section-inner').css('border-width', '3px');
		$('.my-wrap').fadeOut(1000);
		$('.comment').fadeIn(1000);
		$('.pr-col5').fadeIn(1000);
		$('.send_repost_print').fadeIn(1000);
		$('.h-carousel5').fadeIn(1000);
		$('.h-carousel6').fadeIn(1000);
		$('.pr-col7').fadeIn(1000);
		$('.pr-col6').fadeIn(1000);
		$('#soc_set_like').fadeIn(1000);
		$('.lightbox_fixed').css('display','block');
		
	});
}

function select_product() {
	
	$('#main-menu-filter li a').click(function() {
		var block = $(this).attr('block');
		$('table.filter-block').hide();
		$('#'+block).show();
	});
}

// Удаление товара из корзины и добавление его в список отложенных
$(document).ready(function() {
	$(".delay-btn").click(function() {
		var tr = $(this).parent().parent().parent();
		// добавление в список отложенных товаров
		var prod_id = $(this).attr("product_id");
		var prod_name = $($(tr).children()[1]).children().children().text();
		var cu_id = $("#c_profile_id").val();
		var cu_email = $("#c_profile_email").val();
		var type = '4';
		notice_func(prod_id, prod_name, cu_id, cu_email, type, this);
	});
});

// fix Opera 11 bug <noscript>
$(document).ready(function() {
	$(".isScript").show();
	$(".noScript").hide();
});

function slide_yandex_map() {
	//$('#YMapsID').css('display', 'none');
	$('#slide_map').toggle(function() {
		$('#YMapsID').css('display', 'none');
		$(this).text('Показать карту');
	}, function() {
		$('#YMapsID').css('display', 'block');
		$(this).text('Скрыть карту');
	});
}
var tukeg = true;
var timer = 0;
function magazineSearch(city_id) {
	var type_shop = $('#type_shop').val();	
	var content_s = $('#magazine_search').val();	
	if(!city_id)
		{
			city_id = $('#city_box').val(); 
		}
		
		clearTimeout(timer);
		timer = setTimeout(
				function() {
					if (tukeg) {
						$.post(
								'/shops/search/',
						{ content_s: content_s, city: city_id, type_shop : type_shop},
								function(data) {
									$('#result_search').html(data);
									tukeg = true;
								});
						tukeg = false;
					}
				},
				500
				);
	
}

	function status_query(){
	$('.execute').click(function(){
		$('tr[status_id="Ожидает"]').hide();
		$('tr[status_id="Исполнилось"]').show();
		$('.execute').parents('li').addClass('active');
		$('.waiting').parents('li').removeClass('active');
		$('.all_stat').parents('li').removeClass('active');
	});

	$('.waiting').click(function(){
		$('tr[status_id="Ожидает"]').show();
		$('tr[status_id="Исполнилось"]').hide();
		$('.execute').parents('li').removeClass('active');
		$('.waiting').parents('li').addClass('active');
		$('.all_stat').parents('li').removeClass('active');
	});

	$('.all_stat').click(function(){
		$('tr[status_id="Ожидает"]').show();
		$('tr[status_id="Исполнилось"]').show();
		$('.execute').parents('li').removeClass('active');
		$('.waiting').parents('li').removeClass('active');
		$('.all_stat').parents('li').addClass('active');
	});
}


/* ------------ Модальное окно ------------- */
if(window.location.href.indexOf('/ny2012/') == -1){ //Условие для того чтобы не использовалось на новогоднем сайте
	$(function(){
		$.superbox.settings = {
			boxId: "superbox",
			boxClasses: "",
			overlayOpacity: .5,
			boxWidth: "950",
			boxHeight: "600",
			loadTxt: "Загрузка...",
			closeTxt: "Закрыть",
			prevTxt: "Назад",
			nextTxt: "Далее"
		};

		$.superbox();
	});
}


/* -- Форма регистрации при оформлении заказа --*/
$(function() {
	$('#is_reg').click(function() {
		$(".basket_reg_form").toggle(this.checked);
	})
});

/* -- дополняем адрес пагинатора если была нажата иконка --*/

	$(function(){
		var adress = location.href;
		if(adress.indexOf('?type=is_sale') > -1)
		{
				var link = $('.pager a').attr('href');
				var add_link = link + '?type=is_sale';
				$('.pager a').attr('href', add_link);
		}

		if(adress.indexOf('?type=is_new') > -1)
		{
				var link = $('.pager a').attr('href');
				var add_link = link + '?type=is_new';
				$('.pager a').attr('href', add_link);
		}

		if(adress.indexOf('?type=gender') > -1)
		{
				var link = $('.pager a').attr('href');
				var add_link = link + '?type=is_gender';
				$('.pager a').attr('href', add_link);
		}
		if(adress.indexOf('?type=is_recommended') > -1)
		{
				var link = $('.pager a').attr('href');
				var add_link = link + '?type=is_recommended';
				$('.pager a').attr('href', add_link);
		}

	});
	
$(document).ready(function(){
	$('.lightbox_ar_left').click(function(){
			var t = $(this);
			if(t.hasClass('lightbox_ar_right')){
				$('.lightbox_fixed').animate({right:'-660px'}, 500,function(){
					t.removeClass('lightbox_ar_right');
				});
			}else{
				$('.lightbox_fixed').animate({right:'0px'}, 500,function(){
					t.addClass('lightbox_ar_right');
				});
			}
		});
	$('body').click(function(event)
	{
		//alert(event.target.className);
		if(!$(event.target).parents('.lightbox_fixed')[0] && event.target.className != 'del_prod_lightbox' && event.target.className != ''){
			$('.lightbox_fixed').animate({right:'-660px'}, 500,function(){
					$('.lightbox_ar_left').removeClass('lightbox_ar_right');
				});
		}
	});
    $('.a2au').click(function(event)
	{
		$('.lightbox_fixed').animate({right:'-660px'}, 500,function(){
			$('.lightbox_ar_left').removeClass('lightbox_ar_right');
		});
	});
});

function lightboxBasket(id, val, event)
{
	if(event.keyCode == 13){
		Basket.setCount(id, val);
	}
}

function favorites_del(product_id)
{
		Lib.Ajax.wrap('/profile/selected/remove/id/' + product_id + '/?ajax=1', function(data){
			if(data.favorites_lightbox){
				$('#favorites_lightbox').html(data.favorites_lightbox['html']);
			}
		});
}


function convert2EN(from)
  {
	  var rusChars = new Array('а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ч','ц','ш','щ','э','ю','\я','ы','ъ','ь', ' ', '\'', '\"', '\#', '\$', '\%', '\&', '\*', '\,', '\:', '\;', '\<', '\>', '\?', '\[', '\]', '\^', '\{', '\}', '\|', '\!', '\@', '\(', '\)', '\-', '\=', '\+', '\/', '\\');
	  var transChars = new Array('a','b','v','g','d','e','jo','zh','z','i','j','k','l','m','n','o','p','r','s','t','u','f','h','ch','c','sh','csh','e','ju','ja','y','', '', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');

  from = from.toLowerCase();
  var to = "";
  var len = from.length;
  var character, isRus;
  for(var i=0; i < len; i++)
    {
    character = from.charAt(i,1);
    isRus = false;
    for(var j=0; j < rusChars.length; j++)
      {
      if(character == rusChars[j])
        {
        isRus = true;
        break;
        }
      }
    to += (isRus) ? transChars[j] : character;
    }
   return to;
  }


	function blog_submit(){
		var profile_name = $('.blog_input[name="profile_name"]').val();
		var blog_message = $('#blog_textarea').val();
		var blog_title = $('#blog_title_mes').val();
		var blog_profile_id = $('#blog_profile_id').val();
		var tags = $('#blog_tag_mes').val();
		var arr_tag = tags.split(',');
		var arr_tag_en = new Array();
		for(var i = 0; i <= arr_tag.length; i++){
			if(arr_tag[i] != undefined)
			{
				arr_tag_en[i] = convert2EN(arr_tag[i]);
			}
		}
		var reg = /[<>{}\;]/g;
		var regular = reg.test(blog_message);
		var regular1 = reg.test(blog_title);
		var regular2 = reg.test(tags);
		if(regular == true || regular1 == true || regular2 == true){
			$('#blog_error').html('* Вы ввели не допустимые символы в сообщении.');
		}else{
			$.post(
			'/blog/add',
			{ blog_profile_id: blog_profile_id, blog_message: blog_message, profile_name: profile_name, blog_title: blog_title, tags_rus:arr_tag, tags_eng:arr_tag_en},
			function(data) {
				if(data == 'ok'){
					location.reload();
				}
				if(data == 'er'){
					$('#blog_error').html('* Вы заполнили ни все поля.');
				}
			},
			'json');
		}
	}

	function comment_mes(id, comment, profile_id)
	{
		if(comment != 'Комментировать...' && comment.length > 3){
			var blog_comment = comment;
			var id_mes = id;
			var profile_id = profile_id;
			$.post(
			'/blog/addcomment/id/' + id_mes,
			{ blog_comment: blog_comment, id: id_mes, profile_id:profile_id },
			function(data){
				if(data.id_mes > 0){
					$('.comments_'+data.id_mes).html(data.maket);
					$("textarea[for='form_com_"+ data.id_mes +"']").val('Комментировать...');
				}

			},
			'json');
		}
	}

	function subscribe_email(email, dm_subscribe , type)
	{
		var heightClient = getClientHeight() / 2 - 53;
		var widthClient = getClientWidth() / 2 - 142;
		var reg = new RegExp("[0-9a-z_]+@[0-9a-z_^.]+\\.[a-z]{2,3}", 'i');
		if(email.match(reg))
		{
			if(dm_subscribe == 'on' && email != 'Ваш e-mail'){
				$.post('/subscribe/subscribe/',
						{ "email": email , type: type },
						function(data){
							if(data)
							{
								$('#subscribe_send_ok').css('display', 'block');
								$('#subscribe_send_ok').fadeIn(500);
								$('#subscribe_send_ok').css('position', 'fixed');
								$('#subscribe_send_ok').css('top', heightClient).css('left', widthClient);

								$('#btn1').live('click', function() {
									$('#subscribe_send_ok').fadeOut(500);
								});
								$('#substr_email').value='Ваш e-mail';
							}
						},
				'json');
			}
		} else {
			$('#substr_email').css('color', 'red').css('font-weight', 'bolder');
			$('#substr_email').value='Ваш e-mail';
		}
	}

	//Отправляю аякс запросы при авторизации из кук.
	function get_cookie(name)
	{
		cookie_name = name + "=";
		cookie_length = document.cookie.length;
		cookie_begin = 0;
		while (cookie_begin < cookie_length)
		{
		value_begin = cookie_begin + cookie_name.length;
		if (document.cookie.substring(cookie_begin, value_begin) == cookie_name)
		{
		var value_end = document.cookie.indexOf (";", value_begin);
		if (value_end == -1)
		{
		value_end = cookie_length;
		}
		return unescape(document.cookie.substring(value_begin, value_end));
		}
		cookie_begin = document.cookie.indexOf(" ", cookie_begin) + 1;
		if (cookie_begin == 0)
		{
		break;
		}
	}
	return null;
	}
	//$.cookie('auth_coocke', null); //удаляет куки
	var coocke = get_cookie('auth_coocke');
	if(coocke == 'yes'){
		setTimeout(function(){
		Basket.UpdateBasket();
		setCookie('auth_coocke', 'no');
		}, 2000);
	}

	function setCookie(name, value) {
      var valueEscaped = escape(value);
      var expiresDate = new Date();
      expiresDate.setTime(expiresDate.getTime() + 365 * 24 * 60 * 60 * 1000); // срок - 1 год, но его можно изменить
      var expires = expiresDate.toGMTString();
      var newCookie = name + "=" + valueEscaped + "; path=/; expires=" + expires;
      if (valueEscaped.length <= 4000) document.cookie = newCookie + ";";
	}
	$(document).ready(function(){
		var city_opt_name;
		var select_city = document.getElementById('list_city');
		if (select_city) {
			city_opt_name = select_city.options[select_city.selectedIndex].value;
			if(city_opt_name != 'Москва'){
				$('.tel').hide();
				$('.cars_ban_present').css('top','213px');
			}
		}
	});

function saveGeo(name)
{
	if(name == 'Москва'){
			$('.tel').show();
			$('.cars_ban_present').css('top','240px');
	}else{
		$('.tel').hide();
		$('.cars_ban_present').css('top','213px');
	}
	 $.cookie('geoCity', name, {expires: 7, path: '/'});
}

function sub_cats_slide(name){
	var cats = $('.sub_cats_cats').css('display');
	var tags = $('.sub_cats_tags').css('display');

	if (name == 'tags'){
		$('.h_tags').addClass('h_active');
		$('.h_sub_cats').removeClass('h_active');
		$('.h_slide').css('display' , 'block');

		if (cats == 'table') {
			$('.sub_cats_cats').slideToggle("fast");
			$('.sub_cats_tags'). slideToggle("fast");
		} else {
			$('.sub_cats_tags'). slideToggle("fast");
		}

	} else if (name == 'cats'){
		$('.h_tags').removeClass('h_active');
		$('.h_sub_cats').addClass('h_active');
		$('.h_slide').css('display' , 'block');


		if (tags == 'block') {
			$('.sub_cats_cats').slideToggle("fast");
			$('.sub_cats_tags'). slideToggle("fast");
		} else {
			$('.sub_cats_cats'). slideToggle("fast");
		}
	} else if (name == 'hide'){
		$('.h_slide').css('display' , 'none');
		$('.h_tags').removeClass('h_active');
		$('.h_sub_cats').removeClass('h_active');

		if (cats == 'table') {
			$('.sub_cats_cats').slideToggle("fast");
		} else if (tags == 'block') {
			$('.sub_cats_tags'). slideToggle("fast");
		} 
	}
}

geoFiltr = {
    Height: $(window).height() / 2 - 240,
	Width: $(window).width() / 2 - 400,
    popup: function(obj){
       var obj = $('#'+obj);
       obj.css('display','block');
	   //obj.show();
       obj.css('left',this.Width+'px');
       obj.css('top',this.Height+'px');
    },
    close: function(obj)
    {
        var obj = $('#'+obj);
        obj.css('display','none');
		//obj.hide();
    }
}
$(document).ready(function(){
    $('#geoPopup span').hover(function(){
            $(this).fadeTo(300,0.5);
           },function(){
            $(this).fadeTo(300,1);
    });
    $('#geoPopup span').click(function(){
        saveGeo($(this).html());
        $('span#geo_filtr').html($(this).html());
        geoFiltr.close('geoPopup');
    });
});

$(document).ready(function(){
    $('.pres_view').click(function(){
		$('#pres').show();
    });
	$('#pres_close').click(function(){
		$('#pres').hide();
	});
	/*$('html, body').click(function(event){
		if(!$(event.target).is('.pres_view, #pres, .pres_top, .pres_center, .pres_center_pad, .shops-filter-results,  .pres_in_shops, .pres_in_shops span, .pres_in_shops span b, .shops-filter-results a, .shops-filter-results .work, .shops-filter-results td, .shops-filter-results img, .pres_bottom')){
			$('#pres').hide();
		};
	});*/
	
});



function return_template_winter(sex, type){
	if(sex && type){
		$.post('/winter/sel/',
				{ "sex": sex , type: type},
				function(data){
					if(data.temp)
					{
						$('#template_autumn_2_1').html(data.temp);
					}
				},
		'json');
	}
}

$(function(){
	var rr = 1;
	var ll = 1;

		$('.rt_c2').each(function() {
			$(this).addClass('rtr_' + rr);
			rr = rr + 1 ;
		});
		$('.lt_c2').each(function() {
			$(this).addClass('rtl_' + ll);
			ll = ll + 1;
		});
})

$(function(){
	$('.basket_dialog_close_js').live('click',function(){		
		$.unblockUI(); 
        return false; 
    });
})


