(function ($) {

	$(function() { 
		
		if ($.browser.opera) {
			$.support.opacity = true;
		}

		if ($('#menu_left .selected').length) {
		
			var tt = $('#menu_left .selected').position().top;
			$('#strelko').css({'top':tt+3})
		
		}
		
		$('.regiserform').jqTransform({imgPath: _root + 'i/'});
		$('#left_s form').jqTransform({imgPath: _root + 'i/'});
		$('#basketItems').jqTransform({imgPath: _root + 'i/'});
		$('#advSearch').jqTransform({imgPath: _root + 'i/'});
		$('#login').jqTransform({imgPath: _root + 'i/'});
		
		
		{ // обработка неавторизованного каталога

			$('.more_public').click(function (e) {
				popUp
					.top(e.pageY)
					.load(this);
				return false;
			});
			
		}
		
		{ // обработка авторизованного каталога

			var topA = $(document.body).height() / 2, top = 0;

			$('.more_auth_index').click(function (e) {

				// topA = e.pageY || topA;
				topA = $(this).offset().top;
				
				popUpAuth
					.top(topA)
					.load(this);
				return false;
			});
			
			
			$('.more_auth').click(function (e) {
				
				//top = $(this).offset().top;
				
				top = $(this).position().top;

				$('.more_auth_index', $(this).parents('tr:first')).click();
				return false;
			});
			
		}

		{	// обработка форм поиска каталога
			
			$("#advSearchLink").toggle(function () {
				$(this).addClass('selected');
				$('#advSearch').fadeIn();
				return false;
			}, function () {
				$(this).removeClass('selected');
				$('#advSearch').fadeOut();
			});

			$('#model_name, #full_model_name, #min_price, #max_price, #day, #month, #year').each(function () {
				$(this).DefaultValue($(this).val());
			})

		}

		
		
			
	});




	/**
	 * Абстрактный объект по управлению всеми попапами
	 * Каждый новый попап наследуется от этого класаы
	 */
	var popUpAbstract = {

		/**
		 * сам попап
		 */
		_object : null,

		/**
		 * Текущая маленькая сумочка (по сути та по которой кликнули)
		 */
		_currentBag : null,

		/**
		 * Gоложение курсора на экрене в момент клика по сумке
		 */ 
		_top : 0,
		
		show : function (data) {
			
			var _this = this;
			
			$('#overlay')
				.css('opacity', .8)
				.show();
		
			$('#overlay .loader').hide();
				
			if (_this.getNext()) {
				$('#popUpRight', _this._object).show();
			}
			else {
				$('#popUpRight', _this._object).hide();
			}
			
			if (_this.getPrev()) {
				$('#popUpLeft', _this._object).show();
			}
			else {
				$('#popUpLeft', _this._object).hide();
			}
			
			$('.center', _this._object).html(data);
			
			bindCart($('.center', _this._object));

			
			var  top = _this._top - $(_this._object).height() / 2;
			if (top) {
				$(_this._object).css('top', top>0 ? top : 10);
			}
			
			$(_this._object).fadeIn(500);
			
			// обработка наведения на материалы
			$('.matherial_img IMG', _this._object).mouseover(function () {
				
				var src = $('.big_matherial' , $(this).parents('td:first')).html();

				if (src) {
					$(this).parents('.matherial_img').append('<img class="big_mat" src="'+ src + '"/>');
					$('.big_mat', $(this).parents('td:first')).mouseout(function () {
						$('.big_mat').remove();
					})
				}

			});
			
		},
	
		top : function (top) {
			
			this._top = parseInt(top);
			
			return this;
			
		},
		
		hide : function (callback) {
			$('#overlay .loader').show();
			$(this._object).fadeOut(500, callback);
		},


		/**
		 * Назначаем обработчик на кнопке закрыть
		 */
		_bindClose : function () {
			var _this = this;
			$('#popUpClose', this._object).click(function () {
				_this.hide(function () {
					$('#overlay').hide();
				});
				return false;
			});
			
			$('#overlay').click(function () {
				$('#popUpClose', _this._object).click();
			})
			
			return this;
		},

		/**
		 * Назначаем обработчик на кнопке следующая сумка
		 */
		_bindClickLeft : function () {

			var _this = this;
			
			$('#popUpLeft', this._object).click(function () {
	
				_this.hide(function () {
					var prev = _this.getPrev();
					if (prev) {
						if (prev.toString().indexOf('page')>0) {
							document.location = prev.toString()
						}
						else {
							prev.click();
						}
					}	
				});
				
				return false;
			
			});

			return this;

			
		},
		
		/**
		 * Назначаем обработчик на кнопке предыдущая сумка
		 */
		_bindClickRight : function () {

			var _this = this;
			
			$('#popUpRight', this._object).click(function () {
				
				_this.hide(function () {
					var next = _this.getNext();
					if (next) {
						if (next.toString().indexOf('page')>0) {
							document.location = next.toString();
						}
						else {
							next.click();
						}
					}	
				});
			
				return false;
					
			});

			return this;

		},

		/**
		 * Базовая инициализаия попапа
		 * 
		 */
		_init: function () {
			this
				._bindClose()
				._bindClickLeft()
				._bindClickRight();
		},
		
		getNext : function () {
			
			var parent = $(this._currentBag).parents('table');
			var index = $('a.more_public, a.more_auth_index').index(this._currentBag);
			
			if ($('a.more_public, a.more_auth_index').length > index + 1) {
				return $($('a.more_public, a.more_auth_index').get(index+1));
			}
			else {
				// пытаемся найти ссылку на следующую страницу
				if ($('.catPages .next').length) {
					return $('.catPages .next').get(0);
				}
				
				return false;
			}
			
		},

		getPrev : function () {

			var parent = $(this._currentBag).parents('table');
			var index = $('a.more_public, a.more_auth_index').index(this._currentBag);
			
			if (index > 0) {
				return $($('a.more_public, a.more_auth_index').get(index-1));
			}
			else {
				
				// пытаемся найти ссылку на предыдущую страницу
				if ($('.catPages .prev').length) {
					return $('.catPages .prev').get(0);
				}
				
				return false;
			}

		}

	
	}
	
	var popUp = $.extend({

		
		load : function (currentBag) {

			this._currentBag = currentBag;
			var _this = this;

			$.get(_link_catalog, {
					ajax: 1,
					action: 'info',
					model : $(this._currentBag).attr('rel')
			}, function (data) {_this.show(data)});
			
		},
		
		init : function () {

			this._object = $('#popUp');
			this._init();

		}
		
	}, popUpAbstract);
	
	
	var popUpAuth = $.extend({

		load : function (currentBag) {

			this._currentBag = currentBag;
			var _this = this;
			
			var filter = document.location.toString().match(/filter\=([a-z]*)/);

			$.get(_link_catalog, {
					ajax: 1,
					action: 'infoAuth',
					filter: filter ? filter[1] : 'all',
					model : $(this._currentBag).attr('rel')
			}, function (data) {
					_this.show(data);
			});
			
		},
		
		init : function () {

			this._object = $('#popUpAuth');
			this._init();

		}
		
	}, popUpAbstract);
	
	$(function () {
		popUp.init();
		popUpAuth.init();
	})
	

	
})(jQuery);

