

var fontStep = 0;
// Изменение размера шрифта
function setFontSize(id, plus){
	if(document.getElementById(id) !== null && plus){
		var teststep = 0;
		eval('teststep = fontStep '+plus+' 1');
		if (teststep >= 0 && teststep <= 2) {
			var elem = $( '#'+id );
			eval("elem.css( 'font-size', parseInt( elem.css( 'font-size' ) ) "+plus+" 2 + 'px' )");
			eval('fontStep'+plus+''+plus);
		}
	}
}

function submitForm(form_id) {
	var form = document.getElementById(form_id);
	if(form !== null) form.submit();
}

/* Показать возможные способы оплаты */
function showPayment() {
	if (arguments.length) for (i=0, j=0; i<sdInputs.length; i++) {
		if (sdInputs[i].id == "so"+arguments[j]) {
			document.getElementById("so"+arguments[j]+"_block").style.display = "block";
			if (j==0) document.getElementById("so"+arguments[j]).checked = true;
			else document.getElementById("so"+arguments[j]).checked = false;
			j++;
		} else sdInputs[i].parentNode.style.display = "none";
	} else for (i=0; i<sdInputs.length; i++) {
		sdInputs[i].parentNode.style.display = 'none';
		if (sdInputs[i].checked) sdInputs[i].checked = false;
	}

}


/*--------------------------------------------------------------------------------------*/

