<commit_before>/**
 * JavaScript file to included by the test suite page that it loaded
 * inside the iframe on the "run" pages. This injection must be done
 * by the guest page, it can't be loaded by TestSwarm.
 * Example:
 * - https://github.com/jquery/jquery/blob/master/test/data/testrunner.js
 * - https://github.com/jquery/jquery/blob/master/test/index.html
 *
 * @author John Resig, 2008-2011
 * @author Timo Tijhof, 2012
 * @since 0.1.0
 * @package TestSwarm
 */
/*global QUnit, Test, JSSpec, JsUnitTestManager, SeleniumTestResult, LOG, doh, Screw, mocha */
(function ( undefined ) {
	var DEBUG, doPost, search, url, index, submitTimeout, curHeartbeat,
		beatRate, testFrameworks, onErrorFnPrev;

	DEBUG = false;

	doPost = false;
	search = window.location.search;
	index = search.indexOf( 'swarmURL=' );
	submitTimeout = 5;
	beatRate = 20;

	try {
		doPost = !!window.parent.postMessage;
	} catch ( e ) {}

	if ( index !== -1 ) {
		url = decodeURIComponent( search.slice( index + 9 ) );
	}

	if ( !DEBUG && ( !url || url.indexOf( 'http' ) !== 0 ) ) {
		return;
	}

	// Prevent blocking things from executing
	if ( !DEBUG ) {
		window.print = window.confirm = window.alert = window.open = function () {};
	}

	/** Utility functions **/

	function debugObj( obj ) {
		var i, str = '';
		for ( i in obj ) {
			str += ( str ? '\n' : '' ) + i + ':\n\t ' + obj[i];
		}
		return str;
	}

	function remove( elem ) {
		if ( typeof elem === 'string' ) {
			elem = document.getElementById( elem );
		}

		if ( elem ) {
			elem.parentNode.removeChild( elem );
		}
	}

	function trimSerialize( doc ) {
		var scripts, root, cur, links, i, href;
		doc = doc || document;

		scripts = doc.getElementsByTagName( 'script' );
		while ( scripts.length ) {
			remove( scripts[0] );
		}

		root = window.location.href.replace( /(https?:\/\/.*?)\/.*/, '$1' );
		cur = window.location.href.replace( /[^\/]*$/, '' );

		links = doc.getElementsByTagName( 'link' );
		for ( i = 0; i < links.length; i += 1 ) {
			href = links[i].href;
			if ( href.indexOf( '/' ) === 0 ) {
				href = root + href;
			} else if ( !/^https?:\/\//.test( href ) ) {
				href = cur + href;
			}
			links[i].href = href;
		}

		return ( '' + doc.documentElement.innerHTML + '' )
			.replace( /\s+/g, ' ' );
	}

	function submit( params ) {
		var form, i, input, key, paramItems, parts, query;

		if ( curHeartbeat ) {
			clearTimeout( curHeartbeat );
		}

		paramItems = (url.split( '?' )[1] || '' ).split( '&' );

		for ( i = 0; i < paramItems.length; i += 1 ) {
			if ( paramItems[i] ) {
				parts = paramItems[i].split( '=' );
				if ( !params[ parts[0] ] ) {
					params[ parts[0] ] = parts[1];
				}
			}
		}

		if ( !params.action ) {
			params.action = 'saverun';
		}

		if ( !params.report_html ) {
			params.report_html = window.TestSwarm.serialize();
		}

		if ( DEBUG ) {
			window.alert( debugObj( params ) ) ;
		}

		if ( doPost ) {
			// Build Query String
			query = '';

			for ( key in params ) {
				query += ( query ? '&' : '' ) + key + '=' + encodeURIComponent( params[key] );
			}

			if ( !DEBUG ) {
				window.parent.postMessage( query, '*' );
			}

		} else {
			form = document.createElement( 'form' );
			form.action = url;
			form.method = 'POST';

			for ( i in params ) {
				input = document.createElement( 'input' );
				input.type = 'hidden';
				input.name = i;
				input.value = params[i];
				form.appendChild( input );
			}

			if ( DEBUG ) {
				window.alert( url );

			} else {
				// Watch for the result submission timing out
				setTimeout(function () {
					submit( params );
				}, submitTimeout * 1000);

				document.body.appendChild( form );
				form.submit();
			}
		}
	}

	function detectAndInstall() {
		var key;
		for ( key in testFrameworks ) {
			if ( testFrameworks[key].detect() ) {
				testFrameworks[key].install();
				return key;
			}
		}
		return false;
	}

	// Preserve other handlers
	onErrorFnPrev = window.onerror;

	// Cover uncaught exceptions
	// Returning true will surpress the default browser handler,
	// returning false will let it run.
	window.onerror = function ( error, filePath, linerNr ) {
		var ret = false, report;
		if ( onErrorFnPrev ) {
			ret = onErrorFnPrev( error, filePath, linerNr );
		}

		// Treat return value as window.onerror itself does,
		// Only do our handling if not surpressed.
		if ( ret !== true ) {
			report = document.createElement( 'div' );
			report.innerHTML = '
[TestSwarm] window.onerror:
';
			report.appendChild( document.createTextNode( error ) );
			report.appendChild( document.createElement( 'br' ) );
			report.appendChild( document.createTextNode( 'in ' + filePath + ' on line ' + linerNr ) );
			document.body.appendChild( report );
			submit({ fail: 0, error: 1, total: 1 });

			return false;
		}

		return ret;
	};

	// Expose the TestSwarm API
	window.TestSwarm = {
		submit: submit,
		heartbeat: function () {
			if ( curHeartbeat ) {
				clearTimeout( curHeartbeat );
			}

			curHeartbeat = setTimeout(function () {
				submit({ fail: -1, total: -1 });
			}, beatRate * 1000);
		},
		serialize: function () {
			return trimSerialize();
		}
	};

	testFrameworks = {
		// QUnit (by jQuery)
		// http://docs.jquery.com/QUnit
		'QUnit': {
			detect: function () {
				return typeof QUnit !== 'undefined';
			},
			install: function () {
				QUnit.done = function ( results ) {
					submit({
						fail: results.failed,
						error: 0,
						total: results.total
					});
				};

				QUnit.log = window.TestSwarm.heartbeat;
				window.TestSwarm.heartbeat();

				window.TestSwarm.serialize = function () {
					var ol, i;

					// Show any collapsed results
					ol = document.getElementsByTagName( 'ol' );
					for ( i = 0; i < ol.length; i += 1 ) {
						ol[i].style.display = 'block';
					}

					return trimSerialize();
				};
			}
		},

		// UnitTestJS (Prototype, Scriptaculous)
		// https://github.com/tobie/unittest_js
		'UnitTestJS': {
			detect: function () {
				return typeof Test !== 'undefined' && Test && Test.Unit && Test.Unit.runners;
			},
			install: function () {
				/*jshint loopfunc:true */
				var total_runners = Test.Unit.runners.length,
					cur_runners = 0,
					total = 0,
					fail = 0,
					error = 0,
					i;

				for ( i = 0; i < Test.Unit.runners.length; i += 1 ) {
					// Need to proxy the i variable into a local scope,
					// otherwise all the finish-functions created in this loop
					// will refer to the same i variable..
					(function ( i ) {
						var finish, results;

						finish = Test.Unit.runners[i].finish;
						Test.Unit.runners[i].finish = function () {
							finish.call( this );

							results = this.getResult();
							total += results.assertions;
							fail += results.failures;
							error += results.errors;

							cur_runners += 1;
							if ( cur_runners === total_runners ) {
								submit({
									fail: fail,
									error: error,
									total: total
								});
							}
						};
					}( i ) );
				}
			}
		},

		// JSSpec (MooTools)
		// http://jania.pe.kr/aw/moin.cgi/JSSpec
		// https://code.google.com/p/jsspec/
		'JSSpec': {
			detect: function () {
				return typeof JSSpec !== 'undefined' && JSSpec && JSSpec.Logger;
			},
			install: function () {
				var onRunnerEnd = JSSpec.Logger.prototype.onRunnerEnd;
				JSSpec.Logger.prototype.onRunnerEnd = function () {
					var ul, i;
					onRunnerEnd.call( this );

					// Show any collapsed results
					ul = document.getElementsByTagName( 'ul' );
					for ( i = 0; i < ul.length; i += 1 ) {
						ul[i].style.display = 'block';
					}

					submit({
						fail: JSSpec.runner.getTotalFailures(),
						error: JSSpec.runner.getTotalErrors(),
						total: JSSpec.runner.totalExamples
					});
				};

				window.TestSwarm.serialize = function () {
					var ul, i;
					// Show any collapsed results
					ul = document.getElementsByTagName( 'ul' );
					for ( i = 0; i < ul.length; i += 1 ) {
						ul[i].style.display = 'block';
					}

					return trimSerialize();
				};
			}
		},

		// JSUnit
		// http://www.jsunit.net/
		// Note: Injection file must be included before the frames
		// are document.write()d into the page.
		'JSUnit': {
			detect: function () {
				return typeof JsUnitTestManager !== 'undefined';
			},
			install: function () {
				var _done = JsUnitTestManager.prototype._done;
				JsUnitTestManager.prototype._done = function () {
					_done.call( this );

					submit({
						fail: this.failureCount,
						error: this.errorCount,
						total: this.totalCount
					});
				};

				window.TestSwarm.serialize = function () {
					return '
' + this.log.join( '\n' ) + '
';
				};
			}
		},

		// Selenium Core
		// http://seleniumhq.org/projects/core/
		'Selenium': {
			detect: function () {
				return typeof SeleniumTestResult !== 'undefined' && typeof LOG !== 'undefined';
			},
			install: function () {
				// Completely overwrite the postback
				SeleniumTestResult.prototype.post = function () {
					submit({
						fail: this.metrics.numCommandFailures,
						error: this.metrics.numCommandErrors,
						total: this.metrics.numCommandPasses + this.metrics.numCommandFailures + this.metrics.numCommandErrors
					});
				};

				window.TestSwarm.serialize = function () {
					var results = [], msg;
					while ( LOG.pendingMessages.length ) {
						msg = LOG.pendingMessages.shift();
						results.push( msg.type + ': ' + msg.msg );
					}

					return '
' + results.join( '\n' ) + '
';
				};
			}
		},

		// Dojo Objective Harness
		// http://docs.dojocampus.org/quickstart/doh
		'DOH': {
			detect: function () {
				return typeof doh !== 'undefined' && doh._report;
			},
			install: function () {
				var _report = doh._report;
				doh._report = function () {
					_report.apply( this, arguments );

					submit({
						fail: doh._failureCount,
						error: doh._errorCount,
						total: doh._testCount
					});
				};

				window.TestSwarm.serialize = function () {
					return '
' + document.getElementById( 'logBody' ).innerHTML + '
';
				};
			}
		},

		// Screw.Unit
		// https://github.com/nathansobo/screw-unit
		'Screw.Unit': {
			detect: function () {
				return typeof Screw !== 'undefined' && typeof jQuery !== 'undefined' && Screw && Screw.Unit;
			},
			install: function () {
				$(Screw).bind( 'after', function () {
					var	passed = $( '.passed' ).length,
						failed = $( '.failed' ).length;
					submit({
						fail: failed,
						error: 0,
						total: failed + passed
					});
				});

				$( Screw ).bind( 'loaded', function () {
					$( '.it' )
						.bind( 'passed', window.TestSwarm.heartbeat )
						.bind( 'failed', window.TestSwarm.heartbeat );
					window.TestSwarm.heartbeat();
				});

				window.TestSwarm.serialize = function () {
					return trimSerialize();
				};
			}
		},

		// Mocha
		// http://visionmedia.github.com/mocha/
		'Mocha': {
			detect: function () {
				return typeof Mocha !== 'undefined' && typeof mocha !== 'undefined';
			},
			install: function () {
				// Tab into the run method to install our hooks.
				// Use the mocha instance instead of the prototype, because
				// the mocha instance (HTMLReporter) also overloads .run.
				// This ensures our code runs after HTMLReporter is done.
				var run = mocha.run;
				mocha.run = function (fn) {
					var runner;

					// Sometimes (in IE9?) the 'end' event has already fired.
					// Registering on('end', fn) afterwards doesn't work.
					// So we use the .run(fn) callback instead, which is called
					// internally by Mocha right after the 'end' event.
					runner = run.call(this, function () {
						if (fn) {
							// Call the original callback given to .run(fn)
							fn.apply(this, arguments);
						}
						// `runner` can sometimes still be undefined here (at least in IE9).
						// Let the function return and pick up asynchronously
						// so the variable has been assigned.
						setTimeout(function () {
							submit({
								fail: runner.failures,
								total: runner.total,
								error: 0
							});
						}, 1);
					});

					runner.on('start', window.TestSwarm.heartbeat);
					runner.on('suite', window.TestSwarm.heartbeat);
					runner.on('test end', window.TestSwarm.heartbeat);
					runner.on('pass', window.TestSwarm.heartbeat);
					runner.on('fail', window.TestSwarm.heartbeat);

					return runner;
				};

				window.TestSwarm.serialize = function () {
					var i, len, els;
					els = document.getElementsByTagName('pre');
					// Expand all source code sections, because we submit a static
					// snapshot to TestSwarm, event handlers don't survive.
					for ( i = 0, len = els.length; i < len; i++ ) {
						els[i].style.display = 'inline-block';
					}
					return trimSerialize();
				};
			}
		}
	};

	detectAndInstall();

}() );
<commit_msg> Inject: Use new callback style for QUnit.done. Fixes #264.<commit_after>/**
 * JavaScript file to included by the test suite page that it loaded
 * inside the iframe on the "run" pages. This injection must be done
 * by the guest page, it can't be loaded by TestSwarm.
 * Example:
 * - https://github.com/jquery/jquery/blob/master/test/data/testrunner.js
 * - https://github.com/jquery/jquery/blob/master/test/index.html
 *
 * @author John Resig, 2008-2011
 * @author Timo Tijhof, 2012
 * @since 0.1.0
 * @package TestSwarm
 */