// Matherials

$(document).ready(function(){	
	$("#matherials ul ul").prev('a').click(function(){
		if($(this).parent("li").hasClass("open")) {
			$(this).parent("li").removeClass("open");
			$(this).next("ul").slideUp();
		}
		else {
			$("#matherials ul li ul").slideUp();
			$("#matherials ul li").removeClass("open");
			$(this).next().slideDown();
			$(this).parent("li").addClass("open");
		}
		return false;
	});
});


$(function () {
	
	// обработка клика на ссылке
	$('.material a').click(function () {
		
		var src = $(this).attr('rel');

		if (src) {
			
			src = _root + src;
			
			$('#catItemsAuth').css('z-index', 9999);
			$(this).parents('.material').append('<img class="big_mat_a" src="'+ src + '"/>');
			$('.big_mat_a', $(this).parents('.material')).mouseout(function () {
				$('.big_mat_a').remove();
				$('#catItemsAuth').css('z-index', 20);
			})
		}

		return false;

	});
	
	
	// обработка клика на ссылке
	$('.matherial_spravochnik').click(function () {
		
		var src = $(this).attr('rel');

		if (src) {
			
			src = _root + src;
			
			$(this).parents('li:first').append('<img class="big_mat_a" src="'+ src + '"/>');
			$('.big_mat_a', $(this).parents('li:first')).mouseout(function () {
				$('.big_mat_a').remove();
			})
		}

		return false;

	});
	
})