// Handle scroller
var pageController = {

	// Page width
	width: 0,
	
	// Defaults
	defaults: {
		direction: 'left',
		easing: 'easeOutQuint',
		duration: 1000
	},

	// Show a page
	show: function(currentPage, newPage, options) {
	
		// Options
		var opts = $.extend({}, pageController.defaults, options);

		// Scroll
		pageController.scroll(currentPage, newPage, opts);
	
	},
	
	// Scroll to new page
	scroll: function(currentPage, newPage, opts) {
	
		// Pre-process
		pageController.preProcess(currentPage, newPage, opts);
		
		// Final scroll position
		var finalScroll = 0;
		if (opts.direction == 'left') finalScroll = pageController.width;

		// Scroll
		currentPage.scroller.animate({ scrollLeft: finalScroll }, {
			queue: false, 
			duration: opts.duration, 
			easing: opts.easing, 
			complete: function() {
				pageController.postProcess(currentPage, newPage, opts);
			}
		});

		// Animate height change
		currentPage.scroller.animate({ height: newPage.element.outerHeight() }, {
			queue: false, 
			duration: opts.duration,
			easing: opts.easing
		});
	
	},
	
	// Pre-Processing
	preProcess: function(currentPage, newPage, opts) {
		
		// Get width of window
		pageController.width = $(document).width();
		
		// Fix for IE 6
		var IE6 = (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) && (navigator.userAgent.toLowerCase().indexOf('msie 7') == -1);
		if (IE6) pageController.width -= 21;
		
		// Wrap page in wrapper
		if (!currentPage.wrap) {
			currentPage.element.wrap($('<div class="page_wrap"></div>'));
			currentPage.wrap = currentPage.element.parent();
		}
		
		// Wrap wrapper in scroller
		if (!currentPage.scroller) {
			currentPage.wrap.wrap($('<div class="page_scroller"></div>'));
			currentPage.scroller = currentPage.wrap.parent();
		}
		
		// Process
		currentPage.scroller.css({ overflow: 'hidden', height: currentPage.element.outerHeight() });
		currentPage.wrap.css({ overflow: 'hidden', width: 2 * pageController.width });
		
		// Load in page
		if (opts.direction == 'left') {
			currentPage.wrap.append(newPage.element);
		} else {
			currentPage.wrap.prepend(newPage.element);
			currentPage.scroller[0].scrollLeft = pageController.width;
		}
		
		// Set page widths and style
		currentPage.element.css({width: pageController.width, float: 'left'});
		newPage.element.css({width: pageController.width, float: 'left'});
		
		// After insert Callback
		if (opts.oninsert) opts.oninsert(newPage);
	
	},
	
	// Post-Processing
	postProcess: function(currentPage, newPage, opts) {

		// Get current page
		newPage.element.css({float: 'none', width: 'auto'});

		// Remove wrapper and scroller
		currentPage.scroller.before(newPage.element);
		currentPage.wrap.remove();
		currentPage.wrap = null;
		currentPage.scroller.remove();
		currentPage.scroller = null;
		
		// Complete Callback
		if (opts.complete) opts.complete();
	
	}

};