/*global QUnit, Test, JSSpec, JsUnitTestManager, SeleniumTestResult, LOG, doh, Screw, mocha */
(function ( undefined ) {
	var DEBUG, doPost, search, url, index, submitTimeout, curHeartbeat,
		beatRate, testFrameworks, onErrorFnPrev;

	DEBUG = false;

	doPost = false;
	search = window.location.search;
	index = search.indexOf( 'swarmURL=' );
	submitTimeout = 5;
	beatRate = 20;

	try {
		doPost = !!window.parent.postMessage;
	} catch ( e ) {}

	if ( index !== -1 ) {
		url = decodeURIComponent( search.slice( index + 9 ) );
	}

	if ( !DEBUG && ( !url || url.indexOf( 'http' ) !== 0 ) ) {
		return;
	}

	// Prevent blocking things from executing
	if ( !DEBUG ) {
		window.print = window.confirm = window.alert = window.open = function () {};
	}

	/** Utility functions **/

	function debugObj( obj ) {
		var i, str = '';
		for ( i in obj ) {
			str += ( str ? '\n' : '' ) + i + ':\n\t ' + obj[i];
		}
		return str;
	}

	function remove( elem ) {
		if ( typeof elem === 'string' ) {
			elem = document.getElementById( elem );
		}

		if ( elem ) {
			elem.parentNode.removeChild( elem );
		}
	}

	function trimSerialize( doc ) {
		var scripts, root, cur, links, i, href;
		doc = doc || document;

		scripts = doc.getElementsByTagName( 'script' );
		while ( scripts.length ) {
			remove( scripts[0] );
		}

		root = window.location.href.replace( /(https?:\/\/.*?)\/.*/, '$1' );
		cur = window.location.href.replace( /[^\/]*$/, '' );

		links = doc.getElementsByTagName( 'link' );
		for ( i = 0; i < links.length; i += 1 ) {
			href = links[i].href;
			if ( href.indexOf( '/' ) === 0 ) {
				href = root + href;
			} else if ( !/^https?:\/\//.test( href ) ) {
				href = cur + href;
			}
			links[i].href = href;
		}

		return ( '' + doc.documentElement.innerHTML + '' )
			.replace( /\s+/g, ' ' );
	}

	function submit( params ) {
		var form, i, input, key, paramItems, parts, query;

		if ( curHeartbeat ) {
			clearTimeout( curHeartbeat );
		}

		paramItems = (url.split( '?' )[1] || '' ).split( '&' );

		for ( i = 0; i < paramItems.length; i += 1 ) {
			if ( paramItems[i] ) {
				parts = paramItems[i].split( '=' );
				if ( !params[ parts[0] ] ) {
					params[ parts[0] ] = parts[1];
				}
			}
		}

		if ( !params.action ) {
			params.action = 'saverun';
		}

		if ( !params.report_html ) {
			params.report_html = window.TestSwarm.serialize();
		}

		if ( DEBUG ) {
			window.alert( debugObj( params ) ) ;
		}

		if ( doPost ) {
			// Build Query String
			query = '';

			for ( key in params ) {
				query += ( query ? '&' : '' ) + key + '=' + encodeURIComponent( params[key] );
			}

			if ( !DEBUG ) {
				window.parent.postMessage( query, '*' );
			}

		} else {
			form = document.createElement( 'form' );
			form.action = url;
			form.method = 'POST';

			for ( i in params ) {
				input = document.createElement( 'input' );
				input.type = 'hidden';
				input.name = i;
				input.value = params[i];
				form.appendChild( input );
			}

			if ( DEBUG ) {
				window.alert( url );

			} else {
				// Watch for the result submission timing out
				setTimeout(function () {
					submit( params );
				}, submitTimeout * 1000);

				document.body.appendChild( form );
				form.submit();
			}
		}
	}

	function detectAndInstall() {
		var key;
		for ( key in testFrameworks ) {
			if ( testFrameworks[key].detect() ) {
				testFrameworks[key].install();
				return key;
			}
		}
		return false;
	}

	// Preserve other handlers
	onErrorFnPrev = window.onerror;

	// Cover uncaught exceptions
	// Returning true will surpress the default browser handler,
	// returning false will let it run.
	window.onerror = function ( error, filePath, linerNr ) {
		var ret = false, report;
		if ( onErrorFnPrev ) {
			ret = onErrorFnPrev( error, filePath, linerNr );
		}

		// Treat return value as window.onerror itself does,
		// Only do our handling if not surpressed.
		if ( ret !== true ) {
			report = document.createElement( 'div' );
			report.innerHTML = '
[TestSwarm] window.onerror:
';
			report.appendChild( document.createTextNode( error ) );
			report.appendChild( document.createElement( 'br' ) );
			report.appendChild( document.createTextNode( 'in ' + filePath + ' on line ' + linerNr ) );
			document.body.appendChild( report );
			submit({ fail: 0, error: 1, total: 1 });

			return false;
		}

		return ret;
	};

	// Expose the TestSwarm API
	window.TestSwarm = {
		submit: submit,
		heartbeat: function () {
			if ( curHeartbeat ) {
				clearTimeout( curHeartbeat );
			}

			curHeartbeat = setTimeout(function () {
				submit({ fail: -1, total: -1 });
			}, beatRate * 1000);
		},
		serialize: function () {
			return trimSerialize();
		}
	};

	testFrameworks = {
		// QUnit (by jQuery)
		// http://docs.jquery.com/QUnit
		'QUnit': {
			detect: function () {
				return typeof QUnit !== 'undefined';
			},
			install: function () {
				QUnit.done(function ( results ) {
					submit({
						fail: results.failed,
						error: 0,
						total: results.total
					});
				});

				QUnit.log = window.TestSwarm.heartbeat;
				window.TestSwarm.heartbeat();

				window.TestSwarm.serialize = function () {
					var ol, i;

					// Show any collapsed results
					ol = document.getElementsByTagName( 'ol' );
					for ( i = 0; i < ol.length; i += 1 ) {
						ol[i].style.display = 'block';
					}

					return trimSerialize();
				};
			}
		},

		// UnitTestJS (Prototype, Scriptaculous)
		// https://github.com/tobie/unittest_js
		'UnitTestJS': {
			detect: function () {
				return typeof Test !== 'undefined' && Test && Test.Unit && Test.Unit.runners;
			},
			install: function () {
				/*jshint loopfunc:true */
				var total_runners = Test.Unit.runners.length,
					cur_runners = 0,
					total = 0,
					fail = 0,
					error = 0,
					i;

				for ( i = 0; i < Test.Unit.runners.length; i += 1 ) {
					// Need to proxy the i variable into a local scope,
					// otherwise all the finish-functions created in this loop
					// will refer to the same i variable..
					(function ( i ) {
						var finish, results;

						finish = Test.Unit.runners[i].finish;
						Test.Unit.runners[i].finish = function () {
							finish.call( this );

							results = this.getResult();
							total += results.assertions;
							fail += results.failures;
							error += results.errors;

							cur_runners += 1;
							if ( cur_runners === total_runners ) {
								submit({
									fail: fail,
									error: error,
									total: total
								});
							}
						};
					}( i ) );
				}
			}
		},

		// JSSpec (MooTools)
		// http://jania.pe.kr/aw/moin.cgi/JSSpec
		// https://code.google.com/p/jsspec/
		'JSSpec': {
			detect: function () {
				return typeof JSSpec !== 'undefined' && JSSpec && JSSpec.Logger;
			},
			install: function () {
				var onRunnerEnd = JSSpec.Logger.prototype.onRunnerEnd;
				JSSpec.Logger.prototype.onRunnerEnd = function () {
					var ul, i;
					onRunnerEnd.call( this );

					// Show any collapsed results
					ul = document.getElementsByTagName( 'ul' );
					for ( i = 0; i < ul.length; i += 1 ) {
						ul[i].style.display = 'block';
					}

					submit({
						fail: JSSpec.runner.getTotalFailures(),
						error: JSSpec.runner.getTotalErrors(),
						total: JSSpec.runner.totalExamples
					});
				};

				window.TestSwarm.serialize = function () {
					var ul, i;
					// Show any collapsed results
					ul = document.getElementsByTagName( 'ul' );
					for ( i = 0; i < ul.length; i += 1 ) {
						ul[i].style.display = 'block';
					}

					return trimSerialize();
				};
			}
		},

		// JSUnit
		// http://www.jsunit.net/
		// Note: Injection file must be included before the frames
		// are document.write()d into the page.
		'JSUnit': {
			detect: function () {
				return typeof JsUnitTestManager !== 'undefined';
			},
			install: function () {
				var _done = JsUnitTestManager.prototype._done;
				JsUnitTestManager.prototype._done = function () {
					_done.call( this );

					submit({
						fail: this.failureCount,
						error: this.errorCount,
						total: this.totalCount
					});
				};

				window.TestSwarm.serialize = function () {
					return '
' + this.log.join( '\n' ) + '
';
				};
			}
		},

		// Selenium Core
		// http://seleniumhq.org/projects/core/
		'Selenium': {
			detect: function () {
				return typeof SeleniumTestResult !== 'undefined' && typeof LOG !== 'undefined';
			},
			install: function () {
				// Completely overwrite the postback
				SeleniumTestResult.prototype.post = function () {
					submit({
						fail: this.metrics.numCommandFailures,
						error: this.metrics.numCommandErrors,
						total: this.metrics.numCommandPasses + this.metrics.numCommandFailures + this.metrics.numCommandErrors
					});
				};

				window.TestSwarm.serialize = function () {
					var results = [], msg;
					while ( LOG.pendingMessages.length ) {
						msg = LOG.pendingMessages.shift();
						results.push( msg.type + ': ' + msg.msg );
					}

					return '
' + results.join( '\n' ) + '
';
				};
			}
		},

		// Dojo Objective Harness
		// http://docs.dojocampus.org/quickstart/doh
		'DOH': {
			detect: function () {
				return typeof doh !== 'undefined' && doh._report;
			},
			install: function () {
				var _report = doh._report;
				doh._report = function () {
					_report.apply( this, arguments );

					submit({
						fail: doh._failureCount,
						error: doh._errorCount,
						total: doh._testCount
					});
				};

				window.TestSwarm.serialize = function () {
					return '
' + document.getElementById( 'logBody' ).innerHTML + '
';
				};
			}
		},

		// Screw.Unit
		// https://github.com/nathansobo/screw-unit
		'Screw.Unit': {
			detect: function () {
				return typeof Screw !== 'undefined' && typeof jQuery !== 'undefined' && Screw && Screw.Unit;
			},
			install: function () {
				$(Screw).bind( 'after', function () {
					var	passed = $( '.passed' ).length,
						failed = $( '.failed' ).length;
					submit({
						fail: failed,
						error: 0,
						total: failed + passed
					});
				});

				$( Screw ).bind( 'loaded', function () {
					$( '.it' )
						.bind( 'passed', window.TestSwarm.heartbeat )
						.bind( 'failed', window.TestSwarm.heartbeat );
					window.TestSwarm.heartbeat();
				});

				window.TestSwarm.serialize = function () {
					return trimSerialize();
				};
			}
		},

		// Mocha
		// http://visionmedia.github.com/mocha/
		'Mocha': {
			detect: function () {
				return typeof Mocha !== 'undefined' && typeof mocha !== 'undefined';
			},
			install: function () {
				// Tab into the run method to install our hooks.
				// Use the mocha instance instead of the prototype, because
				// the mocha instance (HTMLReporter) also overloads .run.
				// This ensures our code runs after HTMLReporter is done.
				var run = mocha.run;
				mocha.run = function (fn) {
					var runner;

					// Sometimes (in IE9?) the 'end' event has already fired.
					// Registering on('end', fn) afterwards doesn't work.
					// So we use the .run(fn) callback instead, which is called
					// internally by Mocha right after the 'end' event.
					runner = run.call(this, function () {
						if (fn) {
							// Call the original callback given to .run(fn)
							fn.apply(this, arguments);
						}
						// `runner` can sometimes still be undefined here (at least in IE9).
						// Let the function return and pick up asynchronously
						// so the variable has been assigned.
						setTimeout(function () {
							submit({
								fail: runner.failures,
								total: runner.total,
								error: 0
							});
						}, 1);
					});

					runner.on('start', window.TestSwarm.heartbeat);
					runner.on('suite', window.TestSwarm.heartbeat);
					runner.on('test end', window.TestSwarm.heartbeat);
					runner.on('pass', window.TestSwarm.heartbeat);
					runner.on('fail', window.TestSwarm.heartbeat);

					return runner;
				};

				window.TestSwarm.serialize = function () {
					var i, len, els;
					els = document.getElementsByTagName('pre');
					// Expand all source code sections, because we submit a static
					// snapshot to TestSwarm, event handlers don't survive.
					for ( i = 0, len = els.length; i < len; i++ ) {
						els[i].style.display = 'inline-block';
					}
					return trimSerialize();
				};
			}
		}
	};

	detectAndInstall();

}() );
<|endoftext|>


