var App = App || {};

App.ScrollGallery = function(options) 
{
	this.settings =
    {
		container: null,
    	arrows: false,
		mode: "block",
		pagesCount: null,
		currentPage: 1,
		mousewheel: false,
		autoScroll: false,
		autoScrollTo: "left",
		autoScrollPause: false,
		delta: 4,
		isLoaded: false,
		timer: null,
		params: {}
    };
	
	$.extend(this.settings, options);
	
	// vars
		   
	this._container = this.settings.container.find('.overflow');
	this._slider = this.settings.container.find('.js-slider');
	this._leftArrow = null;
	this._rightArrow = null;
	this._pagesCount = null;
	this._paginator = this.settings.container.find('.b-scroll-paginator');
	this._pagerBtns = null;

	this.init();
};

App.ScrollGallery.prototype = 
{
	/// PUBLIC
	
	init: function()
	{
		var me = this;
		
		if ( this.settings.container.hasClass('products_scroller_mini'))
		{
			this.settings.delta = 1;
		}
		
		if (this.settings.container.attr('rel'))
		{
			this.settings.delta = this.settings.container.attr('rel');
		}
		
		if (this.settings.container.attr('params'))
		{
			this.settings.params = eval('({' + this.settings.container.attr('params') + '})');
		}
		
		this._paginatorInit();
		
		if ( ( this.settings.autoScroll ) && ( this.settings.pagesCount > 1 ) )
		{
			this._autoScroll(1400);
			this._container.mouseenter(function()
			{
				me.settings.autoScrollPause = true;
				me._slider.stop();
			});
			
			this._container.mouseleave(function()
			{
				me.settings.autoScrollPause = false;
				clearTimeout(me.settings.timer);
				me._autoScroll(200);
			});
		} else {
			this.settings.autoScroll = false;
		}
		
		if ( this.settings.arrows )
		{
			
			this._leftArrow = this.settings.container.find('.js-scrollBack');
			this._rightArrow = this.settings.container.find('.js-scrollForward');
			
			this._leftArrow.click(function()
			{
					if (!$(this).hasClass('pager-disabled'))
						me._scrollToPage( Math.ceil(me.settings.currentPage)-1 );
					
					return false;
			});
			
			this._rightArrow.click(function()
			{
					if (!$(this).hasClass('pager-disabled'))
						me._scrollToPage( Math.floor(me.settings.currentPage)+1 );
					
					return false;
			});
			
			this._slider.find('img.poster-pic').live('mouseenter', function()
			{
				me._posterZoomIn(this);
			}).live('mouseleave', function()
			{
				me._posterZoomOut(this);
			});
			
			this._checkArrows(0);
			
		}
		
		// Промотка ленты страницами
	
		this._pagerBtns.click(function()
		{
			if ( !$(this).hasClass('active') )
			{
				me._scrollToPage( $(this).attr('page') );
				me.settings.autoScrollPause = true;
			}
		});
		
		// Промотка ленты колесом мыши
		
		if ( this.settings.mousewheel )
		{
			
			this._container.mousewheel(function(event, delta ) {
				
				
				if ( (delta > 0) && ( me.settings.currentPage-1 > 0 ) ) {
					me._scrollToPage( Math.ceil(me.settings.currentPage)-1 );					
				} else if ( (delta < 0) && ( me.settings.currentPage+1 <= me.settings.pagesCount ) ) {
					me._scrollToPage( Math.floor(me.settings.currentPage)+1 );
				}
				
				return false;
						
			});
			
		}

	},
	
	/// PRIVATE
	
	_refresh: function()
	{
		this.settings.pagesCount = Math.ceil(this._slider.width()/(this._container.width()+this.settings.delta+3));
	},
	
	// Инициализация пэйджинатора
	_paginatorInit: function()
	{
		this._refresh();
	
		//this._slider.width( this.settings.pagesCount*(this._container.width()+this.settings.delta) );
		
		for (i=1; i<= this.settings.pagesCount; i++) {
			this._paginator.append('<i class="squire" page="' + i +  '"></i>');
		}
			   
		this._paginator.find('.squire:first').addClass('active');
		this._pagerBtns = this._paginator.find('.squire');
		
		if ( this.settings.pagesCount < 2 )
		{
			this._paginator.addClass('hidden');
		}
		
	},
	
	// Метод скрытия/показа стрелок прокрутки  
	_checkArrows: function(curLeft)
	{
		
		if ( curLeft >= 0 ) {
			this._leftArrow.addClass('pager-disabled');
		} else {
			this._leftArrow.removeClass('pager-disabled');
		}
		
		if ( this.settings.pagesCount == this.settings.currentPage ) {
			this._rightArrow.addClass('pager-disabled');
		} else {
			this._rightArrow.removeClass('pager-disabled');
		}
		
   },
   
   // Скролить на страницу  
   _scrollToPage: function(page, mode)
   {
	   var dur = 600;
	   var me = this;
	   
	   if (mode == "auto")
	   {
	   		dur = 5600;
			this._slider.addClass('js-autoScrolling');
	   } else {
		   clearTimeout(this.settings.timer);
	   }
	   
	   if ((this._slider.not(":animated").length != 0) || (this._slider.hasClass('js-autoScrolling')) )
	   {
	   
			if (this.settings.pagesCount == page)
			{
				this._loadItems(page);
			}
		
			var newLeft = -this._container.width()*( page - 1 );
			if ( page != 1 )
			{
				newLeft -= this.settings.delta*( page - 1 );
			}
			this._slider.stop();
			this._slider.animate({left: newLeft + "px"}, { duration: dur, easing: "easeInOutQuad", complete: function() { 
				$(this).removeClass('js-autoScrolling'); 
				me.settings.currentPage = page;
				if (mode != "auto")
				{
					me._autoScroll(2000);
				}
				
				if ( me.settings.arrows )
				{
					me._checkArrows(newLeft);
		
				}
			} } );
			this.settings.currentPage += (page-this.settings.currentPage)/2;
			this._pagerBtns.removeClass('active');
			$(this._pagerBtns[page-1]).addClass('active');
			if ( this.settings.arrows )
			{
				this._checkArrows(newLeft);
	
			}
	   }
		
   },
   
   // Подгрузка элементов
   _loadItems: function(page)
   {
	   	var me = this;
	   
		this.settings.params.currentPage = page;
	   
		if (!this.settings.isLoaded)
		{
			$.ajax({
			   	type: "POST",
			   	url: "/ajax/productsscroller/",
				data: this.settings.params,
				success: function(response){
					response = eval('(' + response + ')');
					
					if (response.last)
						me.settings.isLoaded = true;
						
					me._slider.append(response.html).ready(function()
					{
						me._refresh();
						me._checkArrows(-me._container.width()*(page-1));
					});
				}
			});
		}
	
   },
   
   // Zoom превьюхи товара
   _posterZoomIn: function(sender)
   {
	   var originHeight = $(sender).attr('h')*1;
	   $(sender).animate({height: (originHeight+20) + "px", marginTop: "-10px"}, { queue:false, duration:200 });
   },
   
   _posterZoomOut: function(sender)
   {
	   var originHeight = $(sender).attr('h')*1;
	   $(sender).animate({height: originHeight + "px", marginTop: 0}, { queue:false, duration:200 });
   },
   
   // Автоматическая цикличная прокрутка галлереи  
   _autoScroll: function(time)
   {
	   var me = this;
	   
	   this.settings.timer = setTimeout(function()
		{
			if (!me.settings.autoScrollPause)
			{
				if (me.settings.currentPage == 1)
				{
				   me.settings.autoScrollTo = "left";
				}
			   
				if (me.settings.currentPage == me.settings.pagesCount)
				{
				   me.settings.autoScrollTo = "right";
				}
				
				if (me.settings.autoScrollTo == "left")
				{
					me._scrollToPage( Math.floor(me.settings.currentPage)+1, "auto" );
				} else {
					me._scrollToPage( Math.ceil(me.settings.currentPage)-1, "auto" );
				}
				
				me._autoScroll(7000);
			}
			
			
			
		}, time);
   }
      
	
};

$.fn.ScrollGallery = function(options)
{
	this.each(function()
	{
		// options
		options = $.extend(options, { container: $(this) });
		
		// create
		var ScrollGallery = new App.ScrollGallery(options);
	
	});
};

$(function()
{
	$('.js-scroller').ScrollGallery({arrows: true, mousewheel: true, autoScroll: true});
});

