// добавление в корзину
function addCart(i){
	var p = i.attr('id').substr(5);
	total_amount = 0;
	total_sum = 0;
	item_amount = 0;
	//if ($(".main-item").attr("id")) mitem = $(".main-item").attr("id").substr(1); else mitem = 0;
	$.getScript("/shops/add_ajax.html?itm="+p, function(){
		$('#cart-amount').text(total_amount);
		$('#cart-summa').text(total_sum);
		if (total_gifts > 0) $('#cart-gifts').removeClass('hidden');
		a = $(".cart-"+p);
		a.find('span').text(item_amount);
		a.slideDown('normal');
		/*
		if (mitem > 0 && mitem_amount) { 
			m = $(".main-item");
			m.find('span').text(mitem_amount);
			m.slideDown('normal');
		}
		*/
	});
}

// очистка пробелоа
function trim(t)
{
	return t.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '').replace(/ +$/, '').replace(/^ +/, '');
}

$(document).ready(function(){

	// слайдшоу хитов
	$('.hit').slideShow({
		slideEl:'div.hit-slide',
		linkNext:'a.next',
		linkPrev:'a.prev',
		numElement:'ul.pager a',
		duration:300,
		autoSlideShow:true,
		switchTime:6000,
		event:'click',
		currentEl:'span.current',
		allEl:'span.all'
	});

	// листалка фото товаров
	$('div.thumbs').galleryScroll({
		step:1,
		duration:1000,
		funcOnclick:function(){
		}
	});

	// добавление в корзину
	$('.add-cart-button, .btn-buy, .btn-add, .hit .price-box .buy-a').each(function(){
		var i = $(this).click(function(){
			addCart(i);
			if (this.className == 'btn-buy') {
				$('.btn-add').each(function(){
					var j = $(this).unbind().click(function(){
						addCart(j);
						return false;
					});
				});
			} 
			return false;
		});
	});

	// удаление из корзины
	$('.item-del, .item-del-cart').live("click",function(){
		var b = $(this);
		var i = this.className;
		var p = this.id.substr(4);
		total_amount = 0;
		total_sum = 0;
		$.getScript("/shops/add_ajax.html?itm="+p+"&del", function(){
			$('#cart-amount').text(total_amount);
			$('#cart-summa').text(total_sum);
			if (total_gifts <= 0) $('#cart-gifts').addClass('hidden');
			if (i == "item-del") {
				a = $(".cart-"+p);
				a.slideUp('normal');
				a.find('span').text('0');
			} else {
				if (total_amount == 0) $('#cart-table').replaceWith('<div align="center" style="width: 550px; margin-top: 20px; padding-bottom: 45px; color: red; font-weight: bold;">Ваша корзина пуста</div>'); else {
					$(".t"+p).remove();
					$('#cart-table-sum').text(total_sum);
				}
			}
		});
		return false;
	});

	// кнопка поиска
	$(".btn-search").click(function() {
		$("#search-form").submit();
	});

	// переключатель расширенного поиска
	$(".lnk-search").click(function() {
		$("#search-form .form-area.hidden").slideToggle('normal');
		return false;
	});

	// кнопки сравнения
	$("div.compare a").click(function() {
		$("#compare-form").submit();
	});

	// добавление к сравнению
	$('.add-compare').click(function(){
		t = $(this).find(":checkbox");
		p = t.attr("id").substr(12);
		c = t.attr("checked");
		t.next().html((c)?"<span style=\"color:red\">удалить из сравнения</span>":"добавить к сравнению");
		$.getScript("/shops/add_compare.html?itm="+p+((c)?"":"&del"), function(data){
			$('.compare-list').replaceWith(data);
		});
	});
	$('.compare-item img').live("click",function(){
		t = $(this);
		p = t.attr("id").substr(12);
		$.getScript("/shops/add_compare.html?itm="+p+"&del", function(data){
			$('.compare-list').replaceWith(data);
			a = $('#add-compare-'+p);
			a.attr("checked",false);
			a.next().html("добавить к сравнению");			
		});
		return false;
	});
	$('.compare-clear').live("click",function(){
		t = $(this);
		p = t.attr("id").substr(12);
		$.getScript("/shops/add_compare.html?itm="+p+"&clear", function(data){
			$('.compare-list').replaceWith(data);
			if (cat_id && cat_id == p) {
				a = $('[id^="add-compare"]').each(function(){
					$(this).attr("checked",false);
					$(this).next().html("добавить к сравнению");
				});
			}
		});
		return false;
	});

	// выбор кол-ва отображаемых товаров
	$("#pages-part").change(function() {
		$("#pages-part-form").submit();
	});

	// сброс-восстановление рейтинга при голосовании
	$("ul.star-rating:not(.comitem)").mouseover(function() {
		$(this).find("li.active").removeClass("active").addClass("disactive");
	}).mouseout(function() {
		$(this).find("li.disactive").removeClass("disactive").addClass("active");
	});

	// голосование
	$('ul.star-rating:not(.comment) li').click(function(){
		t = $(this);
		u = t.closest("ul");
		var p = u.attr("id").substr(5);
		var r = u.find("li").index(this);
		$.getScript("/shops/add_vote.html?itm="+p+"&r="+r, function(){
			u.find("li").removeClass("active").removeClass("disactive");
			t.addClass("active");
			if (count > 0) {
				u.next("span.lnk-comments").text(count);
				u.nextAll("span.your-vote").show();
				if ($(".container")) {
					a = parseInt($(".container").css("height"));
					b = parseInt($(".top").css("height"))-2;
					if (a < b) $(".container").css("height",b);
				}
				u.addClass("star-rating2");
				u.find("a").addClass("li-star");
			}
			$.cookie("r"+p, rating, {
				expires: 365,
				path: "/"//,
				/*
				domain: "",
				secure: true
				*/
			});
			u.nextAll(".your-rating-block").find(".your-rating").text(rating);
		});
		return false;
	});

	// голосование при комментарии
	$('ul.star-rating.comment:not(.comitem) li').click(function(){
		t = $(this);
		u = t.closest("ul");
		var r = u.find("li").index(this);
		$('#stars-value').val(r);
		u.find("li").removeClass("active").removeClass("disactive");
		t.addClass("active");
		checkForm();
		return false;
	});

	// отображение формы отзыва
	$('.form-trigger').click(function(){
		$('#comform-container').slideToggle('normal').toggleClass('hidden');
		if ($('#comform-container').hasClass('hidden')) $(this).find('a').text('написать отзыв'); else $(this).find('a').text('скрыть форму для отзыва');
		return false;
	});

	// оценка полезности отзыва
	$('.yes,.no').live("click",function(){
		t = $(this);
		p = t.attr("id").substr(3);
		if (!$.cookie("u"+p)) {
			c = t.attr("class");
			r = (c == 'yes') ? 1 : 0 ;
			$.getScript("/shops/add_useful.html?itm="+p+"&r="+r, function(){
				t.closest("div").find('span').removeClass('yes').removeClass('no');
				t.addClass('voted');
				if (count > 0) {
					$("#" + c + '-count-' + p).text(count);
				}
				$.cookie("u"+p, r, {
					expires: 365,
					path: "/"
				});
			});
		}
		return false;
	});

	// разворачивание аксессуаров
	$(".featured .others a").click(function() {
		$(this).closest(".featured").find(".section.hidden").slideToggle('normal');
		return false;
	});

	// чередование строк
	$('.row-color tr:odd:not(.tr-sel)').addClass('tr-odd');
	$('.row-color tr:even:not(.tr-sel)').addClass('tr-even');

	// модальное окно для окон
	$("a[rel='prettyPhotoWindow']").prettyPhoto({
		animationSpeed: 'normal',
		opacity: 0.50,
		allow_resize: false,
		theme: 'light_rounded',
		markup: '<div class="pp_pic_holder"> \
			<div class="ppt">&nbsp;</div> \
			<div class="pp_top"> \
				<div class="pp_left"></div> \
				<div class="pp_middle"></div> \
				<div class="pp_right"></div> \
			</div> \
			<div class="pp_content_container"> \
				<div class="pp_left"> \
				<div class="pp_right"> \
					<div class="pp_content"> \
						<div class="pp_loaderIcon"></div> \
						<div class="pp_fade"> \
							<a href="#" class="pp_expand" title="Полный размер">Увеличить</a> \
							<div class="pp_hoverContainer"> \
								<a class="pp_next" href="#">далее</a> \
								<a class="pp_previous" href="#">назад</a> \
							</div> \
							<div id="pp_full_res"></div> \
							<div class="pp_details"> \
								<a class="pp_close" href="#">Закрыть</a> \
							</div> \
						</div> \
					</div> \
				</div> \
				</div> \
			</div> \
			<div class="pp_bottom"> \
				<div class="pp_left"></div> \
				<div class="pp_middle"></div> \
				<div class="pp_right"></div> \
			</div> \
		</div> \
		<div class="pp_overlay"></div>',
		gallery_markup: '',
		social_tools: ''
	});

	// всплывающая подсказка
	$('.rating-info,.lnk-comments').tooltip({
	  	track: true,
	  	delay: 0,
		showBody: "::",
		showURL: false,
		top: 20,
		left: 10,
	  	opacity: 0.85
	});

});

// закрытие модального окна
function closeModal(i) {
	t = $('#cur-amount').text();
	if ((t == '' || t == 0) && $.cookie("main-add") != 1 && i == 1) {
		addCart($('.btn-buy'));
	}
	$.cookie("main-add", 1, {
		path: "/catalogue/"
	});
	$('.btn-add').each(function(){
		var j = $(this).unbind().click(function(){
			addCart(j);
			return false;
		});
	});
	$.prettyPhoto.close();
	return false;
};
