(function() {
	var methods = {
		init: function(options) {
			var settings = {speed: 500};
			if (typeof options == 'object') {
				$.extend(settings, options);
			}
			
			return this.each(function() {
				// private vars
				var settings = {};
				if (typeof options == 'object') {
					$.extend(settings, options);
				}
				var target = $(this);
				var container = $('> div:first', this);
				var top = 0;
				
				// private functions
				function scrollItems(distance, duration, complete) {
					container.translate({y: -distance}, duration, complete);
				}

				function scrollToPage(page, bottomAlign) {
					if (page.length > 0) {
						var y = page.offset().top - container.offset().top;
						if (bottomAlign) {
							y += page.height() - target.height();
						}
						if (bottomAlign) {
							scrollItems(y, settings.speed);
						} else {
							scrollItems(y, settings.speed, function() {
								if ((this == window) && (typeof settings.complete == 'function')) {
									settings.complete(page);
								}
							});
						}
					}
				}
				
				target.swipe({
					triggerOnTouchEnd : true,
					allowPageScroll: 'horizontal',
					threshold: 200,
					swipeStatus: function(event, phase, direction, distance) {
						var currentPage = $(event.target).closest('.content');
						if (currentPage.length == 0) {
							return;
						}
						if (phase == 'start') {
							top = target.offset().top - container.offset().top;
						} else
						if (phase == 'move' && (direction == 'up' || direction == 'down')) {
							if (direction == 'up') {
								scrollItems(top + distance, 0);
							} else
							if (direction == 'down') {
								scrollItems(top - distance, 0);
							}
						} else
						if ((currentPage.offset().top > target.offset().top) ||  (currentPage.offset().top + currentPage.height() < target.offset().top + target.height())) {
							var page;
							var bottomAlign = false;
							if (phase == 'cancel') {
								bottomAlign = (direction == 'up');
								scrollToPage(currentPage, bottomAlign);
							} else
							if (phase == 'end') {
								if (direction == 'up') {
									page = currentPage.nextAll('.content:first');
									bottomAlign = (page.length == 0);
								} else
								if (direction == 'down') {
									page = currentPage.prevAll('.content:first');
								}
								if (page.length == 0) {
									page = currentPage;
								}
								scrollToPage(page, bottomAlign);
							}
						}
					}
				});
			});
		}
	}
	
	$.fn.pageSlider = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else
		if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' +  method + ' does not exist on jQuery.pageSlider');
		}
		return false;
	}
})(jQuery);
