jQuery.fn.parallax = function(message, options) {
	// alias this as parallax
	var parallax = this;
	
	return parallax.each(function() {
		switch (message) {
			case "start":
					jQuery(this).find(".slice").parallaxSlice("start");
			  break;    
			case "stop":
					jQuery(this).find(".slice").parallaxSlice("stop");
			  break;
			default:
				// define defaults and override with options, if available
			  // by extending the default settings, we don't modify the argument
		
				options = jQuery.extend({
			     speed: 1000
			  }, options);
		
				parallax.each(function() {
					new jQuery.parallax(this, options);
				});
			
		}
	});
	
}

jQuery.parallax = function(element, options) {
	jQuery(element).addClass("parallax");
}



jQuery.fn.parallaxSlice = function(message, options) {
	// alias this as slice
	var slice = this;
	
	return slice.each(function() {
		switch (message) {
			case "start":
				jQuery.data(this, "status", "");
				jQuery.animateSlice(this, jQuery.data(this, "speed"));
			  break;    
			case "stop":
			  jQuery.data(this, "status", "stopping");
			  break;
			default:
				// define defaults and override with options, if available
			  // by extending the default settings, we don't modify the argument
		
				options = jQuery.extend({
			     speed: 1000
			  }, options);
		
				slice.each(function() {
					new jQuery.parallaxSlice(this, options);
				});
			
		}
	});
	
}

jQuery.parallaxSlice = function(element, options) {
	jQuery(element).addClass("slice");
	jQuery.data(element, "speed", options.speed);
}

jQuery.animateSlice = function(element, speed) {
	if (jQuery.data(element, "status") == "stopped") {
		return false;
	}
	var speed = speed || 1;
	var distance = 1 * speed; // percentage width
	var easing = "linear";
	
	var backgroundPosition =  jQuery(element).css("backgroundPosition").split(" ");
	var verticalPosition = backgroundPosition[1];

	switch (jQuery.data(element, "status")) {
		case "running" :
			jQuery(element).animate({"backgroundPosition": "+=" + distance + "% " + verticalPosition}, 1000, easing, function() {
				jQuery(element).css("backgroundPosition", "-=" + distance + "% " + verticalPosition);
				jQuery.animateSlice(element, speed);
			});
			break;
		case "stopping" :
			easing = "easeOutQuad";
			jQuery.data(element, "status", "stopped");
			jQuery(element).animate({"backgroundPosition": "+=" + distance + "% " + verticalPosition}, 1000 * 4, easing, function() {
				jQuery(element).css("backgroundPosition", "-=" + distance + "% " + verticalPosition);
			});
		  break;
		default: 
			// starting 
			easing = "easeInQuad";
			jQuery.data(element, "status", "running");
			jQuery(element).animate({"backgroundPosition": "+=" + distance + "% " + verticalPosition}, 1000 * 4, easing, function() {
				jQuery(element).css("backgroundPosition", "-=" + distance + "% " + verticalPosition);
				jQuery.animateSlice(element, speed);
			});
		  break;
	}
}

