/**
 * @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(){
		$('#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);
			}
		});
		
		$(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');
		$('.show_diff_types').addClass('srav_act');
		$('.show_all_types').removeClass('srav_act');
		return false;
	});
	
	//Показать все в сравнении
	$('.show_all_types').click(function(){
		$('.srav1').slideDown();
		$('.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();
			}
		});
		
		$.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;
	});
	
	
	
	$('.miniThumb').click(function(){
		if($(this).attr('fullhref') != '') {
			$('#fullImage').html('<a style="position: relative; display:block; height:'+$(this).attr('fullh')+'px;" href="'+$(this).attr('fullhref')+'" target="_blank" class="fancyImage"><img style="position: absolute; top: 0pt; left: 0pt; z-index: 1;" src="'+$(this).attr('href')+'" alt=""/><img height="16" width="16" style="position: absolute; z-index: 2; top: 30px; left: 360px;" alt="Увеличить" src="/images/icons/magnifier.png"/></a>');
			$('.fancyImage').fancybox({
				'zoomOpacity'			: true,
				'zoomSpeedIn'			: 500,
				'zoomSpeedOut'			: 300,
				'hideOnContentClick'	: true
			});
		} else {
			$('#fullImage').html('<img src="'+$(this).attr('href')+'" />');
		}
		return false;
	});
	
	//В списке товаров
	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(),
							'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(),
							'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();
			}
		});
	}
	
});


//РЕСАЙЗ ОКНА
$(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;
}
