/**
 * vim:ts=4:sw=4:noet:nowrap
 * @author Антонов Андрей dustweb.ru
 */


var price_slide, price_slide_l, price_slide_r;

$(window).ready(function(){
	
	//Бренды на главной
	$('#brandsBottomCloseBtn').click(function(){
		$('#brandsPanel').slideUp("fast");
		$('#brandsButton').removeClass('brandsButton_opened');
	});
	$('#brandsButton').click(function(){
		if($(this).hasClass('brandsButton_opened')) {
			$('#brandsPanel').slideUp("fast");
			$('#brandsButton').removeClass('brandsButton_opened');
		} else {
			$('#brandsPanel').slideDown("normal");
			$(this).addClass('brandsButton_opened');
		}
	});
	$('#brandsList a').click(function(){
		$('#brandsPanel').slideUp("normal");
	});
	
	//«Возможно понадобится»
	if($('#relBlock').html() != '') runRels();
	function runRels() {
		//«Нет спасибо»
		$('#rels_h_no_tanx').click(function(){
			$('#rels').slideUp('normal', function(){
				$(this).remove();
			});
		});
		//Ресайз
		var relItemWidth = 0;
		function relViewportResize() {
			var newWidth = $('.rel_prod:eq(0)').width();
			$('.rel_prod_holder,.rel_item').css('width', newWidth+'px');
			relItemWidth = newWidth;
		}
		relViewportResize();
		//Скрытие правой стрелки при одном товаре в карусели
		$('.rel_prod_list').each(function(i, item){
			if($(item).find('.rel_item').length == 1) {
				//alert($(item).html());
				$(item).parent().parent().next().css('visibility','hidden');
			} else {
				$(this).width(relItemWidth * $(this).find('.rel_item').length);
			}
		});
		//Стрелка влево
		$('.rel_l').click(function(){
			$(this).next().next().css('visibility','visible');
		
			var holder = $(this).next('.rel_prod').find('.rel_prod_holder');
			var inner = $(this).next('.rel_prod').find('.rel_prod_list');
			var items = holder.find('.rel_item');
			var itemsCount = items.length;
		
			if(typeof(holder.data('scrolled')) == 'undefined') holder.data('scrolled', 0);
			if(holder.data('scrolled') >= -relItemWidth) {
				$(this).css('visibility','hidden');
			}
			holder.data('scrolled', holder.data('scrolled')+relItemWidth);
			inner.animate({
				marginLeft: '+=' + relItemWidth + 'px'
			},333);
		});
		//Стрелка вправо
		$('.rel_r').click(function(){
			$(this).prev().prev().css('visibility','visible');
		
			var holder = $(this).prev('.rel_prod').find('.rel_prod_holder');
			var inner = $(this).prev('.rel_prod').find('.rel_prod_list');
			var items = holder.find('.rel_item');
			var itemsCount = items.length;
		
			if(typeof(holder.data('scrolled')) == 'undefined') holder.data('scrolled', 0);
			if(holder.data('scrolled') <= -(itemsCount-2)*relItemWidth) {
				$(this).css('visibility','hidden');
			}
			holder.data('scrolled', holder.data('scrolled')-relItemWidth);
			inner.animate({
				marginLeft: '-=' + relItemWidth + 'px'
			},333);
		});
		//Немедленный заказ
		$('.rel_btn').click(function(){
			var this_btn = $(this);
			$.ajax({
				url: '/catalog/basket_add/' + $(this).attr('proid'),
				success: function(html) {
					$('#basketblock').html(html);
					$('#addBasketBlock').hide();
					$('#addedBasketBlock').show();
					this_btn.replaceWith('В корзине');
				}
			});
		});
	}
	
	
	//Поле ОТ ДО
	$('.from_to_select').change(function(){
		var st = $(this).attr('strange_thing');
		if($(this).val() == 'from') {
			//alert($(this).parent().next(2).find('input').val());
			$('#from_to_from_'+st).css('width','40px').unbind();
			$('#from_to_l_'+st).show();
			$('#from_to_to_'+st).show();
			$(this).css('width','37px');
		} else if($(this).val() == 'equal') {
			$('#from_to_from_'+st).css('width','50px').change(function(){
				$('#from_to_to_'+st).val($(this).val());
			});
			$('#from_to_l_'+st).hide();
			$('#from_to_to_'+st).val($('#from_to_from_'+st).val()).hide();
			$(this).css('width','58px');
		}
	});
	
	
	//Автозаполнение карточки заказа ДЛЯ АДМИНОВ
	$('#autofill').change(function(){
		var data = eval('('+$(this).val()+')');
		$.each(data, function(i, val){
			if (i == 'delivery' || i == 'delivery_to' || i == 'delivery_from')
				return;
			$("#" + i).val(val);
		});
	});
	
	
	
	//Автокомплит
	$("#searchStr").autocomplete("/ajax", {autoFill:true, maxItemsToShow:10,  extraParams:{m:'SearchSuggest'}, onItemSelect: function(e){
		$("#searchStr").val($(e).text());
		$('#search_form').submit();
	}});
	
	//ХАРАКТЕРИСТИКИ-------
	//Сворачивание панели характеристик
    $('#slideControl_types').click(function(){
        if (active_hint) {
            active_hint.fadeOut('fast', function(){
                $('#slidePanel_types').slideToggle("fast");
                $('#slideControl_types').parent().toggleClass('parah_');
            });
        } else {
			$('#slidePanel_types').slideToggle("fast");
            $('#slideControl_types').parent().toggleClass('parah_');
		}
		return false;
    });
	//Полное раскрытие панели характеристик
	$('#hiddenPanel_show').click(function(){
        if (active_hint) {
            active_hint.fadeOut('fast', function(){
                $('#hiddenPanel_types').slideToggle("fast");
                $('#hiddenPanel_show span').toggle();
            });
        } else {
			$('#hiddenPanel_types').slideToggle("fast");
            $('#hiddenPanel_show span').toggle();
		}
		return false;
    });
	//Открытие хинта
	var active_hint;
	$(".typeHintControl").click(function(){
		var hint = $(this).parent().parent().parent().parent().prev();
		if(hint.css('display') == 'block') {
			hint.fadeOut('fast');
			active_hint = false;
		} else {
			if(active_hint) {
				active_hint.fadeOut('fast');
			}
			
			var id = $(this).attr('id').substr(10);
			$.ajax({
				url: "/catalog/type_hint/" + id,
				success: function(html){
					$("#sspText"+id).html(html);
				}
			});

			hint.fadeIn('fast');
			active_hint = hint;
		}
		return false;
	});
	//Закрытие хинта
	$('.pota2>a,.pota3>a').click(function(){
		$(this).parent().parent().parent().fadeOut('fast');
		active_hint = false;
		return false;
	});
	
	//Открытие хинта 2
	$(".typeHintControl2").click(function(){
		var hint = $(this).parent().next().children(0);
		if(hint.css('display') == 'block') {
			hint.fadeOut('fast');
			active_hint = false;
		} else {
			if(active_hint) {
				active_hint.fadeOut('fast');
			}
			var id = $(this).attr('id').substr(10);
			$.ajax({
				url: "/catalog/type_hint/" + id,
				success: function(html){
					$("#sspText"+id).html(html);
				}
			});
			hint.fadeIn('fast');
			active_hint = hint;
		}
		return false;
	});
	//Закрытие хинта 2
	$('.pota2>a,.pota3>a').click(function(){
		$(this).parent().parent().parent().fadeOut('fast');
		active_hint = false;
		return false;
	});
	
	//СЛАЙДЕР-----------
	//Слайдер
	price_slide_l = $('#price_slide_l');
	price_slide_r = $('#price_slide_r');
	price_slide   = $('#price_slide');
	
	//alert(typeof(price_min));
	if(typeof(price_min)=='undefined') {
		price_min = 1;
	}
	if(typeof(price_max)=='undefined') {
		price_max = 10000;
	}
	
	$(price_slide_l).html(price_min);
	$(price_slide_r).html(price_max);
    price_slide.slider({
        min: price_min,
        max: price_max,
        range: true,
        slide: function(e, ui){
    		/*
			if ((price_slide.slider('value', 1) - price_slide.slider('value', 0)) < 45) {
				price_slide.slider('stop');
			}
			*/
			price_slide_l.text(Math.round(price_slide.slider('value', 0)/10)*10);
			price_slide_r.text(Math.round(price_slide.slider('value', 1)/10)*10);
        },
        stop: function(e, ui){
        	$('#price_from').attr('value', Math.round(price_slide.slider('value', 0)/10)*10);
        	$('#price_to').attr('value', Math.round(price_slide.slider('value', 1)/10)*10);
        }
    });
    
    if(typeof(price_min_curr)!='undefined') {
    	price_slide.slider("moveTo", price_min_curr, 0);
	}
	if(typeof(price_max_curr)!='undefined') {
		price_slide.slider("moveTo", price_max_curr, 1);
	}
	
	$('#brandSelect').mousedown(function(){
		$('#bsFrom').val(price_slide.slider('value', 0));
		$('#bsTo').val(price_slide.slider('value', 1));
	});

    
	//Любая цена
	$('#all_prices').click(function(){
		price_slide.slider('moveTo', price_min, 0);
		price_slide.slider('moveTo', price_max, 1);
		return false;
	});
	
	//СРАВНЕНИЕ-----------
	//Добавить в сравнение
	$('.tcat3-5,.tcat3-2').click(function(){
		$('#compare_block').show();
		
		$('#compare_loader').fadeIn('normal');
		
		$.ajax({
			url: $(this).find('a').attr('href'),
			success: function(html) {
				$('#compare_block').html(html);
				$('.bsravt2').click(clear_basket);
				
				$('.bsravh').click(function(){
					$('#slidePanel_compare').slideToggle("fast");
					$(this).toggleClass('bsravh_');
					return false;
				});
			}
		});
		
		$(this).effect("transfer", { to: "#compare_block" }, 400).removeClass('tcat3-2').addClass('tcat3-2_').html('<a href="/catalog/compare.html">В сравнении</a>').unbind();
		return false;
	});
	
	//Очистить сравнение
	$('.bsravt2').click(clear_basket);
	
	//Захлопнуть сравнение
	$('.bsravh').click(function(){
		$('#slidePanel_compare').slideToggle("fast");
		$(this).toggleClass('bsravh_');
		return false;
	});
	
	//Скроллинг в срвнении
	$('.compare_scroll').click(function(){
		var targetOffset = $($(this).attr('href')).offset().top;
		$('html,body').animate({scrollTop: targetOffset}, 800);
		return false;
	});
	 
	//Скрыть отличающиеся в сравнении
	$('.show_diff_types').click(function(){
		//alert($(this).attr('name')+' .srav1');
		//$('.srav1').slideUp();//css('display','none');
		$('.srav1').hide();
		$('.show_diff_types').addClass('srav_act');
		$('.show_all_types').removeClass('srav_act');
		return false;
	});
	
	//Показать все в сравнении
	$('.show_all_types').click(function(){
		//$('.srav1').slideDown(function(){ $(this).css('display','table-row'); });
		$('.srav1').show();
		$('.show_all_types').addClass('srav_act');
		$('.show_diff_types').removeClass('srav_act');
		return false;
	});

	//СТРАНИЧИНГ--------
	load_paging();
	$(".page_holder").draggable({
		axis : 'x',
		delay : 50,
		containment: 'parent',
		start : function(){
			$('#page_larr').css('visibility', 'visible');
			$('#page_rarr').css('visibility', 'visible');
			$(".page_holder div a").bind('click', function(){
				return false;
			});
		},
		stop : function() {
			setTimeout(function() {
				if(parseInt($(".page_holder").css('left')) >= -(parseInt($(".page_containment").css('left')))) {
					$('#page_larr').css('visibility', 'hidden');
				}
				if (parseInt($(".page_holder").css('left')) <= 0) {
					$('#page_rarr').css('visibility', 'hidden');
				}
				$('.page_holder div a').unbind('click');
			}, 1)
		}
	});
	var page_move_handle, page_left_css, page_mouse_state = false;
	$('#page_larr,#page_sub_larr').mousedown(function(){
		page_left_css = parseInt($(".page_holder").css('left'));
		var page_containment_left_css = -(parseInt($(".page_containment").css('left')));
		var page_holder = $(".page_holder");
		var arr = $(this);
		$('#page_rarr').css('visibility', 'visible');
		page_mouse_state = true;
		move_handle = setInterval(function(){
			page_left_css+=2;
			if (page_left_css > page_containment_left_css) {
				clearInterval(move_handle);
				arr.css('visibility', 'hidden');
				return false;
			}
			page_holder.css('left', page_left_css + 'px');
		},10);
	});
	$('#page_rarr,#page_sub_rarr').mousedown(function(){
		page_left_css = parseInt($(".page_holder").css('left'));
		var page_containment_left_css = -(parseInt($(".page_containment").css('left')));
		var page_holder = $(".page_holder");
		var arr = $(this);
		$('#page_larr').css('visibility', 'visible');
		page_mouse_state = true;
		move_handle = setInterval(function(){
			page_left_css-=2;
			if (page_left_css < 0) {
				clearInterval(move_handle);
				arr.css('visibility', 'hidden');
				return false;
			}
			page_holder.css('left', page_left_css + 'px');
		},10);
	});
	$('#page_larr,#page_rarr,#page_sub_larr,#page_sub_rarr').mouseup(function(){
		if(!page_mouse_state) return false;
		clearInterval(move_handle);
		page_mouse_state = false;
	});
	$('#page_larr,#page_rarr,#page_sub_larr,#page_sub_rarr').click(function(){
		return false;
	});
	$('#page_larr,#page_rarr,#page_sub_larr,#page_sub_rarr').mouseout(function(){
		if(!page_mouse_state) return false;
		clearInterval(move_handle);
		page_mouse_state = false;
	});
	//$('#page_larr,#page_rarr').mousemove(function(){page_mouse_state = true;});
	//
	
	
	//Меню
	$('.xmenu3,.xmenu3_').click(function(){
		//$('xmenu4').css('display','none');
		//$($(this).attr('id') + 'p').toggle();
		//alert('123');
		$('.xmenu4').css('display','none');
		$('.xmenu3_').attr('class','xmenu3');
		$('#' + $(this).attr('id') + 'p').toggle();
		$(this).attr('class','xmenu3_');
		
		return false;
	});
	
	
	//Корзинен
	$('.basket_pay_item').click(function(){
		$('.basket_pay_item').removeClass('bpact');
		$(this).addClass('bpact');
		$('.basket_pay_text').html($(this).find('.basket_pay_descr').html());
		payment_type = $(this).attr('id');
	});
	$('#addBasketBlock,#addWhenProduct').mouseover(function(){
		$('#BBHeaderNoExist').css('backgroundColor', '#ff5d1a');
	});
	$('#addBasketBlock,#addWhenProduct').mouseout(function(){
		$('#BBHeaderNoExist').css('backgroundColor', '#c9c3b4');
	});

	$('#addBasketBlock').click(function(){
		$(this).unbind('mouseout');
		$(this).unbind('click');
		$('.add_to_basket').css('backgroundColor', '#ff5d1a');
		$('#BBHeaderLoader').css('visibility', 'visible');
		
		$.ajax({
			url: $(this).attr('datapagesize'),
			success: function(html) {
				$('#basketblock').html(html);
				$('#addBasketBlock').hide();
				$('#addedBasketBlock').show();

				var overlay = $('<div class="overlay_product_added" />').appendTo(document.body);
				overlay.css({
					position: 'fixed',
					left: 0,
					top: 0,
					width: '100%',
					height: '100%',
					'background-color' : 'black',
					'opacity' : 0,
					'z-index' : 100
				});
				var box = $('<div class="box_product_added" />').appendTo(document.body);
				var css_box_shadow = '0px 0px 10px #777';
				box.css({
					position: 'fixed',
					left: '50%',
					'top': '30%',
					width : '360px',
					height: 75,
					'margin-left': '-225px',
					'background-color' : '#f7f7f7',
					'border' : '1px solid #888',
					'box-shadow' : css_box_shadow,
					'-webkit-box-shadow' : css_box_shadow,
					'-moz-box-shadow' : css_box_shadow,
					'border-radius' : '3px',
					'-moz-border-radius' : '3px',
					'font-size' : '16px',
					padding: '30px',
					opacity: 0,
					'z-index' : 101
				});
				var product_name = $('h1[id^="product_"]').contents()[0].data;
				//box.html('<div class="btn_product_added" style="display: block; position: absolute; top: -12px; right: -15px; height: 30px; width: 30px; background: url(\'/images/fancy/fancy_closebox.png\') top left no-repeat; cursor: pointer; z-index: 181;"></div><p style="font-size: 13px; line-height: 1.8em;">Товар &laquo;'+product_name+'&raquo; добавлен в корзину. Вы можете <a href="/catalog/basket.html" style="color: #FE5800; text-decoration: none; border-bottom: 1px dashed #FE5800; font-size: 20px;">оформить&nbsp;заказ</a>&nbsp;или&nbsp;<a href="#" class="btn_product_added" style="color: #FE5800; text-decoration: none; border-bottom: 1px dashed #FE5800; font-size: 20px;">продолжить&nbsp;покупки</a></p>');
				box.html('<div class="btn_product_added" style="display: block; position: absolute; top: -12px; right: -15px; height: 30px; width: 30px; background: url(\'/images/fancy/fancy_closebox.png\') top left no-repeat; cursor: pointer; z-index: 181;"></div><p style="font-size: 16px; line-height: 1.4em;">Товар &laquo;'+product_name+'&raquo; добавлен в корзину. Вы можете <a href="/catalog/basket.html" style="color: #FE5800; text-decoration: none; border-bottom: 1px dashed #FE5800; font-size: 20px;">оформить&nbsp;заказ</a>&nbsp;или&nbsp;<a href="#" class="btn_product_added" style="color: #FE5800; text-decoration: none; border-bottom: 1px dashed #FE5800; font-size: 20px;">продолжить&nbsp;покупки</a></p>');
				overlay.animate({opacity:.3}, 350);
				box.animate({opacity:1}, 250);
				box.find('.btn_product_added').click(function(e){
					e.preventDefault();
					overlay.remove();
					box.remove();
				});
			}
		});
		
		$.ajax({
			url: '/ajax.html',
			data: {'id': $(this).attr('proid'), 'm': 'RelProducts'},
			success: function(html) {
				$('#relBlock').html(html);
				runRels();
			}
		});
	});
	
	$('#addWhenProduct').mousedown(function(){
		$('.when_product').trigger('mousedown');
	}).click(function(){
		$('.when_product').trigger('click');
	});
	
	//Случайный пример для поиска
	$('#searchExample').click(function(){
		$('#searchStr').val($(this).text());
		return false;
	});
	
	if ($('a.miniThumb').length) {
		var img_orig = $('#fullImage img').attr('src');
		var img = $('a.miniThumb[href="'+img_orig+'"]')[0];
		$('#fullImage').empty();
		$('.miniThumb').each(function(){
			var el = $(this).clone().click(function(){return false;});
			el.removeClass('miniThumb').appendTo('#fullImage').attr('rel','gallery-product').css('display','none');
			el.attr('href_thumb', el.attr('href')).attr('href', el.attr('fullhref'));
			el.children('img').attr('src', el.attr('href_thumb')).css({width:'auto',height:'auto'});
		});
		$('#fullImage > a[href_thumb="'+img_orig+'"]').show();
		$('#fullImage > a').fancybox();
		$('a.miniThumb').click(function(event){
			event.preventDefault();
			var link = $('#fullImage > a[href_thumb="'+$(this).attr('href')+'"]');
			if (link.length) {
				$('#fullImage > a').hide();
				link.show();
			}
		});
	}
	
	//В списке товаров
	if($('#whenProduct').length != 0) {
		var when_product_id = 0;
		$('.when_product').mousedown(function(){
			when_product_id = $(this).attr('id').substr(4);
		});
		$('.when_product').fancybox({
			'hideOnContentClick':	false,
			frameHeight			:	335,
			callbackOnStart		: function(){
			
			},
			callbackOnShow		: function(){
				$('#fancy_div .whenProductName').text($('#product_'+when_product_id).text());
				$('#fancy_div .whenProductInputName').focus();
				$('.whenProductCancel,.whenProductTanxCancel').click(function() {
					$('#fancy_close').trigger('click');
					
					$('.whenProductInner').show();
					$('.whenProductLoader,.whenProductTanx').hide();
				});
				$('.whenProductOK').click(function() {
					var data = {
							'm':		'WhenProductAdd',
							'name':		$('#fancy_div .whenProductInputName').val(),
							'phone':	$('#fancy_div .whenProductInputPhone').val(),
							'tillDate':	$('#fancy_div select[name="tillDate"]').val(),
							'email':	$('#fancy_div .whenProductInputEmail').val(),
							'product':	when_product_id
					};
					
					if(data.name == '') {
						alert('Пожалуйста, напишите Ваше имя.');
						$('#fancy_div .whenProductInputName').focus();
						return;
					}
					if(data.phone == '' && data.email == '') {
						alert('Пожалуйста, напишите номер своего телефона или укажите электронную почту.');
						$('#fancy_div .whenProductInputPhone').focus();
						return;
					}
					
					$('.whenProductLoader').show();
					$('.whenProductInner').hide();
					
					$.ajax({
						type:		'POST',
						url:		'/ajax.html',
						data:		data,
						success:	function(result) {
							$('.whenProductLoader').hide();
							if(result != 'ok') {
								$('.whenProductInner').show();
								alert(result);
								return;
							} else {
								$('.whenProductTanx').show();
							}
						}
					});
				});
			},
			callbackOnClose		: function(){
				$('.whenProductInner').show();
				$('.whenProductLoader,.whenProductTanx').hide();
			}
		});
	}
	
	//В товаре
	if($('#whenProductI').length != 0) {
		var when_product_id = 0;
		$('.when_product').mousedown(function(){
			when_product_id = $(this).attr('id').substr(4);
		});
		$('.when_product').fancybox({
			'hideOnContentClick':	false,
			frameHeight			:	335,
			callbackOnStart		: function(){
			
			},
			callbackOnShow		: function(){
				$('#fancy_div .whenProductName').text($('#product_'+when_product_id).text());
				$('#fancy_div .whenProductInputName').focus();
				$('.whenProductCancel,.whenProductTanxCancel').click(function() {
					$('#fancy_close').trigger('click');
					
					$('.whenProductInner').show();
					$('.whenProductLoader,.whenProductTanx').hide();
				});
				$('.whenProductOK').click(function() {
					var data = {
							'm':		'WhenProductAdd',
							'name':		$('#fancy_div .whenProductInputName').val(),
							'phone':	$('#fancy_div .whenProductInputPhone').val(),
							'tillDate':	$('#fancy_div select[name="tillDate"]').val(),
							'email':	$('#fancy_div .whenProductInputEmail').val(),
							'product':	when_product_id
					};
					
					if(data.name == '') {
						alert('Пожалуйста, напишите Ваше имя.');
						$('#fancy_div .whenProductInputName').focus();
						return;
					}
					if(data.phone == '' && data.email == '') {
						alert('Пожалуйста, напишите номер своего телефона или укажите электронную почту.');
						$('#fancy_div .whenProductInputPhone').focus();
						return;
					}
					
					$('.whenProductLoader').show();
					$('.whenProductInner').hide();
					
					$.ajax({
						type:		'POST',
						url:		'/ajax.html',
						data:		data,
						success:	function(result) {
							$('.whenProductLoader').hide();
							if(result != 'ok') {
								$('.whenProductInner').show();
								alert(result);
								return;
							} else {
								$('.whenProductTanx').show();
							}
						}
					});
				});
			},
			callbackOnClose		: function(){
				$('.whenProductInner').show();
				$('.whenProductLoader,.whenProductTanx').hide();
			}
		});
	}

	if ($.datepicker) {
		$.datepicker.setDefaults({
			dayNames: [ 'Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Гейдень', 'Пятница', 'Суббота' ],
			dayNamesMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб' ],
			dayNamesShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб' ],
			monthNames: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь' ],
			monthNamesShort: [ 'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек' ],
			prevText: 'Назад',
			nextText: 'Вперёд',
			firstDay: 1
		});
	}
	
	
	//Фокус на поиск
	//$('#searchStr').focus();
});