<commit_before>'use strict';

var menuStyles = function() {

  var headHeight = $('.row-wrapper').offset().top;
  var scrollPos = $(window).scrollTop();

  if ($(window).width() > 850) {
    $('#side-nav').css({display: 'block'});

    if ($(window).height() > headHeight) {
      $('#side-nav').addClass('fix');
      $('.newsapps-logo').addClass('shift');
      $('.main').addClass('shift');
    }

  } else {
      $('#side-nav').removeAttr('top').removeClass('fix');
      $('#side-nav').css({display: 'none'});
      $('.newsapps-logo').removeClass('shift');
      $('.main').removeClass('shift');
  }

};

$(document).ready(function(){
  // Hide-Show code blocks
  $('.code-block > .button').click(function(){
    $(this).next('pre').toggle();
  });

  $('#menu').click(function() {
    $('#side-nav').toggle();
  });

  menuStyles();
});

$(window).resize(function() {
  menuStyles();
});

$(window).scroll(function () {
  menuStyles();
});
<commit_msg>linter<commit_after>'use strict';

var menuStyles = function() {

  var headHeight = $('.row-wrapper').offset().top;

  if ($(window).width() > 850) {
    $('#side-nav').css({display: 'block'});

    if ($(window).height() > headHeight) {
      $('#side-nav').addClass('fix');
      $('.newsapps-logo').addClass('shift');
      $('.main').addClass('shift');
    }

  } else {
      $('#side-nav').removeAttr('top').removeClass('fix');
      $('#side-nav').css({display: 'none'});
      $('.newsapps-logo').removeClass('shift');
      $('.main').removeClass('shift');
  }

};

$(document).ready(function(){
  // Hide-Show code blocks
  $('.code-block > .button').click(function(){
    $(this).next('pre').toggle();
  });

  $('#menu').click(function() {
    $('#side-nav').toggle();
  });

  menuStyles();
});

$(window).resize(function() {
  menuStyles();
});

$(window).scroll(function () {
  menuStyles();
});
<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state, bet) {

    console.log("------------------------------------------ BET REQUEST START LOG");
    var community_cards = [];
    if (game_state.community_cards !== 'undefined') {
      community_cards = game_state.community_cards;
    }
    console.log("COMMUNITY:: " + community_cards);
    var number_of_active_players = function(players) {
      var num_of_players = 0;
      for (var i = 0; i < players.length; i++) {
        if(players[i].status != "out") {
          num_of_players++;
        }
      }
      return num_of_players;
    };

    var prepare_bet = function(hand, player_num, check_amount, community_cards) {
        var cards = { "2" : 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8" : 8, "9" : 9, "10" : 10, "J" : 11, "Q": 12, "K": 13, "A": 14};
        var goodStartingHand = ["10", "A", "J", "Q", "K"];
        var max = cards[hand[0]] > cards[hand[1]] ? cards[hand[0]] : cards[hand[1]];
        console.log("PREPARE BET FUNCTION =========");
        var handDifference = Math.abs(cards[hand[0]] - cards[hand[1]]);
        var hasHighCard = goodStartingHand.indexOf(hand[0]) > -1 || goodStartingHand.indexOf(hand[1]) > -1;
        var hasPair = hand[0] === hand[1];
        var communityRanks = [];
        try{
          community_cards.forEach(function(card){console.log(card.rank);communityRanks.push(card.rank);});
        } catch(e){
          console.error("NO COMMUNITY CARDS YET");
        }
        console.log("HIGH CARD: " + max);
        console.log("HAND DIFFERENCE: " + handDifference);
        console.log("COMMUNITY CARDS: " + community_cards);
        console.log("COMMUNITY RANKS: " + communityRanks);
        // 0. TURN
        if(community_cards.length === 0 || community_cards.length === 'undefined'){
          console.log("TURN 0");
          if (handDifference > 4 && !hasHighCard) {
            return 0;
          } else {
            if(hasPair){
              return check_amount * 2;
            }
            else {
              return check_amount;
            }
          }
        } else {
          console.log("FLOP");
          if(communityRanks.indexOf(hand[0]) > -1 || communityRanks.indexOf(hand[1]) > -1){
            return check_amount * 4;
          }
          else {
            return check_amount;
          }
        }
    };

    var check_amount = game_state.current_buy_in - game_state.players[0].bet;

    var hand = [];
    var player = game_state.players[0];
    try{
      hand.push(player.hole_cards[0].rank);
      hand.push(player.hole_cards[1].rank);
    } catch(ex){
      console.log(ex);
    }
    console.log("========================== OWN HAND");
    console.log(hand);

    var player_count = number_of_active_players(game_state.players);
    console.log("========================== NUMBER OF ACTIVE PLAYERS");
    console.log(player_count);

    var actual_bet = prepare_bet(hand, player_count, check_amount, community_cards);
    console.log("###################### ACTUAL BET");
    console.log(actual_bet);
    bet(actual_bet);
    console.log( 'WWWWWWWWWWWWWWWWWWWWWWWWW game state + bet' );
    console.log( game_state );

    console.log("------------------------------------------ BET REQUEST END LOG");

  },

  showdown: function(game_state) {
    if (game_state.players[0].status != "out") {
      console.log("========================== SHOWDOWN");
      console.log(game_state);
      // console.log("========================== OWN HAND");
      // console.log(game_state.players[0].hole_cards[0].rank);
      // console.log(game_state.players[0].hole_cards[1].rank);
      console.log("========================== OPPONENT CARDS IN LAST TURN");
      for(var i =0; i < game_state.players.length; i++) {
        if (game_state.players[i].status != "out") {
          console.log(game_state.players[i].name);
          // console.log(game_state.players[i].hole_cards[0].rank + " " + game_state.players[i].hole_cards[1].rank);
          console.log(game_state.players[i].stack);
        }
      }
    }
}

};
<commit_msg>check<commit_after>
module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state, bet) {

    console.log("------------------------------------------ BET REQUEST START LOG");
    var community_cards = [];
    if (game_state.community_cards !== 'undefined') {
      community_cards = game_state.community_cards;
    }
    console.log("COMMUNITY:: " + community_cards);
    var number_of_active_players = function(players) {
      var num_of_players = 0;
      for (var i = 0; i < players.length; i++) {
        if(players[i].status != "out") {
          num_of_players++;
        }
      }
      return num_of_players;
    };

    var prepare_bet = function(hand, player_num, check_amount, community_cards) {
        var cards = { "2" : 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8" : 8, "9" : 9, "10" : 10, "J" : 11, "Q": 12, "K": 13, "A": 14};
        var goodStartingHand = ["10", "A", "J", "Q", "K"];
        var max = cards[hand[0]] > cards[hand[1]] ? cards[hand[0]] : cards[hand[1]];
        console.log("PREPARE BET FUNCTION =========");
        var handDifference = Math.abs(cards[hand[0]] - cards[hand[1]]);
        var hasHighCard = goodStartingHand.indexOf(hand[0]) > -1 || goodStartingHand.indexOf(hand[1]) > -1;
        var hasPair = hand[0] === hand[1];
        var communityRanks = [];
        try{
          community_cards.forEach(function(card){console.log(card.rank);communityRanks.push(card.rank);});
        } catch(e){
          console.error("NO COMMUNITY CARDS YET");
        }
        console.log("HIGH CARD: " + max);
        console.log("HAND DIFFERENCE: " + handDifference);
        console.log("COMMUNITY CARDS: " + community_cards);
        console.log("COMMUNITY RANKS: " + communityRanks);
        // 0. TURN
        if(community_cards.length === 0 || community_cards.length === 'undefined'){
          console.log("TURN 0");
          if (handDifference > 4 && !hasHighCard) {
            return 0;
          } else {
            if(hasPair){
              return check_amount * 2;
            }
            else {
              return check_amount;
            }
          }
        } else {
          console.log("FLOP");
          if(communityRanks.indexOf(hand[0]) > -1 || communityRanks.indexOf(hand[1]) > -1){
            return Math.max(check_amount * 4, 10) ;
          }
          else {
            return check_amount;
          }
        }
    };

    var check_amount = game_state.current_buy_in - game_state.players[0].bet;

    var hand = [];
    var player = game_state.players[0];
    try{
      hand.push(player.hole_cards[0].rank);
      hand.push(player.hole_cards[1].rank);
    } catch(ex){
      console.log(ex);
    }
    console.log("========================== OWN HAND");
    console.log(hand);

    var player_count = number_of_active_players(game_state.players);
    console.log("========================== NUMBER OF ACTIVE PLAYERS");
    console.log(player_count);

    var actual_bet = prepare_bet(hand, player_count, check_amount, community_cards);
    console.log("###################### ACTUAL BET");
    console.log(actual_bet);
    bet(actual_bet);
    console.log( 'WWWWWWWWWWWWWWWWWWWWWWWWW game state + bet' );
    console.log( game_state );

    console.log("------------------------------------------ BET REQUEST END LOG");

  },

  showdown: function(game_state) {
    if (game_state.players[0].status != "out") {
      console.log("========================== SHOWDOWN");
      console.log(game_state);
      // console.log("========================== OWN HAND");
      // console.log(game_state.players[0].hole_cards[0].rank);
      // console.log(game_state.players[0].hole_cards[1].rank);
      console.log("========================== OPPONENT CARDS IN LAST TURN");
      for(var i =0; i < game_state.players.length; i++) {
        if (game_state.players[i].status != "out") {
          console.log(game_state.players[i].name);
          // console.log(game_state.players[i].hole_cards[0].rank + " " + game_state.players[i].hole_cards[1].rank);
          console.log(game_state.players[i].stack);
        }
      }
    }
}

};
<|endoftext|>


<commit_before>/**
 * Created by Samuel Gratzl on 04.09.2014.
 */

