/**
 * Scroller implementation for Catalog
 * 
 * CatalogScroller depends on Scroller class, it must be included before creating
 * an instance of CatalogScroller
 *  
 * @param {Object} options Required option parameters are: scroller, tabs, container
 */
function CatalogScroller(options) {
	this.options = $.extend({
		scroller: null,					//Scroller instance
		pos_current: 0,					//First visible item index in the tab
		pos_max: 0,						//Positions in the tab
		tab_current: 0,					//Current tab index
		tab_count: 0,					//Tab count
		tabs: [],						//List of tab nodes
		image_reposition: true,			//Move images up 
		container: null,				//Container element
		animation_in_progress: false,	//Tab animation is running
		next: null,						//"Next" link node
		previous: null					//"Previous" link node
	}, options);
	
	this.init();
};
/* Options/properties/variables */
CatalogScroller.prototype.options = {};
/* Scroll to next item */
CatalogScroller.prototype.next = function () {
	if (this.options.pos_current != this.options.pos_max)
	{
		this.options.pos_current++;
		this.options.scroller.scrollToElement(this.options.pos_current);
		this.resetNavigation();
		
		return false;
	}else{
		return true;
	}
};
/* Scroll to previous item */
CatalogScroller.prototype.previous = function () {
	if (this.options.pos_current > 0)
	{
		this.options.pos_current--;
		this.options.scroller.scrollToElement(this.options.pos_current);
		this.resetNavigation();
		
		return false;
	}else{
		return true;
	}
};
/* Recalculate 'next' and 'previous' button visibility */
CatalogScroller.prototype.resetNavigation = function () {
	var next_visible = true;
	var prev_visible = true;
	
	if (this.options.pos_current == 0) { prev_visible = false; }
	if (this.options.pos_current >= this.options.pos_max) { next_visible = false; }
	
	if (this.options.next) {
		if (next_visible) this.options.next.removeClass('disabled'); else this.options.next.addClass('disabled');
	}
	if (this.options.previous) {
		if (prev_visible) this.options.previous.removeClass('disabled'); else this.options.previous.addClass('disabled');
	}
};
/* Change tab */
CatalogScroller.prototype.changeTab = function (tab_index, skip_tab_check) {
	var self = this;
	skip_tab_check = skip_tab_check || false;
	tab_index = parseInt(tab_index);

	if (!this.options.animation_in_progress && (tab_index != this.options.tab_current || skip_tab_check) && this.options.tabs[tab_index])
	{
		this.options.animation_in_progress = true;
		
		//Fade out current tab
		this.options.tabs.eq(this.options.tab_current).parent().stop().fadeOut('fast', function () {
			//Hide current tab
			self.options.tabs.eq(self.options.tab_current)
				.parent().css('display', 'none');
			
			//Fade in new tab
			self.options.tabs.eq(tab_index)
				.css('marginLeft', '0px')
				.parent().fadeIn('fast', function () {
						self.options.animation_in_progress = false;
					});
			
			self.options.tab_current = tab_index;
			
			//Moves images up by half of their height, this can't be done with css because image height is unknown
				if (self.options.image_reposition) {
					$('img', self.options.tabs.eq(self.options.tab_current)).each(function () {
						$(this).css('marginTop', '-' + (Math.floor($(this).height() / 2)) + 'px');
					});
				}
				
			//Set up navigation
				self.options.pos_current = 0;
				self.options.pos_max = $('li', self.options.tabs.eq(tab_index)).length - 6;
				if (self.options.pos_max < 0) self.options.pos_max = 0;
				
				self._ie6BackgroundFlickerFix(tab_index);				
				self.resetNavigation();
			
			//Reset scroller
				var tab = self.options.tabs.eq(self.options.tab_current);
				self.options.scroller.refresh(self.options.container, tab, $('li', tab));
		});
		
		return true;
	}
	else
	{
		return false;
	}
};
/*
 * Fix flicker when content is scrolled in IE6
 * Removes background form each element and assigns it to the 'content' element,
 * only if tab has enough elements to scroll
 */