//РЕСАЙЗ ОКНА
$(window).resize(function(){
	load_paging();
});


/**
 * Очистка корзины
 * @return
 */
function clear_basket() {
	$('#compare_loader').fadeIn('normal');
	$.ajax({
		url: '/catalog/compare_clean',
		success: function(html) {
			$('#slidePanel_compare').fadeOut("normal", function(){
				//$('#slidePanel_compare').remove();
				$('#compare_block').html(html);
				$('.tcat3-5,.tcat3-2').fadeIn('fast');
			});	
			//$('#compare_count').html('');
			//$('.bsravh a').css('background', 'none');
		}
	});
	
	return false;
}


/**
 * Пересчет размеров блоков для страничинга
 */
function load_paging() {
	var paging_holder_width = 0;
	var paging_scroller_width = $(".page_scroller").width();
	var paging_active = 0;
	var paging_active_left = 0;
	$('.page_holder:first div').each(function(){
		if ($(this).children().get(0).tagName == 'SPAN') {
			paging_active = paging_holder_width + 34;
		}
		paging_holder_width += 34;
	});
	
	if(paging_holder_width <= paging_scroller_width) {
		$('#page_larr').css('visibility', 'hidden');
		$('#page_rarr').css('visibility', 'hidden');
		$('.page_containment').css('width', paging_holder_width);
		return false;
	} else {
		$('#page_larr').css('visibility', 'visible');
		$('#page_rarr').css('visibility', 'visible');
	}
	
	if (paging_active != 0) {
		paging_active_left = paging_holder_width - (paging_scroller_width / 2) - paging_active + 17;
		if (paging_active_left > paging_holder_width - paging_scroller_width) {
			paging_active_left = paging_holder_width - paging_scroller_width;
			$('#page_larr').css('visibility', 'hidden');
		}
		if (paging_active_left < 0) {
			paging_active_left = 0;
			$('#page_rarr').css('visibility', 'hidden');
		}
	}
	else {
		paging_active_left = paging_holder_width - paging_scroller_width;
	}
	$(".page_holder").css({
		'width': paging_holder_width + 'px',
		'left': paging_active_left + 'px'
	});
	$(".page_containment").css({
		'width': (paging_holder_width * 2 - paging_scroller_width) + 'px',
		'left': (-(paging_holder_width - paging_scroller_width)) + 'px'
	});
	
	return true;
}