(function (LineUpJS) {
  var menuActions = [
    {
      name: ' new combined', icon: 'fa-plus', action: function () {
      var r = lineup.data.getRankings();
      r = r[r.length - 1];
      lineup.data.push(r, LineUpJS.model.StackColumn.desc('Combined'));
    }
    },
    {
      name: ' new ranking', icon: 'fa-plus', action: function () {
      var old = lineup.data.getRankings()[0];
      var r = lineup.data.pushRanking();
      r.push(lineup.data.clone(old.children[0]));
    }
    },
    {name: ' add single columns', icon: 'fa-plus', action: openAddColumnDialog},
    {name: ' save layout', icon: 'fa-floppy-o', action: saveLayout}
  ];
  var lineUpDemoConfig = {
    htmlLayout: {
      autoRotateLabels: true
    },
    renderingOptions: {
      stacked: true,
      histograms: true,
      animated: true
    },
    svgLayout: {
      freezeCols: 0
    }
  };

  var lineup = null;
  var datasets = [];

  d3.select(window).on('resize', function () {
    if (lineup) {
      lineup.update()
    }
  });

  function updateMenu() {
    var config = lineup.config;
    var kvNodes = d3.select('#lugui-menu-rendering').selectAll('span').data(['stacked', 'animation']);
    kvNodes.exit().remove();
    kvNodes.enter().append('span').on('click', function (d) {
      lineup.changeRenderingOption(d, !config.renderingOptions[d]);
      updateMenu();
    });
    kvNodes.html(function (d) {
      return '  ' + d + '  '
    });

    d3.select('#lugui-menu-actions').selectAll('span').data(menuActions)
      .enter().append('span').html(
      function (d) {
        return '' + d.name + '  '
      }
    ).on('click', function (d) {
      d.action.call(d);
    })
  }

  function uploadDataset(dropFileCallback, dropURLCallback) {
    function handleFileSelect(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      var files = evt.target.files || evt.dataTransfer.files;
      //console.log('drop',files);
      files = Array.prototype.slice.call(files); // FileList object.
      dropFileCallback(files);
    }

    function handleDragOver(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
    }

    var $file = d3.select('#lugui-menu input[type="file"]');
    $file.node().addEventListener('change', handleFileSelect, false);
    var $drop = d3.select('#drop_zone');
    var drop = $drop.node();

    drop.addEventListener('click', function () {
      document.getElementById('fileselect').click();
    })

    drop.addEventListener('dragenter', function () {
      $drop.classed('dragging', true);
    }, false);
    drop.addEventListener('dragleave', function () {
      $drop.classed('dragging', false);
    }, false);
    drop.addEventListener('dragover', handleDragOver, false);
    drop.addEventListener('drop', function (evt) {
      evt.stopPropagation();
      evt.preventDefault();
      var files = evt.dataTransfer.files;
      //console.log('drop',files);
      files = Array.prototype.slice.call(files); // FileList object.
      if (files.length > 0) {
        return dropFileCallback(files);
      } else {
        var url = evt.dataTransfer.getData('text/uri-list');
        if (url) {
          return dropURLCallback(url);
        }
      }
      console.error('unknown datatransfer');
    }, false);
  }

  function loadDataset(ds) {
    function loadData(desc, baseUrl) {
      if (desc.data) {
        initLineup(desc.name, desc, desc.data);
      } else if (desc.file) {
        d3.dsv(desc.separator || '\t', 'text/plain')(baseUrl + '/' + desc.file, function (_data) {
          initLineup(desc.name, desc, _data);
        });
      }
    }

    function loadGist(gistid) {
      d3.json('https://api.github.com/gists/'+gistid, function(error, gistdesc) {
        if (error) {
          console.error('cant load gist id: '+gistid, error);
        } else if (gistdesc) {
          var firstFile = gistdesc.files[Object.keys(gistdesc.files)[0]];
          var content = JSON.parse(firstFile.content);
          initLineup(gistdesc.description, content, content.data);
        }
      });
    }

    document.title = 'LineUp - ' + (ds.name || 'Custom');
    history.pushState(ds, 'LineUp - ' + (ds.name || 'Custom'), '#' + (ds.id || 'custom'));

    if (ds.descriptionFile) {
      var name = ds.descriptionFile.substring(0, ds.descriptionFile.length - 5);
      d3.json(ds.baseURL + '/' + ds.descriptionFile, function (desc) {
        loadData(desc, ds.baseURL);
      })
    } else if (ds.gist) {
      loadGist(ds.gist);
    } else {
      loadData(ds, '');
    }
  }

  /**
   *
   * @param name - name of the dataset
   * @param desc - description of the dataset
   * @param _data - the loaded data
   */
  function initLineup(name, desc, _data) {
    fixMissing(desc.columns, _data);
    var provider = LineUpJS.createLocalStorage(_data, LineUpJS.deriveColors(desc.columns));
    lineUpDemoConfig.name = name;
    if (lineup) {
      lineup.changeDataStorage(provider, desc);
    } else {
      lineup = LineUpJS.create(provider, d3.select('#lugui-wrapper'), lineUpDemoConfig);
      lineup.addPool(d3.select('#pool').node(), {
        hideUsed: false
      }).update();
      lineup.restore(desc);//TODO: why?
    }
    provider.deriveDefault();
    lineup.update();

    //sort by stacked columns
    var cols = provider.getRankings();
    cols.forEach(function (rankCol) {
      rankCol.children.forEach(function (col) {
        if (col.desc.type === "stack")
          col.sortByMe();
      })
    })
    updateMenu();
  }

  function fixMissing(columns, data) {
    columns.forEach(function (col) {
      if (col.type === 'number' && !col.domain) {
        var old = col.domain || [NaN, NaN];
        var minmax = d3.extent(data, function (row) {
          return row[col.column].length === 0 ? undefined : +(row[col.column])
        });
        col.domain = [
          isNaN(old[0]) ? minmax[0] : old[0],
          isNaN(old[1]) ? minmax[1] : old[1]
        ];
      } else if (col.type === 'categorical' && !col.categories) {
        var sset = d3.set(data.map(function (row) {
          return row[col];
        }));
        col.categories = sset.values().sort();
      }
    });
  }

  function openAddColumnDialog() {
    d3.select('#pool').style('display', 'block');
  }

  d3.select('#pool > div i.fa-close').on('click', function () {
    d3.select('#pool').style('display', 'none');
  });

  function saveLayout() {
    //full spec
    var s = lineup.dump();
    s.columns = lineup.data.columns;
    s.data = lineup.data.data;

    //stringify with pretty print
    var str = JSON.stringify(s, null, '\t');
    //create blob and save it
    var blob = new Blob([str], {type: 'application/json;charset=utf-8'});
    saveAs(blob, 'LineUp-' + lineUpDemoConfig.name + '.json');
  }

  function loadLayout() {
    function loadDataFile(name, desc, datafile) {
      var reader = new FileReader();
      reader.onload = function (e) {
        var data_s = e.target.result;
        var _data = d3.dsv(desc.separator || '\t', 'text/plain').parse(data_s);
        initLineup(name, desc, _data);
      };
      // Read in the image file as a data URL.
      reader.readAsText(datafile);
    }

    function countOccurrences(text, char) {
      return (text.match(new RegExp(char, 'g')) || []).length;
    }

    function isNumeric(obj) {
      return (obj - parseFloat(obj) + 1) >= 0;
    }

    function deriveDesc(columns, data, separator) {
      var cols = columns.map(function (col) {
        var r = {
          label: col,
          column: col,
          type: 'string'
        };
        if (isNumeric(data[0][col])) {
          r.type = 'number';
          r.domain = d3.extent(data, function (row) {
            return row[col].length === 0 ? undefined : +(row[col])
          });
        } else {
          var sset = d3.set(data.map(function (row) {
            return row[col];
          }));
          if (sset.size() <= Math.max(20, data.length * 0.2)) { //at most 20 percent unique values
            r.type = 'categorical';
            r.categories = sset.values().sort();
          }
        }
        return r;
      });
      return {
        separator: separator,
        primaryKey: columns[0],
        columns: cols
      };
    }

    function normalizeValue(val) {
      if (typeof val === 'string') {
        val = val.trim();
        if (val.length >= 2 && val.charAt(0) === '"' && val.charAt(val.length - 1) === '"') {
          val = val.slice(1, val.length - 1);
        }
      }
      return val;
    }

    /**
     * trims the given object
     * @param row
     * @return {{}}
     */
    function normalizeRow(row) {
      var r = {};
      Object.keys(row).forEach(function (key) {
        r[normalizeValue(key)] = normalizeValue(row[key]);
      });
      return r;
    }

    function loadDataFileFromText(data_s, fileName) {
      var header = data_s.slice(0, data_s.indexOf('\n'));
      //guess the separator,
      var separator = [',', '\t', ';'].reduce(function (prev, current) {
        var c = countOccurrences(header, current);
        if (c > prev.c) {
          prev.c = c;
          prev.s = current;
        }
        return prev;
      }, {s: ',', c: 0});
      var _data = d3.dsv(separator.s, 'text/plain').parse(data_s, normalizeRow);
      //derive a description file
      var desc = deriveDesc(header.split(separator.s).map(normalizeValue), _data);
      var name = fileName.substring(0, fileName.lastIndexOf('.'));
      initLineup(name, desc, _data);
    }

    uploadDataset(function (files) {
      var descs = files.filter(function (f) {
        return f.name.match(/.*\.json/i) || f.type === 'application/json';
      });

      var reader = new FileReader();
      if (descs.length > 0) {
        // Closure to capture the file information.
        reader.onload = function (e) {
          var desc = e.target.result;
          var name = descs[0].name.substring(0, descs[0].name.length - 5);
          desc = JSON.parse(desc);
          if (desc.data) {
            initLineup(name, desc, desc.data);
          } else if (desc.url) {
            d3.dsv(desc.separator || '\t', 'text/plain')(desc.url, normalizeRow, function (_data) {
              initLineup(name, desc, _data);
            });
          } else if (desc.file) {
            var d = files.filter(function (f) {
              return f.name === desc.file;
            });
            if (d.length > 0) {
              loadDataFile(name, desc, d[0]);
            }
          }
        };
        // Read in the image file as a data URL.
        reader.readAsText(descs[0]);
      } else if (files.length === 1 && files[0].name.match(/.*\.(tsv|csv|txt)/)) {
        //just a data file
        var f = files[0];
        reader.onload = function (e) {
          var data_s = e.target.result;
          loadDataFileFromText(data_s, f.name);
        };
        reader.readAsText(f);
      }
    }, function (url) {
      //access the url using get request and then parse the data file
      d3.text(url, 'text/plain', function (data) {
        loadDataFileFromText(data, 'by_url');
      });
    });
  }

// document ready
  d3.json('datasets.json', function (error, data) {
    //console.log('datasets:', data, error);

    //setup dataset select
    datasets = data.datasets;
    var $selector = d3.select('#lugui-dataset-selector');
    var ds = $selector.selectAll('option').data(data.datasets);
    ds.enter().append('option')
      .attr('value', function (d, i) {
        return i;
      }).text(function (d) {
      return d.name;
    });
    $selector.on('change', function () {
      loadDataset(datasets[this.value]);
    });

    //load data and init lineup

    var old = history.state;
    if (old) {
      var choose = datasets.filter(function (d) {
        return d.id === old.id;
      });
      $selector.property('value', datasets.indexOf(choose[0]));
      loadDataset(choose[0]);
    } else if (window.location.hash) {
      var hash = window.location.hash.substr(1);
      if (hash.match(/gist:.*/)) {
        loadDataset({
          name: 'Github Gist '+hash.substr(5),
          id: hash,
          gist: hash.substr(5)
        });
      } else {
        var choose = datasets.filter(function (d) {
          return d.id === hash;
        });
        if (choose.length > 0) {
          $selector.property('value', datasets.indexOf(choose[0]));
          loadDataset(choose[0]);
        } else {
          loadDataset(datasets[0]);
        }
      }
    } else {
      //and start with 0:
      loadDataset(datasets[0]);
    }

    loadLayout();
  });

}(LineUpJS));
<commit_msg>#103 bugfixing and save to gist feature<commit_after>/**
 * Created by Samuel Gratzl on 04.09.2014.
 */

