var WMX = WMX || { };

WMX.Showroom = Class.create({
	initialize: function(parentDiv, photosPerPage)
	{
		$$('.paging').each(function(e) { e.remove(); });

		this.paging = new Element('div').addClassName('paging');
		this.parentContainer = $(parentDiv);

		var photoArray = this.parentContainer.select('.evoxVehicle');

		this.pages = new Array(Math.ceil(photoArray.length/photosPerPage));
		this.currentIndex = -1;

		for(i=0; i < this.pages.length; i++)
		{
			var newDiv = new Element('div', { 'class': 'showroomPage' });

			var contentToInsert = photoArray.eachSlice(photosPerPage)[i];

			contentToInsert.each(function(s) {
				newDiv.insert(s);
			});

			this.pages[i] = newDiv;
			this.pages[i].hide();

			this.parentContainer.insert(newDiv);
		}

		this.first = new Element('span').addClassName('firstPage').update('&lt;&lt; First').observe('click', this._skipToPage.bind(this, 0));
		this.prev = new Element('span').addClassName('prevPage').update('&lt; Prev').observe('click', this._changePage.bind(this, -1));
		this.next = new Element('span').addClassName('nextPage').update('Next &gt;').observe('click', this._changePage.bind(this, 1));
		this.last = new Element('span').addClassName('lastPage').update('Last &gt;&gt;').observe('click', this._skipToPage.bind(this, this.pages.length - 1));

		this.paging.insert(this.first).insert(this.prev);

		this.pageLinks = new Array();

		for(i = 0; i < this.pages.length; i++)
		{
			var pageNumber = new Element('span').addClassName('pagenumber').update(i + 1).observe('click', this._skipToPage.bind(this, i));
			this.paging.insert(pageNumber);
			this.pageLinks[i] = pageNumber;
		}

		this.paging.insert(this.next).insert(this.last);

		this.parentContainer.up('.evoxvirtualshowroom').insert(this.paging);
		
		this._skipToPage(0);

	},

	_changePage: function(direction) {
		this._skipToPage(this.currentIndex + direction);
	},

	_skipToPage: function(newIndex) {
		$$('.evoxvirtualshowroom .inactive').each(function(s) {
			s.removeClassName('inactive');
		});
		
		if (newIndex != this.currentIndex && newIndex >= 0 && newIndex < this.pages.length)
		{
			if (this.currentIndex >= 0)
			{
				new Effect.Fade(this.pages[this.currentIndex], { duration: 0.25, queue: { position: 'end', scope: 'wmxShowroom' } });
			}
			new Effect.Appear(this.pages[newIndex], { duration: 0.25, queue: { position: 'end', scope: 'wmxShowroom' } });

			this.currentIndex = newIndex;
		}
		
		if (this.pageLinks.length > 0)
		{
			this.pageLinks[this.currentIndex].addClassName('inactive');
		}
		
		if(this.currentIndex == 0)
		{
			this.first.addClassName('inactive');
			this.prev.addClassName('inactive');
		}
		
		if(this.currentIndex == this.pages.length - 1)
		{
			this.next.addClassName('inactive');
			this.last.addClassName('inactive');
		}
	}
});