/* галерея в карточке товара */
$(function(){
	if (!$('#hcImg').length || $('#hcNoGallery').length)
		return;
    var mkScroller = function(obj){
        var li_width = 67;
        var items_width = obj.find('ul.hcList > li').length * li_width - 5,
            cont_width = obj.find('.hcListOuter').width();
        obj.removeClass('hcNoControls');
        if (items_width < cont_width) {
            obj.addClass('hcNoControls');
            obj.find('ul.hcList').css('left', (cont_width-items_width)/2);
        } else {
            obj.find('ul.hcList').css('left', 0);
            obj.unbind('mousewheel');
            obj.find('.hcBtn').unbind('click');
            obj.bind('mousewheel', function(event,delta){
                event.preventDefault();
                obj.find('.hcBtn.'+(delta>0?'hcLeft':'hcRight')).trigger('click');
            });
            obj.find('.hcBtn').bind('click', function(event){
                event.preventDefault();
                var list = obj.find('ul.hcList')[0],
                    bRight = $(this).hasClass('hcRight');
				var pos = parseInt($(list).css('left'));
				var step = bRight ? -67 : 67;
				var newPos = Math.min(0, Math.max(0-($(list).children('li').length)*67+$(list).parent().width()+5, pos + step));
				$(list).css('left', newPos);
				return;
                $(list).find('li:'+(bRight?'first':'last'))[bRight?'appendTo':'prependTo'](list);
            });
        }
    };

    $('#hcImg ul.hcList > li > a').each(function(i){
        $(this).attr('rel', '#hc400-'+i);
		var html = '<div class="hc400 hcHidden" id="hc400-'+i+'"><a href="'+$(this).attr('href')+'"><img src="'+$(this).attr('img400')+'" alt="" /><div class="hcMagnifier"></div></a></div>';
		var el = $(this);
		$(html).appendTo($('#hcImg .hcMedium')).click(function(event){
			event.preventDefault();
			el.trigger('click');
		});
    });

    $('#hcImg ul.hcList > li > a').hover(
        function(){
			var selector = $(this).attr('rel');
			$('#hcImg .hcMedium .hc400').addClass('hcHidden');
			$(selector).removeClass('hcHidden');
			$('#hcImg ul.hcList > li').removeClass('active');
			$(this).parent().addClass('active');
		},
		function(){
		}
    );

	$('#hcFancy').bind('positioning', function(event,image){
		$('#hcFancy, #hcFancyShadow').css({display:'block', visibility:'visible'});
		$('#hcFancy').css({left:0,top:0,right:0,bottom:0});

		var eImgArea = $('#hcFancy .hcImgArea');
		var mw = $('#hcFancy').attr('mw'),
			mh = $('#hcFancy').attr('mh');
		if (eImgArea.width() > mw) {
			var hMargin = (eImgArea.width()-mw)/2;
			$('#hcFancy').css({left:hMargin,right:hMargin});
		}
		if (eImgArea.height() > mh) {
			var vMargin = (eImgArea.height()-mh)/2;
			$('#hcFancy').css({top:vMargin,bottom:vMargin});
		}
		$('#hcSize').css({width:eImgArea.width(),height:eImgArea.height()});

		if (image) {
			$('#hcFancy .hcImgArea img').replaceWith(image);
		}

		var eImg = $('#hcFancy .hcImgArea img');
		var bw = eImg.attr('width-orig'),
			bh = eImg.attr('height-orig');
		if (bw > eImgArea.width() || bh > eImgArea.height()) {
			var hFactor = eImgArea.width()/bw,
				vFactor = eImgArea.height()/bh;
			var factor = Math.min(hFactor, vFactor);
			eImg.css({width:parseInt(bw*factor),height:parseInt(bh*factor)});
		}

		mkScroller($('#hcFancy .hcPreviews'));
		$('#hcFancy > .hcBtn').css('top', ($('#hcFancy').height()-102-42)/2);
	});

    $('#hcFancy').bind('set-img', function(event,src){
        var preloader = new Image;
        preloader.onload = function(){
            var eImg = $('<img src="'+preloader.src+'" width="'+preloader.width+'" height="'+preloader.height+'" width-orig="'+preloader.width+'" height-orig="'+preloader.height+'" alt="" />');
            $('#hcFancy').trigger('positioning', eImg);
        };
        preloader.src = src;
    });

    $('#hcImg .hcMain a').click(function(event){
        event.preventDefault();
    	if (!$('#hcFancy ul.hcList a[href='+$(this).attr('href')+']').trigger('click').length) {
			$('#hcFancy').trigger('set-img', $('#hcImg .hcMain a').attr('href'));
		}
    });
    $('#hcImg ul.hcList a').click(function(event){
        event.preventDefault();
        $('#hcFancy ul.hcList a[href='+$(this).attr('href')+']').trigger('click');
    });

    $('#hcFancy').appendTo(document.body);
    $('#hcFancyShadow').appendTo(document.body);

    $('#hcFancy .hcBtnClose').click(function(event){
        event.preventDefault();
        $('#hcFancy, #hcFancyShadow').hide();
    });
    $('#hcFancyShadow').click(function(event){
    	event.preventDefault();
    	$('.hcBtnClose').trigger('click');
    });
    $('#hcFancy > .hcBtn').click(function(event){
        event.preventDefault();
        var el = $('#hcFancy ul.hcList > li.active')[$(this).hasClass('hcRight')?'next':'prev']('li').find('a');
        if (!el.length) {
            el = $('#hcFancy ul.hcList > li:'+($(this).hasClass('hcRight')?'first':'last')+' a');
        }
        el.trigger('click');
    });

    $('#hcFancy ul.hcList a').click(function(event){
        event.preventDefault();
        $('#hcFancy ul.hcList > li').removeClass('active');
        $(this).parent().addClass('active');
        $('#hcFancy').trigger('set-img', $(this).attr('href'));
    });
    $(window).bind('resize', function(){
        $('#hcFancy:visible').trigger('positioning');
    });

    mkScroller($('#hcImg .hcPreviews'));

    /* next prev */
    $(window).keyup(function(event){
        var btn = null;
        if (event.ctrlKey && event.originalEvent.keyCode == 37) {
            btn = $('#hcFancy:visible > .hcBtn.hcLeft');
        } else if (event.ctrlKey && event.originalEvent.keyCode == 39) {
            btn = $('#hcFancy:visible > .hcBtn.hcRight');
        } else if (event.originalEvent.keyCode == 27) {
            btn = $('#hcFancy:visible > .hcBtnClose');
        }
        if (btn) {
            event.preventDefault();
            btn.trigger('click');
        }
    });
});