(function (LineUpJS) {
  var menuActions = [
    {
      name: ' new combined', icon: 'fa-plus', action: function () {
      var r = lineup.data.getRankings();
      r = r[r.length - 1];
      lineup.data.push(r, LineUpJS.model.StackColumn.desc('Combined'));
    }
    },
    {
      name: ' new ranking', icon: 'fa-plus', action: function () {
      var old = lineup.data.getRankings()[0];
      var r = lineup.data.pushRanking();
      r.push(lineup.data.clone(old.children[0]));
    }
    },
    {name: ' add single columns', icon: 'fa-plus', action: openAddColumnDialog},
    {name: ' save layout', icon: 'fa-floppy-o', action: saveLayout},
    {name: ' save to gist', icon: 'fa-github', action: saveToGist}
  ];
  var lineUpDemoConfig = {
    htmlLayout: {
      autoRotateLabels: true
    },
    renderingOptions: {
      stacked: true,
      histograms: true,
      animated: true
    },
    svgLayout: {
      freezeCols: 0
    }
  };

  var lineup = null;
  var datasets = [];

  d3.select(window).on('resize', function () {
    if (lineup) {
      lineup.update()
    }
  });

  function updateMenu() {
    var config = lineup.config;
    var kvNodes = d3.select('#lugui-menu-rendering').selectAll('span').data(['stacked', 'animation']);
    kvNodes.exit().remove();
    kvNodes.enter().append('span').on('click', function (d) {
      lineup.changeRenderingOption(d, !config.renderingOptions[d]);
      updateMenu();
    });
    kvNodes.html(function (d) {
      return '  ' + d + '  '
    });

    d3.select('#lugui-menu-actions').selectAll('span').data(menuActions)
      .enter().append('span').html(
      function (d) {
        return '' + d.name + '  '
      }
    ).on('click', function (d) {
      d.action.call(d);
    })
  }

  function uploadDataset(dropFileCallback, dropURLCallback) {
    function handleFileSelect(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      var files = evt.target.files || evt.dataTransfer.files;
      //console.log('drop',files);
      files = Array.prototype.slice.call(files); // FileList object.
      dropFileCallback(files);
    }

    function handleDragOver(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
    }

    var $file = d3.select('#lugui-menu input[type="file"]');
    $file.node().addEventListener('change', handleFileSelect, false);
    var $drop = d3.select('#drop_zone');
    var drop = $drop.node();

    drop.addEventListener('click', function () {
      document.getElementById('fileselect').click();
    })

    drop.addEventListener('dragenter', function () {
      $drop.classed('dragging', true);
    }, false);
    drop.addEventListener('dragleave', function () {
      $drop.classed('dragging', false);
    }, false);
    drop.addEventListener('dragover', handleDragOver, false);
    drop.addEventListener('drop', function (evt) {
      evt.stopPropagation();
      evt.preventDefault();
      var files = evt.dataTransfer.files;
      //console.log('drop',files);
      files = Array.prototype.slice.call(files); // FileList object.
      if (files.length > 0) {
        return dropFileCallback(files);
      } else {
        var url = evt.dataTransfer.getData('text/uri-list');
        if (url) {
          return dropURLCallback(url);
        }
      }
      console.error('unknown datatransfer');
    }, false);
  }

  function loadDataset(ds) {
    function loadData(desc, baseUrl) {
      if (desc.data) {
        initLineup(desc.name, desc, desc.data);
      } else if (desc.file) {
        d3.dsv(desc.separator || '\t', 'text/plain')(baseUrl + '/' + desc.file, function (_data) {
          initLineup(desc.name, desc, _data);
        });
      }
    }

    function loadGist(gistid) {
      d3.json('https://api.github.com/gists/'+gistid, function(error, gistdesc) {
        if (error) {
          console.error('cant load gist id: '+gistid, error);
        } else if (gistdesc) {
          var firstFile = gistdesc.files[Object.keys(gistdesc.files)[0]];
          var content = JSON.parse(firstFile.content);
          initLineup(gistdesc.description, content, content.data);
        }
      });
    }

    document.title = 'LineUp - ' + (ds.name || 'Custom');
    history.pushState(ds, 'LineUp - ' + (ds.name || 'Custom'), '#' + (ds.id || 'custom'));

    if (ds.descriptionFile) {
      var name = ds.descriptionFile.substring(0, ds.descriptionFile.length - 5);
      d3.json(ds.baseURL + '/' + ds.descriptionFile, function (desc) {
        loadData(desc, ds.baseURL);
      })
    } else if (ds.gist) {
      loadGist(ds.gist);
    } else {
      loadData(ds, '');
    }
  }

  /**
   *
   * @param name - name of the dataset
   * @param desc - description of the dataset
   * @param _data - the loaded data
   */
  function initLineup(name, desc, _data) {
    fixMissing(desc.columns, _data);
    var provider = LineUpJS.createLocalStorage(_data, LineUpJS.deriveColors(desc.columns));
    lineUpDemoConfig.name = name;
    if (lineup) {
      lineup.changeDataStorage(provider, desc);
    } else {
      lineup = LineUpJS.create(provider, d3.select('#lugui-wrapper'), lineUpDemoConfig);
      lineup.addPool(d3.select('#pool').node(), {
        hideUsed: false
      }).update();
      lineup.restore(desc);//TODO: why?
    }
    provider.deriveDefault();
    lineup.update();

    //sort by stacked columns
    var cols = provider.getRankings();
    cols.forEach(function (rankCol) {
      rankCol.children.forEach(function (col) {
        if (col.desc.type === "stack")
          col.sortByMe();
      })
    })
    updateMenu();
  }

  function fixMissing(columns, data) {
    columns.forEach(function (col) {
      if (col.type === 'number' && !col.domain) {
        var old = col.domain || [NaN, NaN];
        var minmax = d3.extent(data, function (row) {
          return row[col.column].length === 0 ? undefined : +(row[col.column])
        });
        col.domain = [
          isNaN(old[0]) ? minmax[0] : old[0],
          isNaN(old[1]) ? minmax[1] : old[1]
        ];
      } else if (col.type === 'categorical' && !col.categories) {
        var sset = d3.set(data.map(function (row) {
          return row[col];
        }));
        col.categories = sset.values().sort();
      }
    });
  }

  function openAddColumnDialog() {
    d3.select('#pool').style('display', 'block');
  }

  d3.select('#pool > div i.fa-close').on('click', function () {
    d3.select('#pool').style('display', 'none');
  });

  function dumpLayout() {
    //full spec
    var s = lineup.dump();
    s.columns = lineup.data.columns;
    s.data = lineup.data.data;

    //stringify with pretty print
    return JSON.stringify(s, null, '\t');
  }

  function saveLayout() {
    //stringify with pretty print
    var str = dumpLayout();
    //create blob and save it
    var blob = new Blob([str], {type: 'application/json;charset=utf-8'});
    saveAs(blob, 'LineUp-' + lineUpDemoConfig.name + '.json');
  }

  function saveToGist() {
    //stringify with pretty print
    var str = dumpLayout();
    var args = {
        'description': lineUpDemoConfig.name,
        'public': true,
        'files': {
          'lineup.json': {
            'content': str
          }
        }
    };
    d3.json('https://api.github.com/gists').post(JSON.stringify(args), function (error, data) {
      if (error) {
        console.log('cant store to gist', error);
      } else {
        var id = data.id;
        document.title = 'LineUp - ' + (args.description || 'Custom');
        history.pushState({ id: 'gist:'+id }, 'LineUp - ' + (args.description || 'Custom'), '#gist:' + id);
      }
    });
  }

  function loadLayout() {
    function loadDataFile(name, desc, datafile) {
      var reader = new FileReader();
      reader.onload = function (e) {
        var data_s = e.target.result;
        var _data = d3.dsv(desc.separator || '\t', 'text/plain').parse(data_s);
        initLineup(name, desc, _data);
      };
      // Read in the image file as a data URL.
      reader.readAsText(datafile);
    }

    function countOccurrences(text, char) {
      return (text.match(new RegExp(char, 'g')) || []).length;
    }

    function isNumeric(obj) {
      return (obj - parseFloat(obj) + 1) >= 0;
    }

    function deriveDesc(columns, data, separator) {
      var cols = columns.map(function (col) {
        var r = {
          label: col,
          column: col,
          type: 'string'
        };
        if (isNumeric(data[0][col])) {
          r.type = 'number';
          r.domain = d3.extent(data, function (row) {
            return row[col].length === 0 ? undefined : +(row[col])
          });
        } else {
          var sset = d3.set(data.map(function (row) {
            return row[col];
          }));
          if (sset.size() <= Math.max(20, data.length * 0.2)) { //at most 20 percent unique values
            r.type = 'categorical';
            r.categories = sset.values().sort();
          }
        }
        return r;
      });
      return {
        separator: separator,
        primaryKey: columns[0],
        columns: cols
      };
    }

    function normalizeValue(val) {
      if (typeof val === 'string') {
        val = val.trim();
        if (val.length >= 2 && val.charAt(0) === '"' && val.charAt(val.length - 1) === '"') {
          val = val.slice(1, val.length - 1);
        }
      }
      return val;
    }

    /**
     * trims the given object
     * @param row
     * @return {{}}
     */
    function normalizeRow(row) {
      var r = {};
      Object.keys(row).forEach(function (key) {
        r[normalizeValue(key)] = normalizeValue(row[key]);
      });
      return r;
    }

    function loadDataFileFromText(data_s, fileName) {
      var header = data_s.slice(0, data_s.indexOf('\n'));
      //guess the separator,
      var separator = [',', '\t', ';'].reduce(function (prev, current) {
        var c = countOccurrences(header, current);
        if (c > prev.c) {
          prev.c = c;
          prev.s = current;
        }
        return prev;
      }, {s: ',', c: 0});
      var _data = d3.dsv(separator.s, 'text/plain').parse(data_s, normalizeRow);
      //derive a description file
      var desc = deriveDesc(header.split(separator.s).map(normalizeValue), _data);
      var name = fileName.substring(0, fileName.lastIndexOf('.'));
      initLineup(name, desc, _data);
    }

    uploadDataset(function (files) {
      var descs = files.filter(function (f) {
        return f.name.match(/.*\.json/i) || f.type === 'application/json';
      });

      var reader = new FileReader();
      if (descs.length > 0) {
        // Closure to capture the file information.
        reader.onload = function (e) {
          var desc = e.target.result;
          var name = descs[0].name.substring(0, descs[0].name.length - 5);
          desc = JSON.parse(desc);
          if (desc.data) {
            initLineup(name, desc, desc.data);
          } else if (desc.url) {
            d3.dsv(desc.separator || '\t', 'text/plain')(desc.url, normalizeRow, function (_data) {
              initLineup(name, desc, _data);
            });
          } else if (desc.file) {
            var d = files.filter(function (f) {
              return f.name === desc.file;
            });
            if (d.length > 0) {
              loadDataFile(name, desc, d[0]);
            }
          }
        };
        // Read in the image file as a data URL.
        reader.readAsText(descs[0]);
      } else if (files.length === 1 && files[0].name.match(/.*\.(tsv|csv|txt)/)) {
        //just a data file
        var f = files[0];
        reader.onload = function (e) {
          var data_s = e.target.result;
          loadDataFileFromText(data_s, f.name);
        };
        reader.readAsText(f);
      }
    }, function (url) {
      //access the url using get request and then parse the data file
      d3.text(url, 'text/plain', function (data) {
        loadDataFileFromText(data, 'by_url');
      });
    });
  }

// document ready
  d3.json('datasets.json', function (error, data) {
    //console.log('datasets:', data, error);

    //setup dataset select
    datasets = data.datasets;
    var $selector = d3.select('#lugui-dataset-selector');
    var ds = $selector.selectAll('option').data(data.datasets);
    ds.enter().append('option')
      .attr('value', function (d, i) {
        return i;
      }).text(function (d) {
      return d.name;
    });
    $selector.on('change', function () {
      loadDataset(datasets[this.value]);
    });

    //load data and init lineup

    var old = history.state ? history.state.id : (window.location.hash ? window.location.hash.substr(1) : '');
    if (old.match(/gist:.*/)) {
      loadDataset({
        name: 'Github Gist '+old.substr(5),
        id: old,
        gist: old.substr(5)
      });
    } else {
      var choose = datasets.filter(function (d) {
        return d.id === old;
      })
      if (choose.length > 0) {
        $selector.property('value', datasets.indexOf(choose[0]));
        loadDataset(choose[0]);
      } else {
        loadDataset(datasets[0]);
      }
    }

    loadLayout();
  });

}(LineUpJS));
<|endoftext|>


<commit_before>const React = require('react');
const Radium = require('radium');
const _has = require('lodash/has');

const Button = require('./Button');
const Icon = require('./Icon');

const StyleConstants = require('../constants/Style');

