// -----------------------------------------------------------------------------------
// Модуль сравнения

var comparePrc = false;

function compareModule () {
	this.ready = false;
	this.groupId = 0;
	this.ckName = 'senetsy_compare';
	if (o = document.getElementById("compareMenu")) {
		this.oDiv = o;
		this.groupId = this.oDiv.getAttribute("group");
		this.clink = this.oDiv.getAttribute("link");
		this.storage = this.load(this.groupId);
		this.ready = true;
		this.redraw();
	} return this;
}

compareModule.prototype.redraw = function () {
	if (!this.ready) return false;
	total = this.storage[this.groupId].length;
	if (total) {		
		this.oDiv.innerHTML = '<span class="list"><a href="'+this.clink+'?compare='+this.groupId+'"><ins></ins><span>Сравнение товаров</span></a><s>('+total+')</s></span>';
		this.oDiv.style.display = 'block';
	} else {
		this.oDiv.style.display = 'none';
	}
}

compareModule.prototype.add = function (eId) {
	if (!this.ready) return false;
	this.storage = this.load(this.groupId);
	for (var i = 0; i < this.storage[this.groupId].length;i++) {
		if (this.storage[this.groupId][i] == eId) return true;		
	} this.storage[this.groupId].push(eId);
	this.save();
	return true;
}

compareModule.prototype.remove = function (eId) {
	if (!this.ready) return false;
	this.storage = this.load(this.groupId);
	var n = new Array();
	for (var i = 0; i < this.storage[this.groupId].length;i++) {
		if (this.storage[this.groupId][i] == eId) continue;
		n.push(this.storage[this.groupId][i]);
	} if (n.length != this.storage[this.groupId].length) {
		this.storage[this.groupId] = n;
		this.save();
	} return true;
}

compareModule.prototype.check = function (eId) {
	if (!this.ready) return false;
	for (var i = 0; i < this.storage[this.groupId].length;i++) {
		if (this.storage[this.groupId][i] == eId) return true;
	} return false;
}

compareModule.prototype.save = function () {
	var d = new Array ();
	for (a in this.storage) {
		if (this.storage[a].length) d.push(a+'_'+this.storage[a].join('-'));
	} var n = new Date();
	if (n.getMonth() > 10) {
		n.setMonth(0);
		n.setFullYear(n.getFullYear()+1);
	} else {
		n.setMonth(n.getMonth()+1);
	} setCookie(this.ckName, d.join('|'),n,'/');
	this.redraw();
}

compareModule.prototype.load = function (gId) {
	var heap = {};
	if (v = this.getCookie(this.ckName)) {
		var c = v.split('|');
		for (var i = 0; i < c.length; i++) {
			var d = c[i].split('_');
			if (d.length == 2) { 
				heap[d[0]] = d[1].split('-');
			}
		}
	} if (!heap[gId]) {
		heap[gId] = new Array();
	} return heap;
}

compareModule.prototype.getCookie = function () {
	var dc = document.cookie; 
	var prefix = this.ckName + "=";
	var begin = dc.indexOf("; " + prefix);	
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else {
		begin += 2;
	} var end = document.cookie.indexOf(";", begin);	
	if (end == -1) end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) + 
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
	document.cookie = curCookie;
}


// Менеджер сравнения
var CompareManager = {

	init: function () {
		var me = this;
		var item, name, link;
		$("div.compare-link[rel=compare]").each(function(){
			item = $(this);
			name = item.attr('item_id');
			link = item.find('a');
			me.updateItem(item, name);
			if (!link.attr('hasEvent')) {
				item.find('a').click(function(e){
					me.select($(this));
					return false;
				})
				link.attr('hasEvent', 1);
			}
		})
	},
	
	update: function () {
		var me = this;
		var item, name;
		$("div.compare-link[rel=compare]").each(function(){
			item = $(this);
			name = item.attr('item_id');
			me.updateItem(item, name);
		})
	},
	
	updateItem: function (item, name) {
		if (comparePrc.check(name)) {
			item.addClass('added');
		} else {
			item.removeClass('added');
		}
	},
	
	select: function (oLink) {
		var parent = oLink.parents('div.compare-link');
		var name = parent.attr('item_id');

		if (parent.hasClass('added')){
			comparePrc.remove(name);
			parent.removeClass('added');			
		} else {
			comparePrc.add(name);
			parent.addClass('added');
		}
	}
}