/* markdown */
$(function(){
    $('.hc-markdown .hc-mini-button').click(function(event){
        $.ajax({
            url: '/catalog/basket_add/'+$(this).attr('product_id'),
            success: function(html) {
                $('#basketblock').html(html);
                var product_name = $('.hc-markdown .hc-mini-button').attr('product_name');
                $('.hc-markdown .hc-mini-button').remove();
                $('.hc-markdown').append('<div class="hc-inbasket"><a href="/catalog/basket.html">В корзине</a></div>');

                var overlay = $('<div class="overlay_product_added" />').appendTo(document.body);
                overlay.css({
                    position: 'fixed',
                    left: 0,
                    top: 0,
                    width: '100%',
                    height: '100%',
                    'background-color' : 'black',
                    'opacity' : 0,
                    'z-index' : 100
                });
                var box = $('<div class="box_product_added" />').appendTo(document.body);
                var css_box_shadow = '0px 0px 10px #777';
                box.css({
                    position: 'fixed',
                    left: '50%',
                    'top': '30%',
                    width : '360px',
                    height: 75,
                    'margin-left': '-225px',
                    'background-color' : '#f7f7f7',
                    'border' : '1px solid #888',
                    'box-shadow' : css_box_shadow,
                    '-webkit-box-shadow' : css_box_shadow,
                    '-moz-box-shadow' : css_box_shadow,
                    'border-radius' : '3px',
                    '-moz-border-radius' : '3px',
                    'font-size' : '16px',
                    padding: '30px',
                    opacity: 0,
                    'z-index' : 101
                });
                box.html('<div class="btn_product_added" style="display: block; position: absolute; top: -12px; right: -15px; height: 30px; width: 30px; background: url(\'/images/fancy/fancy_closebox.png\') top left no-repeat; cursor: pointer; z-index: 181;"></div><p style="font-size: 16px; line-height: 1.4em;">Товар &laquo;'+product_name+'&raquo; добавлен в корзину. Вы можете <a href="/catalog/basket.html" style="color: #FE5800; text-decoration: none; border-bottom: 1px dashed #FE5800; font-size: 20px;">оформить&nbsp;заказ</a>&nbsp;или&nbsp;<a href="#" class="btn_product_added" style="color: #FE5800; text-decoration: none; border-bottom: 1px dashed #FE5800; font-size: 20px;">продолжить&nbsp;покупки</a></p>');
                overlay.animate({opacity:.3}, 350);
                box.animate({opacity:1}, 250);
                box.find('.btn_product_added').click(function(e){
                    e.preventDefault();
                    overlay.remove();
                    box.remove();
                });
            }
        });
    });
});

