/*
http://www.tumuski.com/code/clumpy/
Copyright (c) 2009 Thomas Peri

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

// Good Parts plus Browser:
/*jslint
	white: true, undef: true, nomen: true, eqeqeq: true, plusplus: true,
	bitwise: true, regexp: true, onevar: true, newcap: true,
	browser: true
*/

/**
 * Model incremental asynchronous processes after traditional loops.
 * version 2009-03-01
 */
var Clumpy = (function () {

	var constructor, // becomes Clumpy
		
		// private "class" functions
		fn, nothing, num, spawn;

	/**
	 * Construct an object for modeling asynchronous loops.
	 */
	constructor = function (options) {
	
		var self = this,
		
			// public methods (more in the prototype below)
			break_loop, continue_loop, label, for_loop, 
			once, pause, resume, set, wait, 
			
			// private instance functions
			advance, clump, enqueue, findLoop, iterate, 
			perform, schedule, setNow, wait_callback, 
			
			// private instance variables
			first, nextLabel, paused, queue, waiting,
			
			// user options
			between, delay, duration;
		
	
		// Public Methods
		
		/**
		 * Emulate the 'break' keyword inside a Clumpy loop.
		 */
		break_loop = function (label) {
			return once(function () {
				findLoop(label);
				queue.head.loop.finished = true;
			});
		};
		
		/**
		 * Emulate the 'continue' keyword inside a Clumpy loop.
		 */
		continue_loop = function (label) {
			return once(function () {
				findLoop(label);
			});
		};
		
		/**
		 * Label the next loop.  Must precede a loop.
		 */
		label = function (newLabel) {
			nextLabel = newLabel;
			return self;
		};
		
		/**
		 * Enqueue the supplied statements function and associated functions
		 * to be executed in the fashion of a 'for' loop.
		 */
		for_loop = function (init, test, inc, statements) {
			// All the other loop methods are written in terms of this one ultimately.
			enqueue(statements, {
				label: nextLabel,
				init: init,
				test: test,
				inc: inc,
				initialized: false,
				finished: false
			});
			return self;
		};
		
		/**
		 * Enqueue the supplied statements function to be executed exactly once.
		 */
		once = function (statements) {
			enqueue(statements, null);
			return self;
		};
	
		/**
		 * Perform an asynchronous action exactly once,
		 * and wait for the callback before proceeding.
		 */
		wait = function (statements) {
			return once(function () {
				waiting = true;
				statements(wait_callback);
			});
		};
		
		/**
		 * Freeze this Clumpy instance in its tracks.
		 */
		pause = function () {
			paused = true;
			return self;
		};
		
		/**
		 * Resume after pause.
		 */
		resume = function () {
			if (paused) {
				paused = false;
				if (!waiting) {
					schedule();
				}
			}
			return self;
		};
		
		/**
		 * Set some options.
		 */
		set = function (options) {
			return once(function () {
				setNow(options);
			});
		};
		
		
		// Private Functions
		
		/*
		 * Advance to the next unit or loop iteration.
		 */
		advance = function () {
			var loop;
			
			// Keep advancing until we get a good one.
			while (true) {
			
				// If the current unit is a loop that hasn't finished,
				// just increment the loop.
				loop = queue.head.loop;
				if (loop && !loop.finished) {
					loop.inc.call();
					
				// If it's a one-off or a loop that has finished,
				// proceed to the next unit.
				} else {
					queue.head = queue.head.next;
					
					if (!queue.head) {
						// If there is no next unit in this queue, clear the tail too.
						queue.tail = null;
						
						// If there's a parent queue to back out to,
						// then back out and advance again.
						if (queue.parent) {
							queue = queue.parent;
							continue;
						}
					}
					
					// If there is no parent queue, and there are no more units,
					// then the current clump will exit without scheduling.
				}
				
				// Stop advancing.
				break;
			}
		};
	
		/*
		 * Do a synchronous clump of statements blocks, 
		 * and schedule another clump after a timeout.
		 */
		clump = function () {
			var beginning = new Date().getTime();
			
			while (true) {
				iterate();

				// If there's nothing left to do after this iteration,
				// then don't bother calling between or schedule.
				if (!queue.head) {
					break;
				}
				
				// If this iteration caused this Clumpy instance to be
				// paused or waiting, then don't schedule a new clump right now,
				// but do call between, because we expect another clump 
				// eventually.
				if (paused || waiting) {
					between();
					break;
				}
				
				// If this clump is over its time limit, schedule a new one.
				if (new Date().getTime() - beginning > duration) {
					between();
					schedule();
					break;
				}
			}
		};
		
		/*
		 * The callback for wait.
		 */
		wait_callback = function () {
			if (waiting) {
				waiting = false;
				if (!paused) {
					schedule();
				}
			}
		};
		
		/*
		 * Put something -- either a loop or not -- 
		 * into the Clumpy queue to be done eventually.
		 */
		enqueue = function (statements, loop) {
			var unit;
			nextLabel = null;
			unit = {
				loop: loop,
				statements: statements,
				next: null,
				parent: null
			};
			
			// If this is the first unit that was enqueued inside a statements
			// block, start a new queue using the current one as its parent.
			if (first) {
				first = false;
				queue = spawn(queue);
			}
	
			// If there's anything in the (now-)current queue, 
			// add the new unit to the end of it.
			if (queue.tail) {
				queue.tail.next = unit;
				queue.tail = unit;
				
			// Otherwise, mark this new unit as the beginning and end.
			} else {
				queue.head = unit;
				queue.tail = unit;
				
				// If this is the beginning of the outermost queue,
				// the the timeouts need to be started.
				if (!queue.parent) {
					schedule();
				}
			}
		};
		
		/*
		 * Back out to the nearest loop, or if a label is supplied,
		 * the nearest loop with that label.
		 */
		findLoop = function (label) {
			// Back out until we find a loop.
			while (!queue.head.loop) {
				queue = queue.parent;
				if (!queue) {
					throw "'break_loop' and 'continue_loop' can only be used inside a Clumpy loop!";
				}
			}
			if (label) {
				// Keep backing out until we find the loop with this label.
				while (!queue.head.loop || queue.head.loop.label !== label) {
					queue = queue.parent;
					if (!queue) {
						throw "Clumpy couldn't find the label '" + label + "'.";
					}
				}
			}
		};
		
		/*
		 * Perform the current code unit.
		 */
		iterate = function () {
			var loop;
			
			queue.begun = true;
			
			loop = queue.head.loop;
			if (loop) {
				if (!loop.initialized) {
					loop.init.call();
					loop.initialized = true;
				}
				if (loop.test.call()) {
					perform();
				} else {
					loop.finished = true;
				}
			} else {
				perform();
			}
			
			// Advance only if the latest statements function 
			// didn't push a new queue that hasn't begun yet.
			if (queue.begun) {
				advance();
			}
		};
		
		
		/*
		 * Perform the current node's statements.
		 */
		perform = function () {
			first = true;
			queue.head.statements.call();
			first = false;
		};
		
		/*
		 * Add the next clump to the browser's event queue.
		 */
		schedule = function () {
			if (queue.head) {
				setTimeout(clump, delay);
			}
		};
		
		/*
		 * Set some options NOW.
		 */
		setNow = function (options) {
			options = options || {};
			
			function defined(key) {
				return typeof options[key] !== 'undefined';
			}
			if (defined('between')) {
				between = fn(options.between);
			}
			if (defined('delay')) {
				delay = num(options.delay, 0);
			}
			if (defined('duration')) {
				duration = num(options.duration, 0);
			}
		};
		
		
		
		// Set initial values for private instance variables.
		first = false;
		nextLabel = null;
		paused = false;
		queue = spawn(null);
		waiting = false;
	
	
		// Set defaults for user options.
		between = nothing;
		delay = 0;
		duration = 100;
		
	
		// User can set options as argument to constructor.
		setNow(options);
		
		
		// Publicize public methods.
		this.break_loop = break_loop;
		this.continue_loop = continue_loop;
		this.label = label;
		this.for_loop = for_loop;
		this.once = once;
		this.wait = wait;
		this.pause = pause;
		this.resume = resume;
		this.set = set;
		
	};
	
	/**
	 * Enqueue the supplied statements and associated test function
	 * to be executed in the fashion of a 'do...while' loop.
	 */
	constructor.prototype.
	do_while_loop = function (statements, test) {
		var first = true;
		return this.while_loop(
			function () {
				var proceed = first || test();
				first = false;
				return proceed;
			},
			statements);
	};
	
	// Tolerate unfiltered for...in in just this one method.  It needs to
	// be unfiltered in order to emulate the real behavior of a for...in loop.
	/*jslint forin: true */
	
	/**
	 * Enqueue the supplied statements function to be executed in the 
	 * fashion of a 'for...in' loop, iterating over the supplied object.
	 */
	constructor.prototype.
	for_in_loop = function (obj, statements) {
		var i, key, keys = [];
		for (key in obj) {
			keys.push(key);
		}
		return this.for_loop(
			function () {
				i = 0;
			},
			function () {
				return i < keys.length;
			},
			function () {
				i += 1;
			},
			function () {
				statements(keys[i]);
			}
		);
	};
	
	/*jslint forin: false */	

	/**
	 * Enqueue a sleep of delay milliseconds.
	 */
	constructor.prototype.
	sleep = function (delay) {
		return this.wait(function (callback) {
			setTimeout(callback, delay);
		});
	};
	
	/**
	 * Enqueue the supplied statements and associated test function
	 * to be executed in the fashion of a 'while' loop.
	 */
	constructor.prototype.
	while_loop = function (test, statements) {
		return this.for_loop(
			nothing,
			test,
			nothing,
			statements);
	};


	/*
	 * Clean an argument that's supposed to be a function.
	 */
	fn = function (value) {
		return typeof value === 'function' ? value : nothing;
	};

	/*
	 * Any empty function.  Go ahead, post this to The Daily WTF.
	 */
	nothing = function () {
	};

	/*
	 * Clean an argument that's supposed to be a number.
	 */
	num = function (value, min) {
		value = parseInt(value, 10);
		return typeof min === 'number' ? Math.max(min, value) : value;
	};

	/*
	 * Start a new queue, optionally specifying the parent.
	 */
	spawn = function (parent) {
		return {
			begun: false,
			parent: parent,
			head: null,
			tail: null
		};
	};


	return constructor;

})();