$( document ).ready( function() {

	/* Определение ишака */
	var IE = false;
	if (!jQuery.support.opacity) { IE = true; }

	// Фото в списках товаров ---------------------------------------
	(function(){

		var photos = $( 'div.shop_catalog_container .catalog_foto a' );
		var defaultOpacity = photos.css('opacity');
		
		if ( IE ) {
			photos.has('img').css({'opacity': 1});
		} else {
			photos.children('img').css({'opacity': 1})
		}
	
		$( 'div.shop_catalog_container .catalog_container a' ).add( '.razd_descr h3 a' ).bind( 'mouseenter', function(){
			var thisPhotoblock = $( this ).closest('div.catalog_container').find('.catalog_foto a');
			thisPhotoblock.addClass( 'hovered' );
			/*if ( IE && thisPhotoblock.has('img').length ) {
				thisPhotoblock = thisPhotoblock.find('img');
			}; thisPhotoblock.stop().animate({'opacity': 1}, 180);*/
			$( this ).closest('div.razd_descr').find('.razd_descr_foto a').addClass( 'hovered' );
		});
		
		$( 'div.shop_catalog_container .catalog_container a' ).add( '.razd_descr h3 a' ).bind( 'mouseleave', function(){
			var thisPhotoblock = $( this ).closest('div.catalog_container').find('.catalog_foto a');
			thisPhotoblock.removeClass( 'hovered' );
			/*if ( IE && thisPhotoblock.has('img').length ) {
				thisPhotoblock = thisPhotoblock.find('img');
			}; thisPhotoblock.stop().animate({'opacity': defaultOpacity}, 180);*/
			$( this ).closest('div.razd_descr').find('.razd_descr_foto a').removeClass( 'hovered' );
		});
		
	})();


	/* Всплывающие превьюхи в списках каталога и магазина ----------------------------- */

	$( '#shop .catalog_foto a > img' ).add( '#shop .razd_descr_foto a > img' ).bind({
		'mouseenter': function(e) {

			$( '#popup_list_image' ).remove();
			$this = $( this );

			$( 'body' ).eq(0).append( 
				$( document.createElement( 'DIV' ) ).attr( 'id', 'popup_list_image' ).append( 
					$( document.createElement( 'IMG' ) ).attr( 'src', $this.attr( 'src' ) ) 
				) 
			);

			var popupImage = $( '#popup_list_image' );
			var thisParent = $this.parent('a').parent();

			popupImage.css({ 
				'left': ( thisParent.offset().left - ( ( popupImage.outerWidth() - thisParent.outerWidth() ) / 2 ) )+'px',
				'top': ( ( thisParent.offset().top - popupImage.outerHeight() ) + 1 )+'px'
			});
		},
		'mouseleave': function(e) {
			$( '#popup_list_image' ).remove();
		}
	});

	/* END OF Всплывающие превьюхи в списках каталога и магазина ---------------------- */


	/* Выбор валюты (переназначение) */
	if ( $( 'body' ).eq(0).data( 'graphSelects' ) ) {
		var currencySelect = $( '#select-currency' );
		if ( currencySelect.length ) {
			var input = currencySelect.children( "input[type='hidden']" ).eq(0);
			input.change( function(){
				setCookie('currency', $( this ).val());
				window.location = window.location.href;
			});
		}
	};
	
	/* Выбор способа доставки (переназначение для графических радиокнопок) */
	if ( $( 'body' ).eq(0).data( 'graphRadios' ) ) {
		var dostavka = $( '#dostavka .graph-radio' );
		if ( dostavka.length ) {
			var oplata = $( '#oplata .order_radioblock' )
			dostavka.map( function( i, el ){
				var $this = $( el )
				var labels = $this.siblings( 'label' ).filter( function( i ){
					if ( $(this).attr('for') == $this.attr('id') ) { return true; }
					return false;
				});
				return [ el, labels.get()[0] ];
			}).bind( 'click', function() {
				$this = $( this );
				var onclick = ''+$( this ).data( 'onclick' );
				onclick = onclick.match(/([0-9]+)/ig);
				$( '#oplata .order_radioblock' ).css({ 'display': 'none' });
				if ( onclick.length ) {
					for ( i=0; i<onclick.length; i++ ) {
						$( '#oplata #so'+onclick[i]+'_block' ).css({ 'display': 'block' })
					}; $( '#oplata #so'+onclick[0] ).checkGraphicRadio();
				}
			});
		}
	};

	// Показать фон для всплывающих блоков
	var showGlass = function() {
		$('#glass').remove();
		if ( IE ) { IEfixGlobal_hideSelects(); }
		// Динамическое добавление блока-фона для всплывающих окон
		$( 'body' ).eq(0).append( 
			$( document.createElement('div') ).attr('id', 'glass').css({
				display : 'block' 
			})
		); return resizeGlass();
	};
	
	// Изменить размеры блока #glass
	var resizeGlass = function() {
		var doc = $( document );
		return $('#glass').css({
			width: 'auto',
			height: 'auto'
		}).css({
			width : ( doc.width() - (( IE && doc.height() > $( window ).height() )? 20: 0) )+'px', 
			height : doc.height()+'px'
		});
	}
	
	// Скрыть фон для всплывающих блоков
	var hideGlass = function() {
		$( '#glass' ).remove();
		if ( IE ) IEfixGlobal_showSelects();
	};

	// Изменить размеры блока #glass при изменении размеров окна
	$( window ).bind( 'resize', resizeGlass );


	/*------------ Фотогалерея --------------*/
	( function() {

		var previewOpacity = 0.4;

		/* Полупрозрачность превьюшек фотогалереи */
		$( '.fotolist a.preview img' ).bind({
			'mouseenter': function(){
				$this = $( this );
				if ( !$this.hasClass( 'active' ) ) {
					$this.stop().animate({'opacity':1}, 300);
				}
			},
			'mouseleave': function(){
				$this = $( this );
				if ( !$this.hasClass( 'active' ) ) {
					$this.stop().animate({'opacity':previewOpacity}, 300);
				}
			}
		});

		var popupGallery = $( '#popup_gallery' );

		if ( popupGallery.length ) {

			// Перенос блока фотогалереи в конец документа
			popupGallery.css({ 'display': 'none' }).detach().appendTo( $('body').eq(0) );

			// Создание фона для предгагрузчика
			var preloaderBackground = $( document.createElement('DIV') ).attr({
				'id': 'preload_fon'
			}).append( $( document.createElement('SPAN') ) );

			// Создание самого прелодера
			var preloader = $( document.createElement('IMG') );
			
			// После загрузки прелодера - старт
			preloader.one( 'load', function() {

				var canvas = $( '#gallery_canvas' );
				preloaderBackground.appendTo( canvas );
				preloader.appendTo( canvas );
				
				if ( !$( '#popup_imagelist' ).length ) { $( '#popup_image' ).css( 'margin-left', '0px' ); }

				var bigImage = $( 'img#p_image' );
				var newImage = $( document.createElement('IMG') );
	
				// Отображение и позиционирование всплывающего блока галереи
				var galleryPos = function() {
					var win = $( window );
					popupGallery.css({
						'margin': ((win.height()/2)-(popupGallery.outerHeight()/2))+'px 0 0 '+((win.width()/2)-(popupGallery.outerWidth()/2))+'px'
					});
				};

				// Скрыть галерею
				var hideGallery = function() {
					hideGlass();
					popupGallery.css({
						'display': 'none'
					});
				};

				// Перепозиционирование блока галереи при ресайзе окна
				$( window ).bind( 'resize', galleryPos );

				// Отобразить основное изображение после первой загрузки
				bigImage.one( 'load', function() {
					$( this ).css({ 'display': 'block' });
				});

				// Действие после загрузки основного изображения
				bigImage.bind( 'load', function() {
					bigImage.parent().parent().css({
						'width': bigImage.width()+'px',
						'height': bigImage.height()+'px'
					});
					galleryPos();
					preloader.css({ 'display': 'none' });
					preloaderBackground.css({ 'display': 'none' });
				});

				//------------ Показать галерею ------------//
				var showGallery = function( src ) {
					// Отменить предыдущее ожидание загрузки
					newImage.unbind( 'load' );
					// Если блок фотогалереи скрыт
					if ( popupGallery.is( ':hidden' ) ) {
						// Скрывать галерею по клику на #glass
						showGlass().one( 'click', function(){ 
							hideGallery();
						});
						popupGallery.css({
							'display': 'block'
						}); galleryPos();
					};
					// Установка активной превьюшки
					popupGallery.find( 'a.preview' ).each( function( i, elem ){
						elem = $( elem );
						if ( elem.data( 'image' ) == src ) { elem.children( 'img' ).addClass( 'active' ).css({'opacity':1}); } 
						else { elem.children( 'img' ).removeClass( 'active' ).css({'opacity':previewOpacity}); }
					});
					// Показать фон предзагрузчика
					preloaderBackground.css({
						'display': 'block',
						'position': 'absolute',
						'left': '0px',
						'top': '0px',
						'width': canvas.outerWidth()+'px',
						'height': canvas.outerHeight()+'px'
					});
					// Показать сам предзагрузчик
					preloader.appendTo( canvas ).css({
						'display': 'block',
						'position': 'absolute',
						'left': ((canvas.outerWidth()/2)-(preloader.width()/2))+'px',
						'top': ((canvas.outerHeight()/2)-(preloader.height()/2))+'px'
					});
					// Загрузка изображения
					newImage = $( document.createElement('IMG') );
					newImage.one( 'load', function(){
						bigImage.attr({ 'src': newImage.get()[0].src });
					}); 
					newImage.attr({
						'src': src
					});
				};
				//--------- END OF Показать галерею --------//
				
				// Замена ссылок на фотографии
				$( '#popup_gallery a.preview' ).add( '#fotoblock a' ).each( function( i, obj ) {
					obj = $( obj );
					var href = obj.attr('href');
					obj.attr({ 'href': '#' }).data( 'image', href );
					obj.bind( 'click', { src: href }, function( e ){
						showGallery( e.data.src );
						return false;
					});
				});
				
				// Закрыть галерею по клику на крестике
				$( '#popup_gallery img.close_gallery' ).eq(0).bind( 'click', hideGallery );

			});

			// Загрузка прелодера
			preloader.attr({
				'id': 'preload_image',
				'src': '../templates/w_shop/images/load.gif'
			});
		}

	})();
	/*--------// END OF Фотогалерея ---------*/


	/* Открыть/закрыть корзину в колонке */
	var bindShowBasket = function(){
		$( 'a#colume-basket-list' ).bind( 'click', function(){
			var $this = $( this );
			$this.trigger( 'blur' );
			var list = $( '#bList' );
			if ( list.hasClass( 'opened' ) ) {
				$this.removeClass( 'opened' );
				list.removeClass( 'opened' ).animate({height: 1+'px'}, 200);
			} else {
				var inner_height = 0;
				list.children( 'div.item' ).each( function(i,el){ inner_height += $(el).outerHeight(true) } );
				$this.addClass( 'opened' );
				list.addClass( 'opened' ).animate({height: inner_height+'px'}, 300);
			}; return false;
		});
	}; bindShowBasket();
	

	/* Проверка состояния корзины ( открыта/закрыта ) при загрузке страницы */
	if ( $( '#bList' ).hasClass( 'mustBeOpened' ) ) {
		$( 'a#colume-basket-list' ).removeClass( 'mustBeOpened' ).trigger( 'click' );
	};
	

	/* Поведение меню в колонке */
	$( '#shop_menu a.shop_parent' ).bind({
		'click': function(){
			$this = $( this );
			$this.trigger( 'blur' );
			var submenu = $this.next( 'ul' );
			if ( submenu.length ) {
				var inner_height = 0;
				submenu.children( 'li' ).each( function(i,el){ inner_height += $(el).outerHeight(true) } );
				if ( submenu.hasClass( 'opened' ) ) {
					submenu.css({'overflow':'hidden','height':inner_height+'px'}).removeClass( 'opened' ).animate({height: 1+'px'}, 150, function(){
						$this.parent( 'li' ).removeClass( 'active' );
					});
				} else {
					$this.parent( 'li' ).addClass( 'active' );
					submenu.css({'height':'1px'}).addClass( 'opened' ).animate({'height':inner_height+'px'}, 250);
				}; return false;
			}
		}
	});
	

	/* Наведение на пункты подменю */
	$( '#shop_menu ul.shop_submenu a' ).bind( 'mouseenter', function(){
		$( this ).parent( 'li' ).addClass( 'active' );
	});
	$( '#shop_menu ul.shop_submenu a' ).bind( 'mouseleave', function(){
		$( this ).parent( 'li' ).removeClass( 'active' );
	});


	/* Всплывающие подсказки в корзине */
	var checkBasketBubbles = function(){
		var bubble_blocks = $('.bubble_params');
		if ( bubble_blocks.length ) {
			$('.bubble_params a.bubble_link').bind('mouseenter', function(e){
				var thisLink = $(this);
				var bubble = thisLink.next('div.bubble').detach().appendTo('body');
				bubble.css({ left:(parseInt(e.pageX)+10)+'px', top:(parseInt(e.pageY)+10)+'px', position:'absolute', display:'block' });
				thisLink.bind('mousemove', function(e){
					bubble.css({ left:(parseInt(e.pageX)+10)+'px', top:(parseInt(e.pageY)+10)+'px' });
				});
				thisLink.one('mouseleave', function(e){
					bubble.hide().css({ left:'auto', top:'auto' }).detach().insertAfter(thisLink);
					thisLink.unbind('mousemove');
				});
			});
		}
	}; checkBasketBubbles();



	/* Добавление в корзину и удаление из корзины через Ajax */
	(function(){

		// Подготовка предзагрузчика
		var preloader = document.createElement('IMG');
		preloader.src = '../templates/w_shop/images/load.gif';

		// Извлечение параметров pid, rid и bl и т.п. ТЕКУЩЕЙ страницы
		var templateId = document.URL.match( /(?:&|\?)bl=(\d+)/i )
	 	templateId = (templateId !== null)? templateId[1]: 0;
		var pageId = document.URL.match( /(?:&|\?)pid=(\d+)/i );
		pageId = (pageId !== null)? pageId[1]: 0;
		var razdId = document.URL.match( /(?:&|\?)rid=(\d+)/i );
		razdId = (razdId !== null)? razdId[1]: 0;
		var viewId = document.URL.match( /(?:&|\?)view=(\d+)/i );
		viewId = (viewId !== null)? viewId[1]: 0;

		var getlanguage = document.URL.match( /\/([a-z]{1,3})\/[^\/]*?$/i );
		getlanguage = (getlanguage !== null)? getlanguage[1]: '';

		// Обновление содержимого корзины
		var updateBasketHTML = function( newHTML ) {
			newHTML = $( newHTML );
			var list = $( '#bList' );
			// Проверяем, открыта ли корзина
			var opened = list.hasClass( 'opened' );
			// Если была открыта, добавляем классы
			if ( opened ) {
				newHTML.find( 'a#colume-basket-list' ).eq(0).addClass( 'opened' );
				newHTML.find( '#bList' ).eq(0).addClass( 'opened' );
				newHTML.find( '#bList' ).eq(0).css( 'height', ($( '#bList' ).outerHeight()+'px') )
			}
			// Заменяем содержимое корзины
			$( 'div#basket div.basket_text' ).eq(0).replaceWith( newHTML );
			// Повторная привязка события 'click' для открытия корзины
			bindShowBasket();
			checkBasketBubbles();
		};
		
		// Обновление кол-ва товаров в маленькой ссылке на корзину
		var updateSmallBasket = function( newHTML ) {
			newHTML = $( newHTML );
			var newCount = newHTML.find( 'a#colume-basket-list span span' );
			if ( newCount.length ) {
				newCount = newCount.text();
			}; $( '#small_basket #small_goods_count span' ).text( newCount );
		};

		// Подогнать высоту корзины под высоту ее элементов
		var updateBasketHeight = function() {
			var list = $( '#bList' );
			var inner_height = 0;
			list.children( 'div.item' ).each( function(i,el){ inner_height += $(el).outerHeight(true) } );
			if ( list.hasClass( 'opened' ) ) {
				list.animate({height: inner_height+'px'}, 100);
			} else {
				$( 'a#colume-basket-list' ).trigger( 'click' );
			};
		};

		// Корректировка позиции бабла при изменении размеров окна
		var bubbleOkOnWindowResize = function(){
			var bubble = $('#bubbleOk');
			if ( bubble.length ) {
				bubble.css({
					left: (($(window).width()+$(window).scrollLeft())-parseInt(bubble.outerWidth()))+'px',
					top: (($(window).height()+$(window).scrollTop())-parseInt(bubble.outerHeight()))+'px'
				});
			}
		};

		// Обработка прокрутки окна с баблом
		$( window ).bind({
			'scroll': bubbleOkOnWindowResize,
			'resize': bubbleOkOnWindowResize
		});


		// Bubble добавления в корзину для нудных
		var bubbleOk = function(){

			$('#bubbleOk').remove();

			// Создание бабла
			$( document.createElement('DIV') )
						.attr( 'id', 'bubbleOk' )
						.appendTo( $('body').eq(0) )
						.append( $(document.createElement('DIV')).text('Товар добавлен в корзину') );

			var bubble = $('#bubbleOk');

			// установка начальных стилей бабла
			bubble.css({ 
				height: '1px',
				left: (($(window).width()+$(window).scrollLeft())-parseInt(bubble.outerWidth()))+'px', 
				top: (($(window).height()+$(window).scrollTop())-parseInt(bubble.outerHeight()))+'px',
				opacity: 0
			}).bind( 'click', function(e){ // Убрать бабл по щелчку
				$(this).stop().remove();
			});

			var bubbleInnerHeight = parseInt(bubble.children('div').outerHeight(true));
			var bubbleOuterHeight = parseInt(bubble.children('div').outerHeight(true))+parseInt(bubble.css('padding-top'))+parseInt(bubble.css('padding-bottom'));

			// Анимированное появление бабла
			bubble.animate(
				{ opacity: 1, 
				  height: bubbleInnerHeight+'px' 
				}, {
					duration: 1500,
					complete: function(){
						setTimeout( function(){
							bubble.animate({opacity:0}, 500, function(){
								bubble.remove();
							});
						}, 2500 );
					},
					step: function(){
						// Подгон позиции top во время анимации
						bubble.css( 'top', ((($(window).height()+$(window).scrollTop())-parseInt(bubble.outerHeight()))+'px') );
					}
				}
			);
		};

		// Просчет позиции X
		var posLeft = function( object ) {
			return parseInt( ( ($(window).width()/2) + $(window).scrollLeft() ) - ( object.outerWidth()/2 ) );
		};
		// Просчет позиции Y
		var posTop = function( object ) {
			return parseInt( ( ($(window).height()/2) + $(window).scrollTop() ) - ( object.outerHeight()/2 ) );
		};

		var updDialogPosition = function(){
			var p = $('.system_popup').eq(0);
			if ( p.length ) {
				p.css({
					left: posLeft( p )+'px',
					top: posTop( p )+'px'
				});
			}
		}; // Пересчет координат диалога при прокрутке страницы 
		   // и изменении размеров окна
		$( window ).bind({
			'scroll': updDialogPosition,
			'resize': function(){
				updDialogPosition();
			}
		});

		// Функция скрытия всплывающих диалогов
		var hidePopup = function(){ 
			$( '#shop_dialog' ).remove(); 
		};

		// Спрятать всё всплывающее
		var hideAll = function(){ 
			$( '#ajaxPreloader' ).remove(); 
			$( '#shop_dialog' ).remove(); 
			hideGlass();
		};

		// Функция отображения всплывающего диалога
		var showPopup = function( htmlData ){

			// Динамическое добавление к документу всплывающего диалога
			$( 'body' ).eq(0).append(
				$( document.createElement('div') ).attr('id', 'shop_dialog')
			);

			var dialog = $( '#shop_dialog' ).addClass( 'system_popup' );

			// Вставка содержимого окна
			dialog.html( htmlData ).css({
				display: 'block',
				left: posLeft( dialog )+'px',
				top: posTop( dialog )+'px'
			});
			
			// Замена выпадающих списков и радиокнопок на графику
			//dialog.makeGraphicRadios();
			//dialog.makeGraphicSelects();

			dialog.append(
				$( document.createElement('IMG') ).attr({ 
					'id': 'close_param_dialog', 
					'src': '../templates/w_shop/images/popup_close.gif'
				})
			);

			// Скрыть диалог по щелчку на его фоновом блоке
			$( '#glass' ).add( $( '#close_param_dialog' ) ).one( 'click', hideAll );
		};

		// Отобразить предзагрузчик
		var showPreloader = function() {

			// Запрет скрытия всплывающих элементов во время выполнения запроса
			$( '#glass' ).unbind( 'click' );

			// Динамическое добавление к документу предзагрузчика
			$( 'body' ).eq(0).append(
				$( document.createElement('div') ).attr('id', 'ajaxPreloader').append( preloader )
			);

			var loader = $( '#ajaxPreloader' ).addClass( 'system_popup' );

			// Вставка содержимого окна
			loader.css({
				display: 'block',
				left: posLeft( loader )+'px',
				top: posTop( loader )+'px'
			});
		}

		// Скрыть предзагрузчик
		var hidePreloader = function() {
			$( '#ajaxPreloader' ).remove();
		}

		// Удаление из корзины ----------------------------------------
		var checkDelLinks = function() {

			var delLinks = $( '#bList' ).find( 'a' ).filter( function(){
				// Поиск ссылок добавления в корзину
				return ( $( this ).attr( 'href' ).search( /(?:&|\?)gdel=\d+/i ) > 0 && $( this ).attr( 'href' ).search( /(?:&|\?)gel=\d+/i ) > 0 )? true: false;
			}).each( function() {
				// Извлечение и запоминание id товара для каждой найденной ссылки и стирание атрибута href
				$( this ).data({ 'gdel': $( this ).attr( 'href' ).match( /(?:&|\?)gdel=(\d+)/i )[1], 'gel': $( this ).attr( 'href' ).match( /(?:&|\?)gel=(\d+)/i )[1] }).attr( 'href', '#' );
			});

			delLinks.bind( 'click', function(){ // Привязка события click ко всем найденным ссылкам
				
				var clickedElement = $( this );
	
				showGlass(); // Динамическое добавление блока-фона для всплывающих окон
	
				var glass = $( '#glass' );
	
				// Обработчик ожидания ответа
				glass.ajaxSend( showPreloader );
	
				// Обработчик неудачного запроса
				glass.ajaxError( function(){
					hidePreloader();
					showPopup( '<div style="margin: 40px 20px;"><h3>Ошибка подключения.</h3><a href="#">закрыть</a></div>' );
					$( '#shop_dialog' ).find('a').one( 'click', function(){ hidePopup(); return false; } );
				});
				
				// установка параметров для отправки
				var inputs = {
					bl: 100, 
					pid: pageId, 
					rid: razdId, 
					lang: getlanguage, 
					tplID: templateId, 
					view: viewId, 
					gdel: clickedElement.data('gdel'), 
					gel: clickedElement.data('gel'), 
					action: 'delelem'
				};
	
				// Отправка Ajax запрса
				$.post( '../templates/w_shop/ajax/cart.php', inputs, function(data, textStatus, XMLHttpRequest){
					// Если запрос выполнен, обновляем корзину в левой колонке
					if ( $( 'div#basket div.basket_text' ).length ) {
						updateBasketHTML( data );
						updateSmallBasket( data );
						// Повторный пересмотр всех ссылок удаления в корзине
						checkDelLinks();
						// Поиск неактуальных пометок "куплено"
						var notActualReserved = $( 'img.reserved' ).filter( function(){
							var id = parseInt( $( this ).prev( 'a' ).data('gid') );
							if ( id > 0 ) {
								var thisInBasket = $( '#bList' ).find( 'a' ).filter( function(){
									return ( $(this).data('gdel') == id )? true: false;
								}); return ( thisInBasket.length )? false: true;
							} else {
								return true;
							}
						}); if ( notActualReserved.length ) notActualReserved.remove();
					};
					// Спрятать всё всплывающее
					hideAll();
					updateBasketHeight();
				});
	
				// Запрет перехода по ссылке
				return false;
			});

		}; checkDelLinks();

		// Добавление в корзину ----------------------------------------
		var cartLinks = $( 'a' ).filter( function(){
			// Поиск ссылок добавления в корзину
			return ( typeof $( this ).attr( 'href' ) !== 'undefined' && $( this ).attr( 'href' ).search( /(?:&|\?)gid=\d+/i ) > 0 )? true: false;
		}).each( function() {
			// Извлечение и запоминание id товара для каждой найденной ссылки и стирание атрибута href
			$( this ).data( 'gid', $( this ).attr( 'href' ).match( /(?:&|\?)gid=(\d+)/i )[1]).attr( 'href', '#' );
		}).bind( 'click', function(){ // Привязка события click ко всем найденным ссылкам

			var clickedElement = $( this );
			clickedElement.trigger('blur');
			
			showGlass(); // Динамическое добавление блока-фона для всплывающих окон

			var glass = $( '#glass' );

			// Обработчик ожидания ответа
			glass.ajaxSend( showPreloader );

			// Обработчик неудачного запроса
			glass.ajaxError( function(){
				hidePreloader();
				showPopup( '<div style="margin: 40px 20px;"><h3>Ошибка подключения.</h3><a href="#">закрыть</a></div>' );
				$( '#shop_dialog' ).find('a').one( 'click', function(){ hidePopup(); return false; } );
			});

			var tovarId = clickedElement.data('gid');

			// Отправка Ajax запрса
			$.post( '../templates/w_shop/ajax/cart.php', {bl: 100, pid: pageId, action: 'getparam', gid: tovarId}, function(data, textStatus, XMLHttpRequest){

				// Отображение диалока в случае успешного запроса
				hidePreloader();
				showPopup( data );

				var addDialog = $( '#shop_dialog' );

				// Клик по кнопке "Купить"
				addDialog.find( '.shop_button' ).find( 'a' ).eq(0).one( 'click', function(){

					// установка параметров для отправки
					var inputs = {
						bl: 100, 
						pid: pageId, 
						rid: razdId, 
						tplID: templateId, 
						view: viewId, 
						action: 'addelem'
					};

					// сбор информации из формы в диалоге
					var form = addDialog.find( 'form' );
					form.find( 'input' ).each( function(){
						var _this = $(this);
						if ( _this.attr('type') == 'radio' ) {
							if ( _this.is(':checked') ) inputs[ $(this).attr('name') ] = $(this).val();
						} else {
							inputs[ $(this).attr('name') ] = $(this).val();
						}
					});
					form.find( 'select' ).each( function(){ 
						inputs[ $(this).attr('name') ] = $(this).find('option:selected').val();
					});

					// Скрыть диалог
					hidePopup();

					// Отправка Ajax запрса
					$.post( '../templates/w_shop/ajax/cart.php', inputs, function(data, textStatus, XMLHttpRequest){
						if ( $( 'div#basket div.basket_text' ).length ) {
							// Если запрос выполнен, обновляем корзину в левой колонке
							updateBasketHTML( data );
							// Повторный пересмотр всех ссылок удаления в корзине
							checkDelLinks();
						};
						if ( $( '#small_basket' ).length ) {
							updateSmallBasket( data );
						}; 
						// Добавление пометки "куплено", если ее еще нет
						var newgid = parseInt( clickedElement.data('gid') );
						if ( newgid ) {
							cartLinks.filter( function(){
								var currentLink = $( this );
								return ( currentLink.data( 'gid' ) == tovarId && !currentLink.next( 'img.reserved' ).length )? true: false;
							}).after('<img class="reserved" src="../templates/w_shop/images/reserved_2.gif" title="Добавлено">');
						}
						// Спрятать всё всплывающее
						hideAll();
						bubbleOk();
						updateBasketHeight();
					});

					// Запрет перехода по ссылке
					return false;
				});
			});

			// Запрет перехода по ссылке
			return false;
		});

	})();

});