const Modal = React.createClass({
  propTypes: {
    buttons: React.PropTypes.arrayOf(React.PropTypes.shape({
      actionText: React.PropTypes.string,
      className: React.PropTypes.string,
      isActive: React.PropTypes.bool,
      icon: React.PropTypes.string,
      label: React.PropTypes.string,
      onClick: React.PropTypes.func,
      style: React.PropTypes.oneOfType([
        React.PropTypes.array,
        React.PropTypes.object
      ]),
      type: React.PropTypes.oneOf(['primary', 'secondary'])
    })),
    color: React.PropTypes.string,
    contentStyle: React.PropTypes.object,
    footerContent: React.PropTypes.node,
    footerStyle: React.PropTypes.oneOfType([
      React.PropTypes.array,
      React.PropTypes.object
    ]),
    isRelative: React.PropTypes.bool,
    onRequestClose: React.PropTypes.func,
    showFooter: React.PropTypes.bool,
    showTitleBar: React.PropTypes.bool,
    title: React.PropTypes.string,
    tooltip: React.PropTypes.string,
    tooltipLabel: React.PropTypes.string,
    tooltipTitle: React.PropTypes.string
  },

  getDefaultProps () {
    return {
      buttons: [],
      color: StyleConstants.Colors.PRIMARY,
      isRelative: false,
      showFooter: false,
      showTitleBar: false,
      title: '',
      tooltip: null,
      tooltipLabel: '',
      tooltipTitle: null
    };
  },

  getInitialState () {
    return {
      showTooltip: false
    };
  },

  componentDidMount () {
  /*eslint-disable */
    if (_has(this.props, 'isOpen')) {
      console.warn('WARNING: The prop "isOpen" is deprecated in this version of the component. Please handle Modal opening from its parent.');
    }
  /*eslint-enable */
  },

  _handleTooltipToggle (show) {
    this.setState({
      showTooltip: show
    });
  },

  _renderTitleBar () {
    if (this.props.showTitleBar) {
      return (

          {this.props.title}

      );
    } else {
      return null;
    }
  },

  _renderFooter () {
    if (this.props.showFooter) {
      return (

          {this._renderTooltipIconAndLabel()}
          {this._renderFooterContent()}

            {this.props.buttons.map((button, i) => {
              return (
                <Button
                  actionText={button.actionText}
                  className={'mx-modal-button ' + button.className}
                  icon={button.icon}
                  isActive={button.isActive}
                  key={button.type + i}
                  onClick={button.onClick}
                  style={[styles.button, button.style]}
                  type={button.type}
                >
                  {button.label}
                </Button>
              );
            })}

      );
    } else {
      return null;
    }
  },

  _renderFooterContent () {
    return (

        {this.props.footerContent}

    );
  },

  _renderTooltip () {
    if (this.state.showTooltip) {
      return (

            {this.props.tooltipTitle}

            {this.props.tooltip}

      );
    } else {
      return null;
    }
  },

  _renderTooltipIconAndLabel () {
    if (this.props.tooltip) {
      return (

          <Icon
            className='mx-modal-tooltip-label-icon'
            onMouseOut={this._handleTooltipToggle.bind(null, false)}
            onMouseOver={this._handleTooltipToggle.bind(null, true)}
            size={18}
            style={{ color: this.props.color }}
            type='info'
          />

            {this.props.tooltipLabel}

      );
    } else {
      return null;
    }
  },

  render () {
    return (

          <Icon
            className='mx-modal-close'
            onClick={this.props.onRequestClose}
            size={24}
            style={styles.close}
            type='close-solid'
          />
          {this._renderTitleBar()}

            {this.props.children}
            {this._renderTooltip()}

          {this._renderFooter()}

    );
  }
});

const styles = {
  scrim: {
    zIndex: 1000,
    position: 'fixed',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    textAlign: 'center'
  },
  relative: {
    position: 'absolute'
  },
  overlay: {
    backgroundColor: StyleConstants.Colors.SCRIM
  },
  close: {
    position: 'absolute',
    top: 0,
    right: 0,
    margin: '-12px -12px 0 0',
    cursor: 'pointer',
    color: StyleConstants.Colors.CHARCOAL
  },
  container: {
    fontFamily: StyleConstants.FontFamily,
    boxSizing: 'border-box',
    position: 'relative',
    zIndex: 1001,
    backgroundColor: StyleConstants.Colors.WHITE,
    boxShadow: '0 0 30px 5px rgba(0,0,0,0.1)',
    borderRadius: 2,
    top: 20,
    maxWidth: 'calc(100% - 40px)',
    display: 'inline-block',
    textAlign: 'left'
  },
  titleBar: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderTopLeftRadius: 2,
    borderTopRightRadius: 2,
    padding: '15px 20px',
    color: StyleConstants.Colors.ASH,
    fontSize: StyleConstants.FontSizes.SMALL,
    textTransform: 'uppercase'
  },
  content: {
    position: 'relative',
    maxHeight: 'calc(100% - 140px)',
    overflow: 'auto'
  },
  footer: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderBottomLeftRadius: 2,
    borderBottomRightRadius: 2,
    padding: '10px 20px',
    display: 'flex',
    justifyContent: 'space-between'
  },
  footerContent: {
    padding: '5px 0',
    textAlign: 'left'
  },
  tooltipLabel: {
    padding: '5px 0'
  },
  tooltipLabelText: {
    fontSize: StyleConstants.FontSizes.SMALL
  },
  tooltip: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderColor: StyleConstants.Colors.FOG,
    borderStyle: 'solid',
    borderWidth: 1,
    boxSizing: 'border-box',
    bottom: 10,
    left: 10,
    position: 'absolute',
    width: 250,
    maxWidth: '100%',
    padding: 10
  },
  tooltipTitle: {
    fontSize: StyleConstants.FontSizes.MEDIUM,
    marginBottom: 5
  },
  tooltipContent: {
    color: StyleConstants.Colors.ASH,
    fontSize: StyleConstants.FontSizes.SMALL,
    lineHeight: '1.5em',
    textAlign: 'left'
  },
  buttons: {
    textAlign: 'right'
  },
  button: {
    marginLeft: 5
  },
  small: {
    width: 400,
    textAlign: 'center'
  }
};

module.exports = Radium(Modal);
<commit_msg>use hasOwnProperty<commit_after>const React = require('react');
const Radium = require('radium');

const Button = require('./Button');
const Icon = require('./Icon');

const StyleConstants = require('../constants/Style');

const Modal = React.createClass({
  propTypes: {
    buttons: React.PropTypes.arrayOf(React.PropTypes.shape({
      actionText: React.PropTypes.string,
      className: React.PropTypes.string,
      isActive: React.PropTypes.bool,
      icon: React.PropTypes.string,
      label: React.PropTypes.string,
      onClick: React.PropTypes.func,
      style: React.PropTypes.oneOfType([
        React.PropTypes.array,
        React.PropTypes.object
      ]),
      type: React.PropTypes.oneOf(['primary', 'secondary'])
    })),
    color: React.PropTypes.string,
    contentStyle: React.PropTypes.object,
    footerContent: React.PropTypes.node,
    footerStyle: React.PropTypes.oneOfType([
      React.PropTypes.array,
      React.PropTypes.object
    ]),
    isRelative: React.PropTypes.bool,
    onRequestClose: React.PropTypes.func,
    showFooter: React.PropTypes.bool,
    showTitleBar: React.PropTypes.bool,
    title: React.PropTypes.string,
    tooltip: React.PropTypes.string,
    tooltipLabel: React.PropTypes.string,
    tooltipTitle: React.PropTypes.string
  },

  getDefaultProps () {
    return {
      buttons: [],
      color: StyleConstants.Colors.PRIMARY,
      isRelative: false,
      showFooter: false,
      showTitleBar: false,
      title: '',
      tooltip: null,
      tooltipLabel: '',
      tooltipTitle: null
    };
  },

  getInitialState () {
    return {
      showTooltip: false
    };
  },

  componentDidMount () {
  /*eslint-disable */
    if (this.props.hasOwnProperty('isOpen')) {
      console.warn('WARNING: The prop "isOpen" is deprecated in this version of the component. Please handle Modal opening from its parent.');
    }
  /*eslint-enable */
  },

  _handleTooltipToggle (show) {
    this.setState({
      showTooltip: show
    });
  },

  _renderTitleBar () {
    if (this.props.showTitleBar) {
      return (

          {this.props.title}

      );
    } else {
      return null;
    }
  },

  _renderFooter () {
    if (this.props.showFooter) {
      return (

          {this._renderTooltipIconAndLabel()}
          {this._renderFooterContent()}

            {this.props.buttons.map((button, i) => {
              return (
                <Button
                  actionText={button.actionText}
                  className={'mx-modal-button ' + button.className}
                  icon={button.icon}
                  isActive={button.isActive}
                  key={button.type + i}
                  onClick={button.onClick}
                  style={[styles.button, button.style]}
                  type={button.type}
                >
                  {button.label}
                </Button>
              );
            })}

      );
    } else {
      return null;
    }
  },

  _renderFooterContent () {
    return (

        {this.props.footerContent}

    );
  },

  _renderTooltip () {
    if (this.state.showTooltip) {
      return (

            {this.props.tooltipTitle}

            {this.props.tooltip}

      );
    } else {
      return null;
    }
  },

  _renderTooltipIconAndLabel () {
    if (this.props.tooltip) {
      return (

          <Icon
            className='mx-modal-tooltip-label-icon'
            onMouseOut={this._handleTooltipToggle.bind(null, false)}
            onMouseOver={this._handleTooltipToggle.bind(null, true)}
            size={18}
            style={{ color: this.props.color }}
            type='info'
          />

            {this.props.tooltipLabel}

      );
    } else {
      return null;
    }
  },

  render () {
    return (

          <Icon
            className='mx-modal-close'
            onClick={this.props.onRequestClose}
            size={24}
            style={styles.close}
            type='close-solid'
          />
          {this._renderTitleBar()}

            {this.props.children}
            {this._renderTooltip()}

          {this._renderFooter()}

    );
  }
});

const styles = {
  scrim: {
    zIndex: 1000,
    position: 'fixed',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    textAlign: 'center'
  },
  relative: {
    position: 'absolute'
  },
  overlay: {
    backgroundColor: StyleConstants.Colors.SCRIM
  },
  close: {
    position: 'absolute',
    top: 0,
    right: 0,
    margin: '-12px -12px 0 0',
    cursor: 'pointer',
    color: StyleConstants.Colors.CHARCOAL
  },
  container: {
    fontFamily: StyleConstants.FontFamily,
    boxSizing: 'border-box',
    position: 'relative',
    zIndex: 1001,
    backgroundColor: StyleConstants.Colors.WHITE,
    boxShadow: '0 0 30px 5px rgba(0,0,0,0.1)',
    borderRadius: 2,
    top: 20,
    maxWidth: 'calc(100% - 40px)',
    display: 'inline-block',
    textAlign: 'left'
  },
  titleBar: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderTopLeftRadius: 2,
    borderTopRightRadius: 2,
    padding: '15px 20px',
    color: StyleConstants.Colors.ASH,
    fontSize: StyleConstants.FontSizes.SMALL,
    textTransform: 'uppercase'
  },
  content: {
    position: 'relative',
    maxHeight: 'calc(100% - 140px)',
    overflow: 'auto'
  },
  footer: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderBottomLeftRadius: 2,
    borderBottomRightRadius: 2,
    padding: '10px 20px',
    display: 'flex',
    justifyContent: 'space-between'
  },
  footerContent: {
    padding: '5px 0',
    textAlign: 'left'
  },
  tooltipLabel: {
    padding: '5px 0'
  },
  tooltipLabelText: {
    fontSize: StyleConstants.FontSizes.SMALL
  },
  tooltip: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderColor: StyleConstants.Colors.FOG,
    borderStyle: 'solid',
    borderWidth: 1,
    boxSizing: 'border-box',
    bottom: 10,
    left: 10,
    position: 'absolute',
    width: 250,
    maxWidth: '100%',
    padding: 10
  },
  tooltipTitle: {
    fontSize: StyleConstants.FontSizes.MEDIUM,
    marginBottom: 5
  },
  tooltipContent: {
    color: StyleConstants.Colors.ASH,
    fontSize: StyleConstants.FontSizes.SMALL,
    lineHeight: '1.5em',
    textAlign: 'left'
  },
  buttons: {
    textAlign: 'right'
  },
  button: {
    marginLeft: 5
  },
  small: {
    width: 400,
    textAlign: 'center'
  }
};

module.exports = Radium(Modal);
<|endoftext|>


<commit_before>// Magic scroll things.
// This binds cool animations to the scroll level in such a way that the
// animations' progress can be controlled by scrolling. This does what
// ScrollMagic does except without the bugs.

const elem = {
  body: document.body,

  header: document.getElementsByTagName('header')[0],
  headerTitle: document.getElementsByTagName('h1')[0],
  downIndicator: document.getElementsByClassName('down-indicator')[0],

  laptop: document.getElementsByClassName('laptop')[0],
  laptopContent: document.getElementsByClassName('laptop-content')[0],
  laptopBase: document.getElementsByClassName('laptop-base')[0],
};

// HEADER TRANSITION LOGIC ====================================================