CatalogScroller.prototype._ie6BackgroundFlickerFix = function (tab_index) {
	if (this.options.pos_max != 0 && $.browser.ie6) {
		var tab = this.options.tabs.eq(tab_index);
		if (tab[0]._ie6FlickerFixed) return;
		
		tab.css({
			'backgroundImage': tab.children('li').css('backgroundImage'),
			'backgroundPosition': 'left top',
			'backgroundRepeat': 'repeat-x'
		});
		
		tab.children('li').css('backgroundImage', 'none');
		tab[0]._ie6FlickerFixed = true;
	}
};
/* Initialize class */
CatalogScroller.prototype.init = function () {
	//Moves images up by half of their height
		if (this.options.image_reposition) {
			$('img', this.options.tabs.eq(this.options.tab_current)).each(function () {
				$(this).css('marginTop', '-' + (Math.floor($(this).height() / 2)) + 'px');
			});
		}
		
	//Calculating position
		this.options.pos_current = 0;
		this.options.pos_max = $('li', this.options.tabs.eq(this.options.tab_current)).length - 6;
		if (this.options.pos_max < 0) this.options.pos_max = 0;
		
		this._ie6BackgroundFlickerFix(0);
		this.resetNavigation();
	
	//Setting up scroller
		this.options.scroller = new Scroller();
		var tab = this.options.tabs.eq(this.options.tab_current);
		this.options.scroller.refresh(this.options.container, tab, $('li', tab));
	
	//Event handlers
		var self = this;
		if (this.options.next) this.options.next.click(function(){ self.next(); });
		if (this.options.previous) this.options.previous.click(function(){ self.previous(); });
		this.options.container.mousewheel(function (delta) {
			if (delta > 0)
			{
				var previous = self.previous();
				return !self.options.animation_in_progress && previous;
			}
			else
			{
				var next = self.next();
				return !self.options.animation_in_progress && next;
			}
		});
};


$(window).bind('load', function () {
	/* Catalogue first page */
		var catalog_list = $('div.catalogue-promo-list td').css('cursor', 'pointer');
		var catalogScroller = null;
		
		//If catalog list exists
		if (catalog_list[0])
		{
			var tab_index = 0;
			var tabs_not_open = true;
			
			//Assign tab index to each item
			catalog_list.each(function () {
				this.tab_index = tab_index;
				tab_index++;
			});
			
			//Handle click
			catalog_list.mouseover(function () {
				if (catalogScroller)
				{
					//changeTab function returns true if tab was changed successfully, otherwise false
					if (catalogScroller.changeTab(this.tab_index, tabs_not_open))
					{
						$('td', $(this).parent()).removeClass('active');
						$(this).addClass('active');
						tabs_not_open = false;
					}
					
					$('div.catalogue-promo-sublist').slideDown();
				}
				
				return false;
			}).click(function () {
				var a = $('a', this).eq(0);
				if (a[0]) {
					document.location = a[0].href;
				}
			});
		}
	
		//If catalog sublist exists
		var catalog_sublist = $('div.catalogue-promo-sublist').css('display', 'block');
		if (catalog_sublist[0])
		{
			var scroller_container = $('div.container', catalog_sublist);
			
			catalogScroller = new CatalogScroller({
				next: $('div.nav-next', catalog_sublist),		//'Next' link
				previous: $('div.nav-prev', catalog_sublist),	//'Previous' link
				tabs: $('div.content ul', scroller_container),	//List of tabs
				container: scroller_container					//Tab container node
			});
			
			catalog_sublist.css('display', 'none');
			
			//Event handlers
				$('li', scroller_container).click(function () {
					document.location = $('a', this).attr('href');
					return false;
				});
		}
		
		var brands_list = $('div.catalogue-brands-list');
		if (brands_list.length)
		{
			var scroller_container = $('div.catalogue-brands-list-wrapper', brands_list);
			
			catalogScroller = new CatalogScroller({
				next: $('div.nav-next', brands_list),		//'Next' link
				previous: $('div.nav-prev', brands_list),	//'Previous' link
				tabs: $('ul', brands_list),						//List of tabs
				container: scroller_container,					//Tab container node
				image_reposition: false
			});
			
			//Event handlers
				$('li', brands_list).click(function () {
					document.location = $('a', this).attr('href');
					return false;
				}).hover(function () {
					$(this).addClass('hover');
				}, function () {
					$(this).removeClass('hover');
				});
				
			//Image adjustment
				$('img', brands_list).imageReady(function () {
					var h = this.height;
					var h_offset = Math.floor((103 - h) / 2);
					
					$(this).css('marginTop', h_offset + 'px');
				});
			
			//Item horizontal position adjustment
				var li = $('li', brands_list)
				var cnt = li.length;
				if (cnt < 5) {
					li.addClass('item-count-' + cnt);
				}
		}
});

/**
 * Call callback on each image when it has been loaded succesfully
 * @param {Object} callback
 */
$.fn.imageReady = function (callback) {
	var callback = callback;
	var preload_list = [];
	var preload_img_count = 0;
	
	$(this).each(function () {
		if (this.complete)
			callback.call(this);
		else
			preload_list.push(this);
			
		preload_img_count = preload_list.length;
			
		if (preload_img_count) {
			setTimeout(function () {
				for(var i=0,j=preload_list.length; i<j; i++) {
					if (preload_list[i] && preload_list[i].complete) {
						callback.call(preload_list[i]);
						preload_list[i] = null;
						preload_img_count--;
					}
				}
				
				if (preload_img_count > 0) {
					setTimeout(arguments.callee, 10);
				}
			}, 10);
		}
	});
};