/**
 * Slidr.js
 * Copyright (c) Fluid Creativity, 2009
 *
 * Implements a content pager which slides horizontally between pages when the appopriate page link is activated
 */

var ContentPager = new Class({

	Implements: [Options, Events],

	options: {
	        pageLinksContainer: null,
	        pageLinksPosition: 'top',
		slideDuration: 300,
		transition: 'cubic',
		selectedPageClass: 'selected'
	},

	initialize: function (el, options) {
		this.el = $(el);
		this.setOptions(options);
		this.setupComponent();
	},

	setupComponent: function() {
		// Get pages from element
		var pages = this.el.getChildren();
		this.pageWidth = this.el.getStyle('width').toInt() + this.el.getStyle('padding-right').toInt();

		if (pages.length > 1) {
			this.el.setStyles({ 'overflow': 'hidden', 'position': 'relative', 'width': this.el.getStyle('width').toInt() });

			// Insert container element to house pages
			this.pager = new Element('div')
				.setStyles({ 'position': 'relative', 'width': this.getInternalWidth() })
				.adopt(pages.dispose())
				.inject(this.el);

			// Setup animation
			this.pager.set('tween', {
				duration: this.options.slideDuration,
				transition: this.options.transition
			});

			// Retrieve links container
			var pageLinksContainer = $(this.options.pageLinksContainer);
			if (!$defined(pageLinksContainer)) pageLinksContainer = this.el;

			// Create page links
			this.pageLinks = new Element('ul').inject(pageLinksContainer, this.options.pageLinksPosition)

			pages.each(function(page, i) {
				var padding = this.el.getStyle('padding-right').toInt();
				page.setStyles({ 'float': 'left', 'width': this.pageWidth - padding, 'padding-right': padding });

				this.pageLinks.adopt(
					new Element('li').adopt(
						new Element('a', {
							'text': i + 1,
							'rel': i,
							'title': 'Page ' + (i + 1) + ' of ' + pages.length,
							'href': '#'
						}).addEvent('click', function(e) {
							e.stop();

							this.switchPage(e.target.rel);
						}.bindWithEvent(this))
					)
				);
			}, this);

			this.switchPage(0);
		}
	},

	getInternalWidth: function() {
		return this.pageWidth * this.el.getChildren().length;
	},

	switchPage: function(page) {
		var pageLinkItems = this.pageLinks.getElements('li');

		pageLinkItems.removeClass(this.options.selectedPageClass);
		pageLinkItems[page].addClass(this.options.selectedPageClass);

		this.pager.tween('left', -this.pageWidth * page);
	},

	toElement: function() {
		return ($defined(this.pager) ? this.pager : this.el);
	}
});