function setHeaderElementsPinned(fixed) {
  // Switch between fixed and absolute, pinning elements in the appropriate place
  [elem.headerTitle, elem.laptop].forEach((element) => {
    /* eslint-disable no-param-reassign */
    element.style.position = fixed ? 'fixed' : 'absolute';
    element.style.top = fixed ? '50vh' : `${window.innerHeight}px`;
    /* eslint-enable no-param-reassign */
  });
}

function updateHeaderElements(progress) {
  // Blends two values based on "progress" made between them.
  function tween(a, b) {
    return a + ((b - a) * progress);
  }

  // FIT MAIN HEADER TO LAPTOP SCREEN

  const whRatio = elem.laptopContent.offsetWidth / elem.laptopContent.offsetHeight;
  const width = tween(
    100,
    ((100 * elem.laptopContent.offsetWidth) / window.innerWidth)
  );
  elem.header.style.width = `${width}vw`;

  const height = tween(
    100 * (window.innerHeight / window.innerWidth),
    ((100 * elem.laptopContent.offsetWidth) / window.innerWidth) / whRatio
  );
  elem.header.style.height = `${height}vw`;

  const top = (progress < 1 ?
    tween(window.innerHeight / 2, (window.innerHeight / 2) - (elem.laptopBase.offsetHeight / 2)) :
    window.innerHeight - (elem.laptopBase.offsetHeight / 2));
  elem.header.style.top = `${top}px`;

  elem.header.style.position = progress < 1 ? 'fixed' : 'absolute';

  // DEAL WITH ASSOCIATED TIDBITS

  elem.downIndicator.style.opacity = 1 - progress;  // Fade out down indicator
  elem.headerTitle.style.fontSize = `${tween(5, 3.5)}vw`;  // Shrink header

  // ADJUST CANVAS SETTINGS

  // Mean of X scale difference and Y scale difference
  const canvasScale = (
    (window.gol.canvas.offsetWidth / window.innerWidth) +
    (window.gol.canvas.offsetHeight / window.innerHeight)
  ) / 2;
  window.gol.idealCellSize = 20 * canvasScale;
  window.gol.sizeChanged();
}

// SCROLL LISTENER ============================================================

document.addEventListener('scroll', () => {
  const scroll = window.scrollY;

  // Header

  const headerProgress = scroll / (window.innerHeight / 2);

  switch (true) {
    case (scroll < 5):
      setHeaderElementsPinned(true);
      updateHeaderElements(0);
      break;

    case (scroll < window.innerHeight / 2):
      setHeaderElementsPinned(true);
      updateHeaderElements(headerProgress);
      break;

    default:
      setHeaderElementsPinned(false);
      updateHeaderElements(1);
  }
});
<commit_msg>Clean up scroll effect code a bit<commit_after>// Magic scroll things.
// This binds cool animations to the scroll level in such a way that the
// animations' progress can be controlled by scrolling. This does what
// ScrollMagic does except without the bugs.

const elem = {
  body: document.body,

  header: document.getElementsByTagName('header')[0],
  headerTitle: document.getElementsByTagName('h1')[0],
  downIndicator: document.getElementsByClassName('down-indicator')[0],

  laptop: document.getElementsByClassName('laptop')[0],
  laptopContent: document.getElementsByClassName('laptop-content')[0],
  laptopBase: document.getElementsByClassName('laptop-base')[0],
};

// HEADER TRANSITION LOGIC ====================================================

function setHeaderElementsPinned(fixed) {
  // Switch between fixed and absolute, pinning elements in the appropriate place
  [elem.headerTitle, elem.laptop].forEach((element) => {
    /* eslint-disable no-param-reassign */
    element.style.position = fixed ? 'fixed' : 'absolute';
    element.style.top = fixed ? '50vh' : `${window.innerHeight}px`;
    /* eslint-enable no-param-reassign */
  });
}

function updateHeaderElements(progress) {
  // Blends two values based on "progress" made between them.
  function tween(a, b) {
    return a + ((b - a) * progress);
  }

  // FIT MAIN HEADER TO LAPTOP SCREEN

  // Values for tweening. [x, y, w, h]. All values are viewport-relative.

  const initialPos = [50, 50, 100, 100]; // The starting position (fixed)
  const destinationPos = [               // The shrunk position (still fixed)
    50, 50,
    (100 * elem.laptopContent.offsetWidth) / window.innerWidth,
    (100 * elem.laptopContent.offsetHeight) / window.innerHeight,
  ];
  const restingPos = [                   // The shrunk position (absolute now)
    50,
    100,
    (100 * elem.laptopContent.offsetWidth) / window.innerWidth,
    destinationPos[3],
  ];

  // NOTE: Left is ignored since it's constant

  const fixedTop = tween(initialPos[1], destinationPos[1]);
  const top = progress < 1 ? fixedTop : restingPos[1];
  elem.header.style.top = `${top}vh`;

  const width = tween(initialPos[2], destinationPos[2]);
  elem.header.style.width = `${width}vw`;

  const height = tween(initialPos[3], destinationPos[3]);
  elem.header.style.height = `${height}vh`;

  elem.header.style.position = progress < 1 ? 'fixed' : 'absolute';

  // MISCELLANEOUS

  // Update opacity of down indicator
  elem.downIndicator.style.opacity = 1 - progress;
  // Reduce font size of my name
  elem.headerTitle.style.fontSize = `${tween(5, 3.5)}vw`;

  // ADJUST CANVAS SETTINGS

  const canvasScale = ( // Mean of X scale difference and Y scale difference
    (window.gol.canvas.offsetWidth / window.innerWidth) +
    (window.gol.canvas.offsetHeight / window.innerHeight)
  ) / 2;
  window.gol.idealCellSize = 20 * canvasScale;
  window.gol.sizeChanged();
}

// SCROLL LISTENER ============================================================

document.addEventListener('scroll', () => {
  const scroll = window.scrollY;

  // Header

  const headerProgress = scroll / (window.innerHeight / 2);

  switch (true) {
    case (scroll < 5):
      setHeaderElementsPinned(true);
      updateHeaderElements(0);
      break;

    case (scroll < window.innerHeight / 2):
      setHeaderElementsPinned(true);
      updateHeaderElements(headerProgress);
      break;

    default:
      setHeaderElementsPinned(false);
      updateHeaderElements(1);
  }
});
<|endoftext|>


<commit_before>// LICENSE : MIT
"use strict";
var pkgToReadme = require("pkg-to-readme");
var path = require("path");
var confirmer = require('confirmer');
var fs = require('fs');
// Update README.md
var templatePath = path.resolve(__dirname, "..", "configs", "README.md.template");
Promise.resolve().then(function() {
    if (!fs.existsSync(path.resolve('README.md'))) {
        return;
    }
    return confirmer('Would you overwrite README.md? (y/n)')
        .then(function(result) {
            return result ? Promise.resolve() : Promise.reject(new Error("Not overwrite"));
        });
}).then(function() {
    return pkgToReadme({
        template: templatePath
    })
}).then(()=> {
    console.log('Generated README.md');
}).catch(error => {
    console.error(error.message);
    process.exit(1);
});<commit_msg>fix(init): fix to non arrow function<commit_after>// LICENSE : MIT
"use strict";
var pkgToReadme = require("pkg-to-readme");
var path = require("path");
var confirmer = require('confirmer');
var fs = require('fs');
// Update README.md
var templatePath = path.resolve(__dirname, "..", "configs", "README.md.template");
Promise.resolve().then(function() {
    if (!fs.existsSync(path.resolve('README.md'))) {
        return;
    }
    return confirmer('Would you overwrite README.md? (y/n)')
        .then(function(result) {
            return result ? Promise.resolve() : Promise.reject(new Error("Not overwrite"));
        });
}).then(function() {
    return pkgToReadme({
        template: templatePath
    })
}).then(function() {
    console.log('Generated README.md');
}).catch(error => {
    console.error(error.message);
    process.exit(1);
});<|endoftext|>