// Переключалка видов сравнения
var Compare = {

	table: null,
	
	selected: null,
	
	init : function() {

		this.table = $('#compare-table');
		if (!this.table.size()) {
			return;
		}

		var me = this;
		var elem, link;
		$('#compare_switch li.item').each(function(){
			elem = $(this);
			if (elem.hasClass('selected')) {
				me.selected = elem;
			}
			elem.click(function(e){
				me.doSwitch($(this));
			})
		})
	},
	
	doSwitch: function (elem) {
		var name = elem.attr('name');
		if (this.selected) {
			this.selected.removeClass('selected')
			this.table.removeClass(this.selected.attr('name'));
		}
		elem.addClass('selected');
		this.table.addClass(name);
		this.selected = elem;
	}
}




// -----------------------------------------------------------------------------------
// Переключатель закладок на странице бренда

var BrandTabs = {

	tabs: {},
	selected: null,

	init: function () {

		var self = this;
		var content = $('#brand-tabs');

		if (!content.size()){
			return;
		}

		var tab, link, name;
		content.find('ul.family-tabs li').each(function(){
			tab = $(this);
			link = tab.find('a');
			name = link.attr('href').replace('#', '');
			self.tabs[name] = {
				elem: tab,
				layer: $('#' + name + '_layer')
			}
			link.click(function(e){
				var href = decodeURIComponent(e.target.href);
				$.history.load(href.replace(/^.*#/, ''));
			})
			if (tab.hasClass('selected')) {
				self.selected = name;
			}
		})
		
		$.history.init(function(name){
			if (name != '') {
				BrandTabs.select(name);
			}
		});
	},
	
	select: function (name) {
		
		if (name == this.selected) {
			return;
		}
		
		var targetTab, selectedTab;
		if (this.selected) {
			selectedTab = this.tabs[this.selected];
			selectedTab.elem.removeClass('selected');
			selectedTab.layer.hide();
		}

		targetTab = this.tabs[name];
		targetTab.elem.addClass('selected');
		targetTab.layer.show();
		
		this.selected = name;
	}
}




// -----------------------------------------------------------------------------------
// Переключатель направлений и категорий на странице бренда

Directions = {

	duration: 300,
	
	items: {},

	selected: null,

	init: function () {

		var self = this;
		var content = $('.directions');

		if (!content.size()){
			return;
		}

		var link, item;
		content.find('a.pseudo-link').each(function(num){
			link = $(this);
			link.attr('num', num);
			item = link.parents('li');
			self.items[num] = {
				elem: item,
				links: item.find('ul.links')
			}
			link.click(function(){
				var num = $(this).attr('num');
				self.switchItem(num);
				return false;
			})
		})
	},

	switchItem: function (num) {

		this.hide(this.selected);
		if (num != this.selected) {
			this.show(num);
			this.selected = num;
		} else {
			this.selected = null;
		}
	},
	
	show: function (num) {
		var item = this.items[num];
		if (item) {
			item.elem.addClass('selected');
			item.links.slideDown(this.duration);
		}
	},
	
	hide: function (num) {
		var item = this.items[num];
		if (item) {
			item.elem.removeClass('selected');
			item.links.slideUp(this.duration);
		}
	}
}




// -----------------------------------------------------------------------------------
// Переключалка прайс-листов
// в других форматах на странице бренда

var PriceFormats = {

	init: function () {
		
		var self = this;
		var content = $('#price_formats_layer');
		
		if (!content.size()){
			return;
		}
		
		this.link = $('#price_formats_link');
		this.wrapper = this.link.parent();
		
		if ($.browser.msie) {
			var oBody = document.getElementsByTagName('body').item(0);
			var layer = document.createElement('ul');
			layer.className = 'formats-list';
			oBody.appendChild(layer);
		
			this.layer = $(layer);
			this.layer.html(content.html());
			
			$(window).resize(function(e){
				self.move();
			})
		} else {
			this.layer = content;
		}
		
		this.link.click(function(){
			if (self.wrapper.hasClass('selected')) {
				self.close();
			} else {
				self.open();
			}
			return false;
		})
		
		this.layer.click(function(e){
			if (e.target && e.target.tagName != 'A') {
				e.stopPropagation();
				e.cancelBubble = true;
				return false;
			} else {
				return true;
			}
		})
		
		$(document).click(function(e){
			if (e.target) self.close();
		})
	},
	
	open: function () {
		this.move();
		this.layer.show();
		this.wrapper.addClass('selected');
	},
	
	close: function () {
		this.layer.hide();
		this.wrapper.removeClass('selected');
	},
	
	move: function () {
		if (!$.browser.msie) return;
		this.layer.css('top', this.wrapper.offset().top + this.wrapper.height() + 14);
		this.layer.css('left', this.wrapper.offset().left)
	}

}




// -----------------------------------------------------------------------------------
// Переключалка серий

var SeriesUtils = {

	series: {},
	groups: {},
	selectedItem: null,
	defaultItem: null,
	groupPrefix: 'group',
	fadeElem: null,
	
	init: function () {
	
		var tabsWrapper = $('#series-chooser');
		if (!tabsWrapper.size()) {
			return;
		}
		
		this.fadeElem = $('#family-list-fade');

		var me = this;
		var name, elem, link, index, group;
		var parsedUrl = Utils.parseUrl();
		
		this.resizeSelected();

		$('ul.series li').each(function(i){

			elem = $(this);
			link = elem.find('a');
			name = link.attr('href').replace(/^.*#/, '');
			group = me.groupPrefix + (elem.attr('group') ? elem.attr('group') : 'all');
			index = (elem.attr('rel') == 'index' ? true : false);
			elem.attr('name', name);

			me.series[name] = {
				elem: elem,
				index: index
			}

			me.groups[name] = document.getElementById(group);
			
			link.click(function(e){
				//var href = decodeURIComponent(e.target.href);
				//$.history.load(href.replace(/^.*#/, ''));
				$.history.load(this.href.replace(/^.*#/, ''));
				return false;
			})
			
			if (parsedUrl.anchor == name) {
				me.select(name, true);
			}

			if (index) {
				me.defaultItem = name;
			}
		})

		$.history.init(function(name){
			if (name) {
				SeriesUtils.select(name);
			} else {
				SeriesUtils.select(SeriesUtils.defaultItem);
			}
		});
		
		$(window).resize(function(){
			me.resizeSelected();
		})
	},

	select: function (name, init) {

		if (name == this.selectedItem) {
			return;
		}

		if (this.selectedItem) {
			var selected = this.series[this.selectedItem];
			selected.elem.removeClass('selected');
			if (selected.index) selected.elem.removeClass('all');
		}

		var item = this.series[name];
		item.elem.addClass('selected');
		if (item.index) item.elem.addClass('all');

		var group = this.groups[name];
		if (!group) {
			this.selectedItem = name;
			return;
		}

		var fade = this.fadeElem;
		var wrapper = document.getElementById('family-list-wrapper');
		var delta = group.offsetLeft - wrapper.offsetLeft;
		var height = group.offsetHeight;

		if (init) {
			wrapper.scrollLeft = delta;
			$(wrapper).height(height);
		} else {
			fade.show();
			$('#family-list-wrapper').animate({
				scrollLeft: delta
			}, function(){
				$(this).height(height);
				fade.hide();
			})
		}

		this.selectedItem = name;
	},
	
	resizeSelected: function () {

		var wrapper = document.getElementById('family-list-wrapper');
		var width = wrapper.offsetWidth;
		
		$('#family-list .family-group').each(function(i){
			$(this).width(width);
		})

		if (this.selectedItem) {
			var group = this.groups[this.selectedItem];
			var delta = group.offsetLeft - wrapper.offsetLeft;
			var height = group.offsetHeight;
	
			wrapper.scrollLeft = delta;
			$(wrapper).height(height);
		}
	}
}




// -----------------------------------------------------------------------------------
// Переключалка закладок на странице семейства

FamilyTabsUtils = {


	tabs: {}, 					// список закладок
	
	selectedTab: null,			// имя текущей успешно загруженной закладки
	
	activeTab: null,			// имя текущей закладки перед загрузкой (по которой кликнули)
	
	defaultTab: null,			// имя основной закладки, загружаемой по-умолчанию
	
	platformName: null,			// имя выбранной платформы
	
	hasFullHeader: true,
	
	headerDims: [],				// здесь будем сохранять высоты заголовка
	
	headerState: 0,

	interval: null,

	classNames: ['selected', 'loading'],
	
	firstLoad: true,

	loading: false,


	// функция инициализации утилиты
	init: function () {
		
		var familyContainer = $('#FamilyContainer');
		
		// если это страница сравнения товаров, выключаем скрипт
		if ($('#compare-table').size()) return;
		if (!familyContainer.size()) return;
		
		// есть ли вообще закладки?
		var tabsWrapper = familyContainer.find('ul.family-tabs');
		if (!tabsWrapper.size()) return;

		// проверяем наличие большой картинки
		// если она существует, запомниаем размеры блоков
		if (!$('#headerPic').size()) {
			this.hasFullHeader = false;
		} else {
			headerDims = [$('#headerPic').height(), $('#headerSimple').height()];
		}
		
		// индикатор загрузки страницы
		this.loadingStatus = $('#content-loading');

		var name, elem, link, layer_name, layer, loaded;
		var self = this;
		var container = $('#family-content-wrapper');
		var indexTab = null;
		
		// собираем закладки в массив
		tabsWrapper.children('li').each(function(i){

			elem = $(this);
			link = elem.children('a'); // ссылка на страницу
			name = elem.attr('name') ? elem.attr('name') : 'tab' + i; // имя закладки

			layer_name = name + '_content';
			layer = $('#' + layer_name);
			if (!layer.children().size()) {
				loaded = false;
			} else {
				loaded = true;
			}

			self.tabs[name] = { // запоминаем параметры закладки
				tab: elem,
				link: link,
				url: link.attr('href'),
				layer: layer,
				loaded: loaded,
				index: (i == 0 ? true : false)
			}
			if (i == 0) {
				indexTab = name;
			}
			
			link.attr('href', '#' + name); // подменяем href ссылок
			link.click(function(e){ // ловим клик по ссылке
				if (self.loading) {
					tabsWrapper.stop();
					return false;
				}
				var href = decodeURIComponent(e.target.href);
				$.history.load(href.replace(/^.*#/, ''));
				return false;
			})
			
			if (elem.hasClass('selected')) {
				self.selectedTab = name;
				self.defaultTab = name;
			} else {
				layer.hide();
			}
			
		});
		
		// обрабатываем событие перед загрузкой содержания закладки
		tabsWrapper.ajaxSend(function(){

			var active = self.tabs[self.activeTab];
			self.loading = true; // начинаем загрузку
			self.interval = setInterval(function(){
				if (self.activeTab) {
					active.tab.addClass(self.classNames[1]);
				}
			}, 100);

		})
		
		// обрабатываем событие после успешной загрузки содержания
		tabsWrapper.ajaxComplete(function(){
			
			try {
				if (!self.firstLoad) {
					self.loadingStatus.hide();
				}
	
				var item = self.tabs[self.activeTab];
				item.tab.removeClass(self.classNames[1]);
				item.tab.addClass(self.classNames[0]);
				item.layer.show();
				item.loaded = true;

				item.platforms = new FamilyPlatforms(item.layer); // создаем таблицу с платформами
				item.platforms.selectByUrl(self.platformName);
				
				self.loading = false; // успешно загрузили
				self.selectedTab = self.activeTab;
				self.activeTab = null;
				clearInterval(self.interval);
				
				self.toggleHeader(item.index); // анимация заголовока
				familyReload();
			} catch (e) {
				//
			}
		})
		
		// обрабатываем событие ошибки загрузки
		tabsWrapper.ajaxError(function(){
			var item = self.tabs[self.activeTab];
			document.location.href = item.url;
		})
		
		if (indexTab != this.defaultTab) {
			this.headerState = 1;
		}
		
		$.history.init(function(url){
			var urls = url.split('/');
			var tabName = urls[0];
			var platformName = urls[1];
			FamilyTabsUtils.platformName = platformName;
			FamilyTabsUtils.selectByUrl(tabName, platformName);
		});
	},
	
	selectByUrl: function (tabName, platformName) {
		if (tabName) {
			if (this.firstLoad && this.selectedTab != tabName) { // первая загрузка
				var selected = this.tabs[this.selectedTab];
				selected.layer.hide();
				this.loadingStatus.show();
				this.toggleHeader(false)
				this.firstLoad = false;
			}
			this.select(tabName, platformName);
		} else {
			this.select(this.defaultTab);
		}
	},
	
	// функция, обработчик события клика по ссылке закладки
	select: function (tabName, platformName) {

		if (tabName == this.selectedTab) {
			this.firstLoad = false;
		//	return;
		}

		var item = this.tabs[tabName];
		if (!item) {
			return;
		}
		var selected = this.tabs[this.selectedTab];
		selected.tab.removeClass(this.classNames[0]);

		if (!item.loaded) {
			this.activeTab = tabName;
			selected.layer.css('opacity', 0.5);
			$.get(item.url + '?ajax=1', function(content){
				selected.layer.css('opacity', 1);
				selected.layer.hide();
				item.layer.html(content);
			});
		} else {
			selected.layer.hide();
			item.tab.addClass(this.classNames[0])
			item.layer.show();
			if (!item.platforms) {
				item.platforms = new FamilyPlatforms(item.layer); // создаем таблицу с платформами
			}
			item.platforms.selectByUrl(platformName);
			CompareManager.update(); // обновляем ссылки добавления к сравнению
			this.toggleHeader(item.index);
		}

		this.selectedTab = tabName;
	},
	
	// функция анимации заголовка
	toggleHeader: function (isIndex) {

		if (!this.hasFullHeader) {
			return;
		}
		var headerPic = $('#headerPic');
		var headerSimple = $('#headerSimple');
		var duration = 200;

		if (isIndex && this.headerState) {
			if (this.firstLoad) {
				headerPic.show();
				headerSimple.hide();
			} else {
				headerSimple.animate({
					height: headerDims[0]
				}, duration, null, function(){
					headerPic.height(headerDims[0])
					headerSimple.height(headerDims[1])
					headerPic.show();
					headerSimple.hide();
				});
			}
			this.headerState = 0;
		} else if (!isIndex && !this.headerState) {
			if (this.firstLoad) {
				headerPic.hide();
				headerSimple.show();
			} else {
				headerPic.animate({
					height: headerDims[1]
				}, duration, null, function(){
					headerPic.hide();
					headerSimple.show();
				});
			}
			this.headerState = 1;
		}
	}
}




// -----------------------------------------------------------------------------------
// Переключалка платформ (модели и цены + фотогалерея)

function FamilyPlatforms (container) {

	this.container = container;
	this.platforms = {};
	this.selected = null;
	this.wrapper = this.container.find('table.family-data');
	this.wrapperHeight = null;
	this.states = ['platforms', 'photos'];
	this.state = 0;
	this.listPrefix = 'list_';
	this.init();
}

FamilyPlatforms.prototype.init = function () {

	var me = this;
	var platformsSelector = this.container.find('thead.platforms_selector');
	var photosSelector = this.container.find('thead.photos_selector');
	
	if (platformsSelector.size()) { // платформы
		this.state = 1;
		this.selector = platformsSelector;
		this.initPlatforms();
	} else if (photosSelector.size()) { // фотографии
		this.state = 2;
		this.selector = photosSelector;
		this.initPhotos();
	}

	$(window).resize(function(){
		me.stretchBorders()
	})
}

FamilyPlatforms.prototype.initPlatforms = function () {
	var me = this;
	var elem, name, borders, list, link, platform;
	
	// собираем платформы
	this.selector.find("tr.platforms td").each(function(i){
		elem = $(this);
		name = elem.attr('rel');
		if (elem.hasClass('noprice')){
			me.platforms[name] = {
				elem: elem,
				name: name,
				index: i,
				dom: this,
				disabled: true
			}
		} else {
			borders = elem.children('div.borders');
			list = me.container.find('*[rel=' + me.listPrefix + name + ']');
			list = new ModelsList(list);
			me.platforms[name] = {
				elem: elem,
				name: name,
				index: i,
				dom: this,
				disabled: false,
				borders: borders,
				list: list
			}
			if (this.className == 'selected'){
				me.selected = name;
			}
		}
	})
	
	// собираем миниатюры
	this.selector.find('tr.thumbs td').each(function(){
		elem = $(this);
		name = elem.attr('rel');
		
		platform = me.platforms[name];
		platform.thumb = $(this);
		
		// ссылка миниатюры
		link = elem.find('a');
		link.attr('href', me.formatURL(platform.disabled ? 1 : 0, name));
		link.click(function(e){ return me.linkClick(this) })
	})
	
	// собираем ссылки для сравнения
	this.selector.find('tr.links td').each(function(){
		elem = $(this);
		name = elem.attr('rel');
		platform = me.platforms[name];
		platform.compare = elem;
	})

	// собираем переключалки платформ
	this.selector.find("tr.prices td[class!='noprice']").each(function(){
		elem = $(this);
		name = elem.attr('rel');
		
		// ссылка цены
		link = elem.find('a[href]');
		link.attr('href', me.formatURL(0, name));
		link.click(function(e){ return me.linkClick(this) })

		// ссылка на закрытие платформы
		link = elem.find('a.close');
		link.attr('href', '#platforms');
		link.click(function(e){ return me.linkClick(this) })
		
		platform = me.platforms[name];
		platform.price = elem;
	})
}

FamilyPlatforms.prototype.initPhotos = function () {
	var me = this;
	var elem, name, borders, link, list, platform;

	// собираем платформы
	this.selector.find('tr.platforms td').each(function(i){
		elem = $(this);
		name = elem.attr('rel');
		borders = elem.children('div.borders');
		list = me.container.find('*[rel=' + me.listPrefix + name + ']');
		me.platforms[name] = {
			elem: elem,
			name: name,
			index: i,
			dom: this,
			borders: borders,
			list: list
		}
		if (this.className == 'selected' || !this.className && i == 0){
			me.selected = name;
		}
	})

	this.selector.find('tr.thumbs td').each(function(){
		elem = $(this);
		name = elem.attr('rel');

		link = elem.find('a.zoom');
		link.attr('href', me.formatURL(1, name));
		link.click(function(e){ return me.linkClick(this) })

		platform = me.platforms[name];
		platform.thumb = $(this);
	})
}

FamilyPlatforms.prototype.linkClick = function (href) {
	var href = decodeURIComponent(href);
	$.history.load(href.replace(/^.*#/, ''));
	return false;
}
	
FamilyPlatforms.prototype.selectByUrl = function (name) {
	if (name) {
		this.select(name); // показываем платформу
	//} else if (name == undefined && this.state == 2) {
	//	this.show(this.selected); // показываем первую фотографию
	} else {
		this.hide(this.selected); // исходное состояние
	}
}
	
FamilyPlatforms.prototype.select = function (name) {
	if (this.selected) {
		this.hide(this.selected);
	}
	this.show(name);
}
	
FamilyPlatforms.prototype.show = function (name) {
	var platform = this.platforms[name];
	if (!platform || platform && platform.disabled) {
		return false;
	}

	for (var n in this.platforms) {
		var p = this.platforms[n];
		if (n != name) {
			p.elem.addClass('disabled');
			p.thumb.addClass('disabled');
		}
	}
	
	platform.elem.addClass('selected');
	if (platform.list) platform.list.show();
	if (platform.compare) platform.compare.addClass('selected');
	if (platform.price) platform.price.addClass('selected');

	switch (this.state) {
		case 1:
			var overview = this.wrapper.find('tbody.overview');
			overview.children('tr').each(function(){
				for (var i = 0; i < this.cells.length; i++) {
					if (i == platform.index + 1) {
						this.cells[i].className = 'selected';
					}
				}
			})
			overview.addClass('disabled');
			if (platform.thumb)	platform.thumb.addClass('enabled');
			this.setPlatformLink(name, platform.thumb, 1);
		break;
		case 2:
			if (platform.thumb)	platform.thumb.addClass('selected');
		break;
	}
	
	this.selected = name;
	this.stretchBorders();
	return true;
}
	
FamilyPlatforms.prototype.hide = function (name) {
	var platform = this.platforms[name];
	if (!platform) {
		return false;
	}

	for (var n in this.platforms) {
		var p = this.platforms[n];
		p.elem.removeClass('disabled');
		p.thumb.removeClass('disabled');
	}

	platform.elem.removeClass('selected');
	if (platform.list) platform.list.hide();
	if (platform.compare) platform.compare.removeClass('selected');
	if (platform.price) platform.price.removeClass('selected');

	switch (this.state) {
		case 1:
			var overview = this.wrapper.find('tbody.overview');
			overview.children('tr').each(function(){
				for (var i = 0; i < this.cells.length; i++) {
					if (i == platform.index + 1) {
						this.cells[i].className = '';
					}
				}
			})
			overview.removeClass('disabled');
			if (platform.thumb) platform.thumb.removeClass('enabled');
			this.setPlatformLink(name, platform.thumb, 0);
		break;
		case 2:
			if (platform.thumb) platform.thumb.removeClass('selected');
		break;
	}
	
	this.selected = null;
	return true;
}

FamilyPlatforms.prototype.setPlatformLink = function(name, thumb, selected) {
	// ссылка на фотографии
	var me = this;
	var link = thumb.find('a.zoom');
	link.attr('href', this.formatURL(selected, name));
}
	
FamilyPlatforms.prototype.stretchBorders = function() {
	try {
		var h = this.wrapper.height();
		var platform, borders, pipe;
		platform = this.platforms[this.selected];
		borders = platform.borders;
		pipe = borders.find('div.pipe');
		if (this.wrapperHeight != h) {
			if (pipe) pipe.css('top', h);
			borders.find('div.border').each(function(){
				$(this).height(h);
			})
		}
	} catch(e){}
}

FamilyPlatforms.prototype.formatURL = function (stateIdx, name) {
	return '#' + this.states[stateIdx]  + '/' + name;
}

function ModelsList (oList) {
	this.oList = $(oList);
	this.duration = 300;

	var that = this;
	this.oList.find('div.group a.title').click(function(e){ that.itemClick(e) })
}

ModelsList.prototype.itemClick = function (e) {
	var elem = $(e.target);
	if (elem.hasClass('empty')) {
		return;
	}
	var group = elem.parents('div.group');
	var list = group.find('table');
	if (group.hasClass('active')) {
		list.slideUp(this.duration, function () {
			group.removeClass('active')
		});
	} else {
		group.addClass('active')
		list.slideDown(this.duration);
	}
}

ModelsList.prototype.show = function () {
	this.oList.show();
}

ModelsList.prototype.hide = function () {
	this.oList.hide();
}




// -----------------------------------------------------------------------------------
// Подсказки

Tips = {

	container: null,
	
	currentTip: null,
	
	interval: null,
	
	tipHasFocus: false,
	
	initialized: false,
	
	animateDuration: 100,
	
	init: function () {

		if (!this.initialized) {
			this.create();
	
			this.container.mouseover(function(e){ me.tipHasFocus = true;  })
			this.container.mouseout(function(e){  me.tipHasFocus = false; })
			
			var me = this;
			$(document).click(function(e){
				if (e.target && e.target.className.indexOf('tip-container') < 0) {
					me.hideCurrent($(e.target))
				}
			})
			
			this.initialized = true;
		}

		this.collect();
	},
	
	collect: function () {
		var elem;
		var me = this;
		var buttons = $('span.help-btn, ins.stock');
		buttons.each(function(i){
			elem = $(this);
			elem.css('zIndex', 1000);
			if (!elem.children().size()) {
				elem.hide();
			} else if (!elem.attr('tip')) {
				elem.attr('tip', 1);
				elem.mouseover(function(e){
					me.over(e);
				})
				elem.mouseout(function(e){
					me.out(e);
				})
			}
		})
	},
	
	create: function () {
		var oBody = document.getElementsByTagName('body').item(0);
		var oContainer = document.createElement('div');
		oContainer.className = 'tip-container';
		oBody.appendChild(oContainer);
		this.container = $(oContainer);
	},
	
	over: function (e) {
		var elem = $(e.target);
		this.show(elem)
	},
	
	out: function (e) {
		var me = this;
		var elem = $(e.target);
		var hideFunc = function(){
			if (!me.tipHasFocus) {
				me.hide(elem)
			}
		}
		this.interval = setInterval(hideFunc, 1000);
	},
	
	show: function (elem) {
		clearInterval(this.interval);
		if (this.currentTip && this.currentTip != elem) {
			this.hide(this.currentTip);
		}
		var tip = elem.children('p');
		var offset = elem.offset();
		var d = elem.hasClass('stock') ? 3 : 0; // hack
		elem.addClass('opened');
		this.container.html('<ins></ins>' + tip.html());
		this.container.css('top', offset.top + d);
		this.container.css('left', offset.left + d);
		if (offset.left + this.container.width() > $(window).width()) {
			this.container.addClass('rt');
			this.container.removeClass('lt');
		} else {
			this.container.addClass('lt');
			this.container.removeClass('rt');
		}
		this.container.show();
		this.currentTip = elem;
	},
	
	hide: function (elem) {
		clearInterval(this.interval);
		elem.removeClass('opened');
		this.container.hide();
		this.currentTip = null;
	},
	
	hideCurrent: function (elem) {
		if (elem.attr('tip') || elem.parent().attr('tip')) {
			return;
		}
		if (this.currentTip) {
			this.hide(this.currentTip);
		}
	}

}




// -----------------------------------------------------------------------------------
// Двигает стрелку легенды на модулях

function moveLegend() {
	$('tfoot div.legend').each(function(){
		var a = $(this);
		var b = $('th.tab_title').next()[0].offsetWidth - 40;
		a.find('ins.arrow').css('left', b)
		//alert($('th.tab_title').next().html())
		//a.css('left', b.offsetLeft)
	})
}

function checkHScroll() {
	var table = $('#FamilyContainer');
	var td = table.find('tr:first > td');
	if (table.width() > $(window).width()) {
		td.addClass('pad');
	} else {
		td.removeClass('pad');
	}
}




// -----------------------------------------------------------------------------------


$(document).ready(function(){

	comparePrc = new compareModule();
	Compare.init();
	
	FamilyTabsUtils.init();
	BrandTabs.init();
	Directions.init();
	SeriesUtils.init();
	PriceFormats.init();
	
	$(window).resize(function(){
		checkHScroll();
	})
	familyReload();
})


function familyReload() {
	CompareManager.init();
	Tips.init();
	checkHScroll();
}