<commit_before>(function(){

	var DEBUG = false;

	var doPost = false;

	try {
		doPost = !!window.top.postMessage;
	} catch(e){}

	var search = window.location.search,
		url, index;
	if( ( index = search.indexOf( "swarmURL=" ) ) != -1 )
		url = decodeURIComponent( search.slice( index + 9 ) );

	if ( !DEBUG && (!url || url.indexOf("http") !== 0) ) {
		return;
	}

	var submitTimeout = 5;

	var curHeartbeat;
	var beatRate = 20;

	// Expose the TestSwarm API
	window.TestSwarm = {
		submit: submit,
		heartbeat: function(){
			if ( curHeartbeat ) {
				clearTimeout( curHeartbeat );
			}

			curHeartbeat = setTimeout(function(){
				submit({ fail: -1, total: -1 });
			}, beatRate * 1000);
		},
		serialize: function(){
			return trimSerialize();
		}
	};

	// Prevent careless things from executing
	window.print = window.confirm = window.alert = window.open = function(){};

	window.onerror = function(e){
		document.body.appendChild( document.createTextNode( "ERROR: " + e ));
		submit({ fail: 0, error: 1, total: 1 });
		return false;
	};

	// QUnit (jQuery)
	// http://docs.jquery.com/QUnit
	if ( typeof QUnit !== "undefined" ) {
		QUnit.done = function(fail, total){
			submit({
				fail: fail,
				error: 0,
				total: total
			});
		};

		QUnit.log = window.TestSwarm.heartbeat;
		window.TestSwarm.heartbeat();

		window.TestSwarm.serialize = function(){
			// Clean up the HTML (remove any un-needed test markup)
			remove("nothiddendiv");
			remove("loadediframe");
			remove("dl");
			remove("main");

			// Show any collapsed results
			var ol = document.getElementsByTagName("ol");
			for ( var i = 0; i < ol.length; i++ ) {
				ol[i].style.display = "block";
			}

			return trimSerialize();
		};

	// UnitTestJS (Prototype, Scriptaculous)
	// http://github.com/tobie/unittest_js/tree/master
	} else if ( typeof Test !== "undefined" && Test && Test.Unit && Test.Unit.runners ) {
		var total_runners = Test.Unit.runners.length, cur_runners = 0;
		var total = 0, fail = 0, error = 0;

		for (var i = 0; i < Test.Unit.runners.length; i++) (function(i){
			var finish = Test.Unit.runners[i].finish;
			Test.Unit.runners[i].finish = function(){
				finish.call( this );

				var results = this.getResult();
				total += results.assertions;
				fail += results.failures;
				error += results.errors;

				if ( ++cur_runners === total_runners ) {
					submit({
						fail: fail,
						error: error,
						total: total
					});
				}
			};
		})(i);

	// JSSpec (MooTools)
	// http://jania.pe.kr/aw/moin.cgi/JSSpec
	} else if ( typeof JSSpec !== "undefined" && JSSpec && JSSpec.Logger ) {
		var onRunnerEnd = JSSpec.Logger.prototype.onRunnerEnd;
		JSSpec.Logger.prototype.onRunnerEnd = function(){
			onRunnerEnd.call(this);

			// Show any collapsed results
			var ul = document.getElementsByTagName("ul");
			for ( var i = 0; i < ul.length; i++ ) {
				ul[i].style.display = "block";
			}

			submit({
				fail: JSSpec.runner.getTotalFailures(),
				error: JSSpec.runner.getTotalErrors(),
				total: JSSpec.runner.totalExamples
			});
		};

		window.TestSwarm.serialize = function(){
			// Show any collapsed results
			var ul = document.getElementsByTagName("ul");
			for ( var i = 0; i < ul.length; i++ ) {
				ul[i].style.display = "block";
			}

			return trimSerialize();
		};

	// JSUnit
	// http://www.jsunit.net/
	// Note: Injection file must be included before the frames
	//       are document.write()d into the page.
	} else if ( typeof JsUnitTestManager !== "undefined" ) {
		var _done = JsUnitTestManager.prototype._done;
		JsUnitTestManager.prototype._done = function(){
			_done.call(this);

			submit({
				fail: this.failureCount,
				error: this.errorCount,
				total: this.totalCount
			});
		};

		window.TestSwarm.serialize = function(){
			return "
" + this.log.join("\n") + "
";
		};

	// Selenium Core
	// http://seleniumhq.org/projects/core/
	} else if ( typeof SeleniumTestResult !== "undefined" && typeof LOG !== "undefined" ) {
		// Completely overwrite the postback
		SeleniumTestResult.prototype.post = function(){
			submit({
				fail: this.metrics.numCommandFailures,
				error: this.metrics.numCommandErrors,
				total: this.metrics.numCommandPasses + this.metrics.numCommandFailures + this.metrics.numCommandErrors
			});
		};

		window.TestSwarm.serialize = function(){
			var results = [];
			while ( LOG.pendingMessages.length ) {
				var msg = LOG.pendingMessages.shift();
				results.push( msg.type + ": " + msg.msg );
			}

			return "
" + results.join("\n") + "
";
		};

	// Dojo Objective Harness
	// http://docs.dojocampus.org/quickstart/doh
	} else if ( typeof doh !== "undefined" && doh._report ) {
		var _report = doh._report;
		doh._report = function(){
			_report.apply(this, arguments);

			submit({
				fail: doh._failureCount,
				error: doh._errorCount,
				total: doh._testCount
			});
		};

		window.TestSwarm.serialize = function(){
			return "
" + document.getElementById("logBody").innerHTML + "
";
		};
  // Screw.Unit
  // git://github.com/nathansobo/screw-unit.git
	} else if ( typeof Screw !== "undefined" && typeof jQuery !== 'undefined' && Screw && Screw.Unit ) {
    $(Screw).bind("after", function() {
     var passed = $('.passed').length;
     var failed = $('.failed').length;
     submit({
        fail: failed,
        error: 0,
        total: failed + passed
      });
    });

    $(Screw).bind("loaded", function() {
      $('.it')
        .bind("passed", window.TestSwarm.heartbeat)
        .bind("failed", window.TestSwarm.heartbeat);
      window.TestSwarm.heartbeat();
    });

    window.TestSwarm.serialize = function(){
    	return trimSerialize();
    };
  }

	function trimSerialize(doc) {
		doc = doc || document;

		var scripts = doc.getElementsByTagName("script");
		while ( scripts.length ) {
			remove( scripts[0] );
		}

		var root = window.location.href.replace(/(https?:\/\/.*?)\/.*/, "$1");
		var cur = window.location.href.replace(/[^\/]*$/, "");

		var links = doc.getElementsByTagName("link");
		for ( var i = 0; i < links.length; i++ ) {
			var href = links[i].href;
			if ( href.indexOf("/") === 0 ) {
				href = root + href;
			} else if ( !/^https?:\/\//.test( href ) ) {
				href = cur + href;
			}
			links[i].href = href;
		}

		return ("" + doc.documentElement.innerHTML + "")
			.replace(/\s+/g, " ");
	}

	function remove(elem){
		if ( typeof elem === "string" ) {
			elem = document.getElementById( elem );
		}

		if ( elem ) {
			elem.parentNode.removeChild( elem );
		}
	}

	function submit(params){
		if ( curHeartbeat ) {
			clearTimeout( curHeartbeat );
		}

		var paramItems = (url.split("?")[1] || "").split("&");

		for ( var i = 0; i < paramItems.length; i++ ) {
			if ( paramItems[i] ) {
				var parts = paramItems[i].split("=");
				if ( !params[ parts[0] ] ) {
					params[ parts[0] ] = parts[1];
				}
			}
		}

		if ( !params.state ) {
			params.state = "saverun";
		}

		if ( !params.results ) {
			params.results = window.TestSwarm.serialize();
		}

		if ( doPost ) {
			// Build Query String
			var query = "";

			for ( var i in params ) {
				query += ( query ? "&" : "" ) + i + "=" +
					encodeURIComponent(params[i]);
			}

			if ( DEBUG ) {
				alert( query );
			} else {
				window.top.postMessage( query, "*" );
			}

		} else {
			var form = document.createElement("form");
			form.action = url;
			form.method = "POST";

			for ( var i in params ) {
				var input = document.createElement("input");
				input.type = "hidden";
				input.name = i;
				input.value = params[i];
				form.appendChild( input );
			}

			if ( DEBUG ) {
				alert( form.innerHTML );
			} else {

				// Watch for the result submission timing out
				setTimeout(function(){
					submit( params );
				}, submitTimeout * 1000);

				document.body.appendChild( form );
				form.submit();
			}
		}
	}

})();
<commit_msg>Adapt QUnit adapter to latest callback changes in QUnit.<commit_after>(function(){

	var DEBUG = false;

	var doPost = false;

	try {
		doPost = !!window.top.postMessage;
	} catch(e){}

	var search = window.location.search,
		url, index;
	if( ( index = search.indexOf( "swarmURL=" ) ) != -1 )
		url = decodeURIComponent( search.slice( index + 9 ) );

	if ( !DEBUG && (!url || url.indexOf("http") !== 0) ) {
		return;
	}

	var submitTimeout = 5;

	var curHeartbeat;
	var beatRate = 20;

	// Expose the TestSwarm API
	window.TestSwarm = {
		submit: submit,
		heartbeat: function(){
			if ( curHeartbeat ) {
				clearTimeout( curHeartbeat );
			}

			curHeartbeat = setTimeout(function(){
				submit({ fail: -1, total: -1 });
			}, beatRate * 1000);
		},
		serialize: function(){
			return trimSerialize();
		}
	};

	// Prevent careless things from executing
	window.print = window.confirm = window.alert = window.open = function(){};

	window.onerror = function(e){
		document.body.appendChild( document.createTextNode( "ERROR: " + e ));
		submit({ fail: 0, error: 1, total: 1 });
		return false;
	};

	// QUnit (jQuery)
	// http://docs.jquery.com/QUnit
	if ( typeof QUnit !== "undefined" ) {
		QUnit.done = function(results){
			submit({
				fail: results.failed,
				error: 0,
				total: results.total
			});
		};

		QUnit.log = window.TestSwarm.heartbeat;
		window.TestSwarm.heartbeat();

		window.TestSwarm.serialize = function(){
			// Clean up the HTML (remove any un-needed test markup)
			remove("nothiddendiv");
			remove("loadediframe");
			remove("dl");
			remove("main");

			// Show any collapsed results
			var ol = document.getElementsByTagName("ol");
			for ( var i = 0; i < ol.length; i++ ) {
				ol[i].style.display = "block";
			}

			return trimSerialize();
		};

	// UnitTestJS (Prototype, Scriptaculous)
	// http://github.com/tobie/unittest_js/tree/master
	} else if ( typeof Test !== "undefined" && Test && Test.Unit && Test.Unit.runners ) {
		var total_runners = Test.Unit.runners.length, cur_runners = 0;
		var total = 0, fail = 0, error = 0;

		for (var i = 0; i < Test.Unit.runners.length; i++) (function(i){
			var finish = Test.Unit.runners[i].finish;
			Test.Unit.runners[i].finish = function(){
				finish.call( this );

				var results = this.getResult();
				total += results.assertions;
				fail += results.failures;
				error += results.errors;

				if ( ++cur_runners === total_runners ) {
					submit({
						fail: fail,
						error: error,
						total: total
					});
				}
			};
		})(i);

	// JSSpec (MooTools)
	// http://jania.pe.kr/aw/moin.cgi/JSSpec
	} else if ( typeof JSSpec !== "undefined" && JSSpec && JSSpec.Logger ) {
		var onRunnerEnd = JSSpec.Logger.prototype.onRunnerEnd;
		JSSpec.Logger.prototype.onRunnerEnd = function(){
			onRunnerEnd.call(this);

			// Show any collapsed results
			var ul = document.getElementsByTagName("ul");
			for ( var i = 0; i < ul.length; i++ ) {
				ul[i].style.display = "block";
			}

			submit({
				fail: JSSpec.runner.getTotalFailures(),
				error: JSSpec.runner.getTotalErrors(),
				total: JSSpec.runner.totalExamples
			});
		};

		window.TestSwarm.serialize = function(){
			// Show any collapsed results
			var ul = document.getElementsByTagName("ul");
			for ( var i = 0; i < ul.length; i++ ) {
				ul[i].style.display = "block";
			}

			return trimSerialize();
		};

	// JSUnit
	// http://www.jsunit.net/
	// Note: Injection file must be included before the frames
	//       are document.write()d into the page.
	} else if ( typeof JsUnitTestManager !== "undefined" ) {
		var _done = JsUnitTestManager.prototype._done;
		JsUnitTestManager.prototype._done = function(){
			_done.call(this);

			submit({
				fail: this.failureCount,
				error: this.errorCount,
				total: this.totalCount
			});
		};

		window.TestSwarm.serialize = function(){
			return "
" + this.log.join("\n") + "
";
		};

	// Selenium Core
	// http://seleniumhq.org/projects/core/
	} else if ( typeof SeleniumTestResult !== "undefined" && typeof LOG !== "undefined" ) {
		// Completely overwrite the postback
		SeleniumTestResult.prototype.post = function(){
			submit({
				fail: this.metrics.numCommandFailures,
				error: this.metrics.numCommandErrors,
				total: this.metrics.numCommandPasses + this.metrics.numCommandFailures + this.metrics.numCommandErrors
			});
		};

		window.TestSwarm.serialize = function(){
			var results = [];
			while ( LOG.pendingMessages.length ) {
				var msg = LOG.pendingMessages.shift();
				results.push( msg.type + ": " + msg.msg );
			}

			return "
" + results.join("\n") + "
";
		};

	// Dojo Objective Harness
	// http://docs.dojocampus.org/quickstart/doh
	} else if ( typeof doh !== "undefined" && doh._report ) {
		var _report = doh._report;
		doh._report = function(){
			_report.apply(this, arguments);

			submit({
				fail: doh._failureCount,
				error: doh._errorCount,
				total: doh._testCount
			});
		};

		window.TestSwarm.serialize = function(){
			return "
" + document.getElementById("logBody").innerHTML + "
";
		};
  // Screw.Unit
  // git://github.com/nathansobo/screw-unit.git
	} else if ( typeof Screw !== "undefined" && typeof jQuery !== 'undefined' && Screw && Screw.Unit ) {
    $(Screw).bind("after", function() {
     var passed = $('.passed').length;
     var failed = $('.failed').length;
     submit({
        fail: failed,
        error: 0,
        total: failed + passed
      });
    });

    $(Screw).bind("loaded", function() {
      $('.it')
        .bind("passed", window.TestSwarm.heartbeat)
        .bind("failed", window.TestSwarm.heartbeat);
      window.TestSwarm.heartbeat();
    });

    window.TestSwarm.serialize = function(){
    	return trimSerialize();
    };
  }

	function trimSerialize(doc) {
		doc = doc || document;

		var scripts = doc.getElementsByTagName("script");
		while ( scripts.length ) {
			remove( scripts[0] );
		}

		var root = window.location.href.replace(/(https?:\/\/.*?)\/.*/, "$1");
		var cur = window.location.href.replace(/[^\/]*$/, "");

		var links = doc.getElementsByTagName("link");
		for ( var i = 0; i < links.length; i++ ) {
			var href = links[i].href;
			if ( href.indexOf("/") === 0 ) {
				href = root + href;
			} else if ( !/^https?:\/\//.test( href ) ) {
				href = cur + href;
			}
			links[i].href = href;
		}

		return ("" + doc.documentElement.innerHTML + "")
			.replace(/\s+/g, " ");
	}

	function remove(elem){
		if ( typeof elem === "string" ) {
			elem = document.getElementById( elem );
		}

		if ( elem ) {
			elem.parentNode.removeChild( elem );
		}
	}

	function submit(params){
		if ( curHeartbeat ) {
			clearTimeout( curHeartbeat );
		}

		var paramItems = (url.split("?")[1] || "").split("&");

		for ( var i = 0; i < paramItems.length; i++ ) {
			if ( paramItems[i] ) {
				var parts = paramItems[i].split("=");
				if ( !params[ parts[0] ] ) {
					params[ parts[0] ] = parts[1];
				}
			}
		}

		if ( !params.state ) {
			params.state = "saverun";
		}

		if ( !params.results ) {
			params.results = window.TestSwarm.serialize();
		}

		if ( doPost ) {
			// Build Query String
			var query = "";

			for ( var i in params ) {
				query += ( query ? "&" : "" ) + i + "=" +
					encodeURIComponent(params[i]);
			}

			if ( DEBUG ) {
				alert( query );
			} else {
				window.top.postMessage( query, "*" );
			}

		} else {
			var form = document.createElement("form");
			form.action = url;
			form.method = "POST";

			for ( var i in params ) {
				var input = document.createElement("input");
				input.type = "hidden";
				input.name = i;
				input.value = params[i];
				form.appendChild( input );
			}

			if ( DEBUG ) {
				alert( form.innerHTML );
			} else {

				// Watch for the result submission timing out
				setTimeout(function(){
					submit( params );
				}, submitTimeout * 1000);

				document.body.appendChild( form );
				form.submit();
			}
		}
	}

})();
<|endoftext|>