<commit_before>'use strict';

var isFunction = require('es5-ext/lib/Function/is-function')
  , convert    = require('es5-ext/lib/String/prototype/hyphen-to-camel')
  , path       = require('path')
  , readdir    = require('fs').readdir
  , indexTest  = require('tad/lib/utils/index-test')

  , dir = path.dirname(__dirname);

module.exports = {
	"": indexTest(indexTest.readDir(dir)(function (o) {
		delete o.benchmark;
		delete o.deferred;
		delete o.examples;
		delete o.ext;
		delete o.promise;
		delete o.profiler;
		return o;
	}), ['Deferred', 'callAsync', 'delay', 'extend', 'gate', 'profile',
		'profileEnd', 'promisify', 'promisifySync', 'reject', 'map', 'reduce',
		'some']),
	"isPromise": function (t, a) {
		a(t.isPromise(t(null)), true);
		a(t.isPromise({}), false);
	},
	"InvokeAsync": function (t, a, d) {
		var x = {};
		t.invokeAsync({}, function (cb) {
			setTimeout(function () {
				cb(null, x);
			}, 0);
			return {};
		})(function (r) {
			a(r, x);
		}).done(d, d);
	},
	"CallAsync": function (t, a, d) {
		var x = {};
		t.callAsync(function (cb) {
			setTimeout(function () {
				cb(null, x);
			}, 0);
			return {};
		})(function (r) {
			a(r, x);
		}).done(d, d);
	},
	"Delay": function (t, a, d) {
		var x = {};
		t.delay(function (r) {
			return r;
		}, 5)(x)(function (r) {
			a(r, x);
		}).done(d, d);
	},
	"Gate": function (t, a) {
		var fn, dx, dy, ready;
		fn = t.gate(function (p) {
			return p;
		}, 1);
		dx = t();
		fn(dx.promise);
		dy = t();
		fn(dy.promise).done(function () {
			a(ready, true);
		});
		dy.resolve({});
		ready = true;
		dx.resolve({});
		ready = false;
	},
	"Profile": function (t, a) {
		a(typeof t.profile, 'function', "Profile");
		a(typeof t.profileEnd, 'function', "ProfileEnd");
	},
	"Promisify": function (t, a, d) {
		var x = {};
		t.promisify(function (cb) {
			setTimeout(function () {
				cb(null, x);
			}, 0);
			return {};
		})()(function (r) {
			a(r, x);
		}).done(d, d);
	},
	"PromisifySync": function (t, a, d) {
		t.promisifySync(function () {
			return;
		})()(function (r) {
			a(r, undefined);
		}).done(d, d);
	},
	"Map": function (t, a, d) {
		t.map([t(1), t(2), 3], function (res) {
			return t(res * res);
		})(function (r) {
			a.deep(r, [1, 4, 9]);
		}, a.never).done(d, d);
	},
	"Reduce": function (t, a, d) {
		t.reduce([t(1), t(2), 3], function (arg1, arg2) {
			return t(arg1 * arg2);
		}, 1)(function (r) {
			a(r, 6);
		}, a.never).done(d, d);
	},
	"Some": function (t, a, d) {
		var count = 0;
		t.some([t(1), t(2), 3], function (res, index) {
			++count;
			return index;
		})(function (r) {
			a(r, true);
			a(count, 2, "Count");
		}, a.never).done(d, d);
	},
	"Deferred function is main object": function (t, a) {
		var d = t();
		d.resolve({});
		a.ok(isFunction(d.resolve) && isFunction(d.promise.then));
	},
	"Ports are loaded": function (t, a, d) {
		var p = t().resolve();
		readdir(dir + '/ext/promise', function (err, files) {
			if (err) {
				d(err);
				return;
			}
			files.map(function (file) {
				if ((file.slice(-3) === '.js') && (file[0] !== '_')) {
					return convert.call(file.slice(0, -3));
				}
			}).filter(Boolean).forEach(function (file) {
				a(isFunction(p[file]), true, file);
			});
			d();
		});
	}
};
<commit_msg>Fix index test<commit_after>'use strict';

var isFunction = require('es5-ext/lib/Function/is-function')
  , convert    = require('es5-ext/lib/String/prototype/hyphen-to-camel')
  , path       = require('path')
  , readdir    = require('fs').readdir
  , indexTest  = require('tad/lib/utils/index-test')

  , dir = path.dirname(__dirname);

module.exports = {
	"": indexTest(indexTest.readDir(dir)(function (o) {
		delete o.assimilate;
		delete o.benchmark;
		delete o.deferred;
		delete o.examples;
		delete o.ext;
		delete o.promise;
		delete o.profiler;
		return o;
	}), ['Deferred', 'callAsync', 'delay', 'extend', 'gate', 'profile',
		'profileEnd', 'promisify', 'promisifySync', 'reject', 'map', 'reduce',
		'some']),
	"isPromise": function (t, a) {
		a(t.isPromise(t(null)), true);
		a(t.isPromise({}), false);
	},
	"InvokeAsync": function (t, a, d) {
		var x = {};
		t.invokeAsync({}, function (cb) {
			setTimeout(function () {
				cb(null, x);
			}, 0);
			return {};
		})(function (r) {
			a(r, x);
		}).done(d, d);
	},
	"CallAsync": function (t, a, d) {
		var x = {};
		t.callAsync(function (cb) {
			setTimeout(function () {
				cb(null, x);
			}, 0);
			return {};
		})(function (r) {
			a(r, x);
		}).done(d, d);
	},
	"Delay": function (t, a, d) {
		var x = {};
		t.delay(function (r) {
			return r;
		}, 5)(x)(function (r) {
			a(r, x);
		}).done(d, d);
	},
	"Gate": function (t, a) {
		var fn, dx, dy, ready;
		fn = t.gate(function (p) {
			return p;
		}, 1);
		dx = t();
		fn(dx.promise);
		dy = t();
		fn(dy.promise).done(function () {
			a(ready, true);
		});
		dy.resolve({});
		ready = true;
		dx.resolve({});
		ready = false;
	},
	"Profile": function (t, a) {
		a(typeof t.profile, 'function', "Profile");
		a(typeof t.profileEnd, 'function', "ProfileEnd");
	},
	"Promisify": function (t, a, d) {
		var x = {};
		t.promisify(function (cb) {
			setTimeout(function () {
				cb(null, x);
			}, 0);
			return {};
		})()(function (r) {
			a(r, x);
		}).done(d, d);
	},
	"PromisifySync": function (t, a, d) {
		t.promisifySync(function () {
			return;
		})()(function (r) {
			a(r, undefined);
		}).done(d, d);
	},
	"Map": function (t, a, d) {
		t.map([t(1), t(2), 3], function (res) {
			return t(res * res);
		})(function (r) {
			a.deep(r, [1, 4, 9]);
		}, a.never).done(d, d);
	},
	"Reduce": function (t, a, d) {
		t.reduce([t(1), t(2), 3], function (arg1, arg2) {
			return t(arg1 * arg2);
		}, 1)(function (r) {
			a(r, 6);
		}, a.never).done(d, d);
	},
	"Some": function (t, a, d) {
		var count = 0;
		t.some([t(1), t(2), 3], function (res, index) {
			++count;
			return index;
		})(function (r) {
			a(r, true);
			a(count, 2, "Count");
		}, a.never).done(d, d);
	},
	"Deferred function is main object": function (t, a) {
		var d = t();
		d.resolve({});
		a.ok(isFunction(d.resolve) && isFunction(d.promise.then));
	},
	"Ports are loaded": function (t, a, d) {
		var p = t().resolve();
		readdir(dir + '/ext/promise', function (err, files) {
			if (err) {
				d(err);
				return;
			}
			files.map(function (file) {
				if ((file.slice(-3) === '.js') && (file[0] !== '_')) {
					return convert.call(file.slice(0, -3));
				}
			}).filter(Boolean).forEach(function (file) {
				a(isFunction(p[file]), true, file);
			});
			d();
		});
	}
};
<|endoftext|>


<commit_before>// Shortcut-function (until we update to Prototye v1.5)
if(typeof $$ != "Function") $$ = document.getElementsBySelector;

/**
 * File: WidgetAreaEditor.js
 */

/**
 * Class: WidgetAreaEditorClass
 */
WidgetAreaEditorClass = Class.create();
WidgetAreaEditorClass.prototype = {
	initialize: function() {
		this.name = this.getAttribute('name');
		this.rewriteWidgetAreaAttributes();
		UsedWidget.applyToChildren(document.getElementById('usedWidgets-'+this.name), 'div.Widget');

		var availableWidgets = document.getElementById('availableWidgets-'+this.name).childNodes;

		for(var i = 0; i < availableWidgets.length; i++) {
			var widget = availableWidgets[i];
			// Don't run on comments, whitespace, etc
			if (widget.nodeType == 1) {
				// Gotta change their ID's because otherwise we get clashes between two tabs
				widget.id = widget.id + '-'+this.name;
			}
		}

		// Create dummy sortable to prevent javascript errors
		Sortable.create('availableWidgets-'+this.name, {
			tag: 'li',
			handle: 'handle',
			containment: []
		});

		// Used widgets are sortable
		Sortable.create('usedWidgets-'+this.name, {
			tag: 'div',
			handle: 'handle',
			containment: ['availableWidgets-'+this.name, 'usedWidgets-'+this.name],
			onUpdate: this.updateWidgets
		});

		// Figure out maxid, this is used when creating new widgets
		this.maxid = 0;

		var usedWidgets = document.getElementById('usedWidgets-'+this.name).childNodes;
		for(var i = 0; i < usedWidgets.length; i++) {
			var widget = usedWidgets[i];
			if(widget.id) {
				widgetid = widget.id.match(/\Widget\[(.+?)\]\[([0-9]+)\]/i);
				if(widgetid && parseInt(widgetid[2]) > this.maxid) {
					this.maxid = parseInt(widgetid[2]);
				}
			}
		}

		// Ensure correct sort values are written when page is saved
		// TODO Adjust to new event listeners
		jQuery('.cms-edit-form').bind('ajaxsubmit', this.beforeSave.bind(this));
	},

	rewriteWidgetAreaAttributes: function() {
		this.name = this.getAttribute('name');

		var monkeyWith = function(widgets, name) {
			if (!widgets) {
				return;
			}
			for(var i = 0; i < widgets.length; i++) {
				widget = widgets[i];
				if (!widget.getAttribute('rewritten') && (widget.id || widget.name)) {
					if (widget.id && widget.id.indexOf('Widget[') === 0) {
						var newValue = widget.id.replace(/Widget\[/, 'Widget['+name+'][');
						//console.log('Renaming '+widget.tagName+' ID '+widget.id+' to '+newValue);
						widget.id = newValue;
					}
					if (widget.name && widget.name.indexOf('Widget[') === 0) {
						var newValue = widget.name.replace(/Widget\[/, 'Widget['+name+'][');
						//console.log('Renaming '+widget.tagName+' Name '+widget.name+' to '+newValue);
						widget.name = newValue;
					}
					widget.setAttribute('rewritten', 'yes');
				}
				else {
					//console.log('Skipping '+(widget.id ? widget.id : (widget.name ? widget.name : 'unknown '+widget.tagName)));
				}
			}
		}

		monkeyWith($$('#WidgetAreaEditor-'+this.name+' .Widget'), this.name);
		monkeyWith($$('#WidgetAreaEditor-'+this.name+' .Widget *'), this.name);
	},

	beforeSave: function() {
		// Ensure correct sort values are written when page is saved
		var usedWidgets = document.getElementById('usedWidgets-'+this.name);

		if(usedWidgets) {
			this.sortWidgets();

			var children = usedWidgets.childNodes;

			for( var i = 0; i < children.length; ++i ) {
				var child = children[i];

				if(child.beforeSave) {
					child.beforeSave();
				}
			}
		}
	},

	addWidget: function(className, holder) {

		if (document.getElementById('WidgetAreaEditor-'+holder).getAttribute('maxwidgets')) {
			var maxCount = document.getElementById('WidgetAreaEditor-'+holder).getAttribute('maxwidgets');
			var count = $$('#usedWidgets-'+holder+' .Widget').length;
			if (count+1 > maxCount) {
				alert(ss.i18n._t('WidgetAreaEditor.TOOMANY'));
				return;
			}
		}

		this.name = holder;
		jQuery.ajax({
			'url': 'Widget_Controller/EditableSegment/' + className,
			'success' : document.getElementById('usedWidgets-'+holder).parentNode.parentNode.insertWidgetEditor.bind(this)
		});
	},

	updateWidgets: function() {
		var self = this;

		// Gotta get the name of the current dohickey based off the ID
		this.name = this.element.id.split('-').pop();

		// alert(this.name);

		// Gotta get the name of the current dohickey based off the ID
		this.name = this.element.id.split('-').pop();

		// This is called when an available widgets is dragged over to used widgets.
		// It inserts the editor form into the new used widget

		var usedWidgets = document.getElementById('usedWidgets-'+this.name).childNodes;
		for(var i = 0; i < usedWidgets.length; i++) {
			var widget = usedWidgets[i];
			if(widget.id && (widget.id.indexOf("Widget[") != 0) && (widget.id != 'NoWidgets-'+this.name)) {
				// Need to remove the -$Name part.
				var wIdArray = widget.id.split('-');
				wIdArray.pop();

				jQuery.ajax({
					'url': 'Widget_Controller/EditableSegment/' + wIdArray.join('-'),
					'success' : function() {
						document.getElementById('usedWidgets-'+self.name).parentNode.parentNode.insertWidgetEditor();
					}
				});
			}
		}
	},

	insertWidgetEditor: function(response) {
		// Remove placeholder text
		if(document.getElementById('NoWidgets-'+this.name)) {
			document.getElementById('usedWidgets-'+this.name).removeChild(document.getElementById('NoWidgets-'+this.name));
		}

		var usedWidgets = document.getElementById('usedWidgets-'+this.name).childNodes;

		// Give the widget a unique id
		widgetContent = response.replace(/Widget\[0\]/gi, "Widget[new-" + (++document.getElementById('usedWidgets-'+this.name).parentNode.parentNode.maxid) + "]");
		new Insertion.Top(document.getElementById('usedWidgets-'+this.name), widgetContent);

		document.getElementById('usedWidgets-'+this.name).parentNode.parentNode.rewriteWidgetAreaAttributes();
		UsedWidget.applyToChildren(document.getElementById('usedWidgets-'+this.name), 'div.Widget');

		// Repply some common form controls
		WidgetTreeDropdownField.applyTo('div.usedWidgets .TreeDropdownField');

		Sortable.create('usedWidgets-'+this.name, {
			tag: 'div',
			handle: 'handle',
			containment: ['availableWidgets-'+this.name, 'usedWidgets-'+this.name],
			onUpdate: document.getElementById('usedWidgets-'+this.name).parentNode.parentNode.updateWidgets
		});
	},

	sortWidgets: function() {
		// Order the sort by the order the widgets are in the list
		var usedWidgets = document.getElementById('usedWidgets-'+this.name);

		if(usedWidgets) {
			widgets = usedWidgets.childNodes;

			for(i = 0; i < widgets.length; i++) {
				var div = widgets[i];

				if(div.nodeName != '#comment') {
					var fields = div.getElementsByTagName('input');

					for(j = 0; field = fields.item(j); j++) {
						if(field.name == div.id + '[Sort]') {
							field.value = i;
						}
					}
				}

			}
		}
	},

	deleteWidget: function(widgetToRemove) {
		// Remove a widget from the used widgets column
		document.getElementById('usedWidgets-'+this.name).removeChild(widgetToRemove);
		// TODO ... re-create NoWidgets div?
	}
}

/**
 * Class: UsedWidget
 */
UsedWidget = Class.create();
UsedWidget.prototype = {
	initialize: function() {
		// Call deleteWidget when delete button is pushed
		this.deleteButton = this.findDescendant('span', 'widgetDelete');
		if(this.deleteButton)
			this.deleteButton.onclick = this.deleteWidget.bind(this);
	},

	// Taken from FieldEditor
	findDescendant: function(tag, clsName, element) {
		if(!element)
			element = this;

		var descendants = element.getElementsByTagName(tag);

		for(var i = 0; i < descendants.length; i++) {
			var el = descendants[i];

			if(tag.toUpperCase() == el.tagName && el.className.indexOf( clsName ) != -1)
				return el;
		}

		return null;
	},

	deleteWidget: function() {
		this.parentNode.parentNode.parentNode.deleteWidget(this);
	}
}

/**
 * Class: AvailableWidgetHeader
 */
AvailableWidgetHeader = Class.create();
AvailableWidgetHeader.prototype = {
	onclick: function(event) {
		parts = this.parentNode.id.split('-');
		var widgetArea = parts.pop();
		var className = parts.pop();
		document.getElementById('WidgetAreaEditor-'+widgetArea).addWidget(className, widgetArea);
	}
}
AvailableWidgetHeader.applyTo('div.availableWidgets .Widget h3');

/**
 * Class: WidgetTreeDropdownField
 */
WidgetTreeDropdownField = Class.extend('TreeDropdownField');
WidgetTreeDropdownField.prototype = {
	getName: function() {
		return 'Widget_TDF_Endpoint';
	}
}
WidgetTreeDropdownField.applyTo('div.usedWidgets .TreeDropdownField');
WidgetAreaEditorClass.applyTo('.WidgetAreaEditor');
=======
(function($) {
	$.entwine('ss', function($) {
		$('.WidgetAreaEditor').entwine({
			onmatch: function() {
				var parentName=$(this).attr('name');
				this.rewriteWidgetAreaAttributes();

				var availableWidgets=$('#availableWidgets-'+$(this).attr('name')).children().each(function() {
					// Don't run on comments, whitespace, etc
					if($(this)[0].nodeType==1) {
						// Gotta change their ID's because otherwise we get clashes between two tabs
						$(this)[0].id=$(this)[0].id+'-'+parentName;
					}
				});

				var parentRef=$(this);

				// Used widgets are sortable
				$(this).find('.usedWidgets').sortable({
					opacity: 0.6,
					handle: '.handle',
					update: function(e, ui) {parentRef.updateWidgets(e, ui)},
					placeholder: 'ui-state-highlight',
					forcePlaceholderSize: true
				});

				// Figure out maxid, this is used when creating new widgets
				$(this).data('maxid', 0);

				var usedWidgets = $(this).find('.usedWidgets .Widget');
				usedWidgets.each(function() {
					var widget = $(this)[0];
					if(widget.id) {
						widgetid = widget.id.match(/Widget\[(.+?)\]\[([0-9]+)\]/i);
						if(widgetid && parseInt(widgetid[2]) > parseInt(parentRef.data('maxid'))) {
							parentRef.data('maxid', parseInt(widgetid[2]));
						}
					}
				});

				// Ensure correct sort values are written when page is saved
				// TODO Adjust to new event listeners
				$('.cms-container').bind('submitform', this.beforeSave);
			},

			rewriteWidgetAreaAttributes: function() {
				var name = $(this).attr('name');

				var monkeyWith = function(widgets, name) {
					if (!widgets) {
						return;
					}

					widgets.each(function() {
						widget=$(this)[0];
						if (!widget.rewritten && (widget.id || widget.name)) {
							if (widget.id && widget.id.indexOf('Widget[') === 0) {
								var newValue = widget.id.replace(/Widget\[/, 'Widget['+name+'][');
								//console.log('Renaming '+widget.tagName+' ID '+widget.id+' to '+newValue);
								widget.id = newValue;
							}
							if (widget.name && widget.name.indexOf('Widget[') === 0) {
								var newValue = widget.name.replace(/Widget\[/, 'Widget['+name+'][');
								//console.log('Renaming '+widget.tagName+' Name '+widget.name+' to '+newValue);
								widget.name=newValue;
							}
							widget.rewritten='yes';
						}else {
							//console.log('Skipping '+(widget.id ? widget.id : (widget.name ? widget.name : 'unknown '+widget.tagName)));
						}
					});
				}

				monkeyWith($('#WidgetAreaEditor-'+name+' .Widget'), name);
				monkeyWith($('#WidgetAreaEditor-'+name+' .Widget *'), name);
			},

			beforeSave: function() {
				// Ensure correct sort values are written when page is saved
				var usedWidgets = $('#usedWidgets-'+$(this).attr('name'));
				if(usedWidgets) {
					this.sortWidgets();

					var children=usedWidgets.children();

					children.each(function() {
						if($(this).beforeSave) {
							$(this).beforeSave();
						}
					});
				}
			},

			addWidget: function(className, holder) {
				if($('#WidgetAreaEditor-'+holder).attr('maxwidgets')) {
					var maxCount = $('#WidgetAreaEditor-'+holder).attr('maxwidgets');
					var count = $('#usedWidgets-'+holder+' .Widget').length;
					if (count+1 > maxCount) {
						alert(ss.i18n._t('WidgetAreaEditor.TOOMANY'));
						return;
					}
				}

				var parentRef=$(this);
				$.ajax({
					'url': 'Widget_Controller/EditableSegment/' + className,
					'success' : function(response) {parentRef.insertWidgetEditor(response)}
				});
			},

			updateWidgets: function(e, ui) {
				// Gotta get the name of the current dohickey based off the ID
				var name = $(this).attr('id').split('-').pop();

				var i=0;
				var usedWidgets = $('#usedWidgets-'+name).children().each(function() {
					var widget = $(this)[0];
					if(widget.id) {
						$(this).find('input[name='+widget.id.replace(/\]/g,'\\]').replace(/\[/g,'\\[')+'\\[Sort\\]]').val(i);
						i++;
					}
				});
			},

			insertWidgetEditor: function(response) {
				var usedWidgets = $('#usedWidgets-'+$(this).attr('name')).children();

				// Give the widget a unique id
				var newID=parseInt($(this).data('maxid'))+1;
				$(this).data('maxid', newID);

				var widgetContent = response.replace(/Widget\[0\]/gi, "Widget[new-" + (newID) + "]");
				$('#usedWidgets-'+$(this).attr('name')).prepend(widgetContent);

				this.rewriteWidgetAreaAttributes();
			},

			sortWidgets: function() {
				// Order the sort by the order the widgets are in the list
				$('#usedWidgets-'+$(this).attr('name')).children().each(function() {
						var div = $(this)[0];

						if(div.nodeName != '#comment') {
							var fields = div.getElementsByTagName('input');
							for(j = 0; field = fields.item(j); j++) {
								if(field.name == div.id + '[Sort]') {
									field.value = i;
								}
							}
						}
					});
			},

			deleteWidget: function(widgetToRemove) {
				// Remove a widget from the used widgets column
				widgetToRemove.remove();
			}
		});

		$('div.availableWidgets .Widget h3').entwine({
			onclick: function(event) {
				parts = $(this).parent().attr('id').split('-');
				var widgetArea = parts.pop();
				var className = parts.pop();
				$('#WidgetAreaEditor-'+widgetArea).addWidget(className, widgetArea);
			}
		});

		/**
		 * Disable chosen
		 */
		$('div.usedWidgets .field.dropdown select, div.usedWidgets .field select[multiple]').entwine({
			onmatch: function() {
				$(this).addClass('no-chzn');

				this._super();
			}
		});

		$('div.usedWidgets div.Widget').entwine({
			onmatch: function() {
				// Call deleteWidget when delete button is pushed
				$(this).find('span.widgetDelete').click(function() {
																$(this).closest('.WidgetAreaEditor').deleteWidget($(this).parent().parent());
															});
			}
		});
	})
})(jQuery);<commit_msg>MINOR resolve merge conflict with pull request issue #4 from dancras<commit_after>(function($) {
	$.entwine('ss', function($) {
		$('.WidgetAreaEditor').entwine({
			onmatch: function() {
				var parentName=$(this).attr('name');
				this.rewriteWidgetAreaAttributes();

				var availableWidgets=$('#availableWidgets-'+$(this).attr('name')).children().each(function() {
					// Don't run on comments, whitespace, etc
					if($(this)[0].nodeType==1) {
						// Gotta change their ID's because otherwise we get clashes between two tabs
						$(this)[0].id=$(this)[0].id+'-'+parentName;
					}
				});

				var parentRef=$(this);

				// Used widgets are sortable
				$(this).find('.usedWidgets').sortable({
					opacity: 0.6,
					handle: '.handle',
					update: function(e, ui) {parentRef.updateWidgets(e, ui)},
					placeholder: 'ui-state-highlight',
					forcePlaceholderSize: true
				});

				// Figure out maxid, this is used when creating new widgets
				$(this).data('maxid', 0);

				var usedWidgets = $(this).find('.usedWidgets .Widget');
				usedWidgets.each(function() {
					var widget = $(this)[0];
					if(widget.id) {
						widgetid = widget.id.match(/Widget\[(.+?)\]\[([0-9]+)\]/i);
						if(widgetid && parseInt(widgetid[2]) > parseInt(parentRef.data('maxid'))) {
							parentRef.data('maxid', parseInt(widgetid[2]));
						}
					}
				});

				// Ensure correct sort values are written when page is saved
				// TODO Adjust to new event listeners
				$('.cms-container').bind('submitform', this.beforeSave);
			},

			rewriteWidgetAreaAttributes: function() {
				var name = $(this).attr('name');

				var monkeyWith = function(widgets, name) {
					if (!widgets) {
						return;
					}

					widgets.each(function() {
						widget=$(this)[0];
						if (!widget.rewritten && (widget.id || widget.name)) {
							if (widget.id && widget.id.indexOf('Widget[') === 0) {
								var newValue = widget.id.replace(/Widget\[/, 'Widget['+name+'][');
								//console.log('Renaming '+widget.tagName+' ID '+widget.id+' to '+newValue);
								widget.id = newValue;
							}
							if (widget.name && widget.name.indexOf('Widget[') === 0) {
								var newValue = widget.name.replace(/Widget\[/, 'Widget['+name+'][');
								//console.log('Renaming '+widget.tagName+' Name '+widget.name+' to '+newValue);
								widget.name=newValue;
							}
							widget.rewritten='yes';
						}else {
							//console.log('Skipping '+(widget.id ? widget.id : (widget.name ? widget.name : 'unknown '+widget.tagName)));
						}
					});
				}

				monkeyWith($('#WidgetAreaEditor-'+name+' .Widget'), name);
				monkeyWith($('#WidgetAreaEditor-'+name+' .Widget *'), name);
			},

			beforeSave: function() {
				// Ensure correct sort values are written when page is saved
				var usedWidgets = $('#usedWidgets-'+$(this).attr('name'));
				if(usedWidgets) {
					this.sortWidgets();

					var children=usedWidgets.children();

					children.each(function() {
						if($(this).beforeSave) {
							$(this).beforeSave();
						}
					});
				}
			},

			addWidget: function(className, holder) {
				if($('#WidgetAreaEditor-'+holder).attr('maxwidgets')) {
					var maxCount = $('#WidgetAreaEditor-'+holder).attr('maxwidgets');
					var count = $('#usedWidgets-'+holder+' .Widget').length;
					if (count+1 > maxCount) {
						alert(ss.i18n._t('WidgetAreaEditor.TOOMANY'));
						return;
					}
				}

				var parentRef=$(this);
				$.ajax({
					'url': 'Widget_Controller/EditableSegment/' + className,
					'success' : function(response) {parentRef.insertWidgetEditor(response)}
				});
			},

			updateWidgets: function(e, ui) {
				// Gotta get the name of the current dohickey based off the ID
				var name = $(this).attr('id').split('-').pop();

				var i=0;
				var usedWidgets = $('#usedWidgets-'+name).children().each(function() {
					var widget = $(this)[0];
					if(widget.id) {
						$(this).find('input[name='+widget.id.replace(/\]/g,'\\]').replace(/\[/g,'\\[')+'\\[Sort\\]]').val(i);
						i++;
					}
				});
			},

			insertWidgetEditor: function(response) {
				var usedWidgets = $('#usedWidgets-'+$(this).attr('name')).children();

				// Give the widget a unique id
				var newID=parseInt($(this).data('maxid'))+1;
				$(this).data('maxid', newID);

				var widgetContent = response.replace(/Widget\[0\]/gi, "Widget[new-" + (newID) + "]");
				$('#usedWidgets-'+$(this).attr('name')).prepend(widgetContent);

				this.rewriteWidgetAreaAttributes();
			},

			sortWidgets: function() {
				// Order the sort by the order the widgets are in the list
				$('#usedWidgets-'+$(this).attr('name')).children().each(function() {
						var div = $(this)[0];

						if(div.nodeName != '#comment') {
							var fields = div.getElementsByTagName('input');
							for(j = 0; field = fields.item(j); j++) {
								if(field.name == div.id + '[Sort]') {
									field.value = i;
								}
							}
						}
					});
			},

			deleteWidget: function(widgetToRemove) {
				// Remove a widget from the used widgets column
				widgetToRemove.remove();
			}
		});

		$('div.availableWidgets .Widget h3').entwine({
			onclick: function(event) {
				parts = $(this).parent().attr('id').split('-');
				var widgetArea = parts.pop();
				var className = parts.pop();
				$('#WidgetAreaEditor-'+widgetArea).addWidget(className, widgetArea);
			}
		});

		/**
		 * Disable chosen
		 */
		$('div.usedWidgets .field.dropdown select, div.usedWidgets .field select[multiple]').entwine({
			onmatch: function() {
				$(this).addClass('no-chzn');

				this._super();
			}
		});

		$('div.usedWidgets div.Widget').entwine({
			onmatch: function() {
				// Call deleteWidget when delete button is pushed
				$(this).find('span.widgetDelete').click(function() {
					$(this).closest('.WidgetAreaEditor').deleteWidget($(this).parent().parent());
				});
			}
		});
	})
})(jQuery);<|endoftext|>


<commit_before>(function (ns){

  ns.accentMap = {
    'á': 'a', 'à': 'a', 'â': 'a',
    'é': 'e', 'è': 'e', 'ê': 'e', 'ë': 'e',
    'ç': 'c',
    'î': 'i', 'ï': 'i',
    'ô': 'o', 'ö': 'o',
    'ù': 'u', 'û': 'u', 'ü': 'u'
  };
  ns.clean_accents = function(term){
    var ret = '';
    for (var i = 0; i < term.length; i++)
      ret += ns.accentMap[term.charAt(i)] || term.charAt(i);
    return ret;
  };

  ns.datize = function(date_str){
    date_str = date_str.trim()
      .replace(/^(\d+)\/(\d+)\/(\d+)$/, '$3-$2-$1');
    return new Date(date_str);
  };

  ns.deputes = {};
  ns.downloadDeputes = function(){
    $.getJSON('http://www.nosdeputes.fr/deputes/enmandat/json', function(data){
      data.deputes.forEach(function(dep){
        var d = dep.depute;
        d.display = d.prenom + ' ' + d.nom_de_famille + ' (' + d.groupe_sigle + ')';
        if (ns.deputes[d.id] == undefined)
          ns.deputes[d.id] = d;
        else for (var key in d)
          ns.deputes[d.id][key] = d[key];
      });
      ns.deputesAr = Object.keys(ns.deputes).map(function(d){
        return ns.deputes[d];
      });
      ns.dep = ns.deputesAr[parseInt(Math.random() * ns.deputesAr.length)];
      ns.buildSelectMenu();
    });
  };

  ns.buildSelectMenu = function(){
    $('#deputes').autocomplete({
      source: function(request, response){
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(ns.clean_accents(request.term)), 'i');
        response($.grep(
          ns.deputesAr.sort(function(a, b){
            return (a.nom_de_famille > b.nom_de_famille ? 1 : -1)
          }).map(function(d){
            return {
              label: d.display,
              value: d.display,
              dep: d
            };
          }),
          function(d){
            return matcher.test(ns.clean_accents(d.label));
          }
        ));
      },
      select: function(event, ui){
        event.preventDefault();
        ns.dep = ui.item.dep;
        ns.displayMP();
      }
    });

    $('#loader').hide();
    $('#content').show();
    ns.displayMP();
  };

  ns.annees = function(date){
    var now = new Date();
    var age = now.getFullYear() - (date instanceof Date ? date : new Date(date)).getFullYear();
    return age + ' an' + (age > 1 ? 's' : '');
  };

  ns.displayMP = function(){
    var sexe = 'Député' + (ns.dep.sexe === 'F' ? 'e' : ''),
      twitter = (ns.dep.twitter ? '@' + ns.dep.twitter : ''),
      plural = (ns.dep.nb_mandats > 2 ? 's' : ''),
      extra_mandats = '
A' + (ns.dep.nb_mandats > 1 ? '' : 'ucun a') + 'utre' + plural + ' mandat' + plural + (ns.dep.nb_mandats > 1 ? ' :

' : '
');

    ns.dep.autres_mandats.forEach(function(m){
      m = m["mandat"].split(' / ');
      var fonction = (/^(pr[eé]sid|maire)/i.test(m[2]) ? '' + m[2] + '' :  m[2]);
      extra_mandats += '
' + m[0] + ' — ' + m[1] + ' (' + fonction + ')
';
    });
    if (ns.dep.nb_mandats > 1) extra_mandats += '
'

    if (!ns.dep.debut_mandat) {
      ns.dep.debut_mandat = ns.datize(ns.dep.mandat_debut);
      ns.dep.anciens_mandats.filter(function(a){
        return a['mandat'].indexOf(' /  / ') === -1;
      }).map(function(a){
        return a['mandat']
          .split(' / ')
          .splice(0, 2)
          .map(function(da){
            return ns.datize(da.trim());
          });
      }).sort(function(a, b){
        return (a[0] < b[0] ? 1 : -1);
      }).forEach(function(a){
        if ((ns.dep.debut_mandat - a[1])/86400000 < 65)
          ns.dep.debut_mandat = a[0];
      });
    }

    $('#name').text(ns.dep.nom);
    $('#descr').text(sexe + ' de TODO ' + ns.dep.nom_circo);
    $('#details').html(ns.annees(ns.dep.date_naissance) + ' - ' + sexe.toLowerCase() + ' depuis ' + ns.annees(ns.dep.debut_mandat) + '
' + ns.dep.profession.replace('declare', 'déclaré'));
    $('#extra').html(twitter);
    $('#logo img').attr('src', 'logos/AN/' + ns.dep.groupe_sigle.toUpperCase() + '.png');
    $('#widget').attr('src', 'http://www.nosdeputes.fr/widget14/' + ns.dep.slug + '?iframe=true&width=950');
    $('#autres').html(extra_mandats);
  };

  ns.setResponsive = function(){
    $('#right').width($(window).width() - $('#incrust').width() - $('#right').css('padding-left').replace('px', '') - 1);
    $('#autres').height($(window).height() - $('#top').height() - 1);
  };

  $(document).ready(function(){
    ns.setResponsive();
    ns.downloadDeputes();
  });
  $(window).resize(ns.setResponsive);

})(window.directparl = window.directparl || {});
<commit_msg>handle particules departements<commit_after>(function (ns){

  ns.accentMap = {
    'á': 'a', 'à': 'a', 'â': 'a',
    'é': 'e', 'è': 'e', 'ê': 'e', 'ë': 'e',
    'ç': 'c',
    'î': 'i', 'ï': 'i',
    'ô': 'o', 'ö': 'o',
    'ù': 'u', 'û': 'u', 'ü': 'u'
  };
  ns.clean_accents = function(term){
    var ret = '';
    for (var i = 0; i < term.length; i++)
      ret += ns.accentMap[term.charAt(i)] || term.charAt(i);
    return ret;
  };

  ns.departements = {
     "Ain": "de l'",
     "Aisne": "de l'",
     "Allier": "de l'",
     "Alpes-de-Haute-Provence": "des ",
     "Alpes-Maritimes": "des ",
     "Ardèche": "de l'",
     "Ardennes": "des ",
     "Ariège": "d'",
     "Aube": "de l'",
     "Aude": "de l'",
     "Aveyron": "de l'",
     "Bas-Rhin": "du ",
     "Bouches-du-Rhône": "des ",
     "Calvados": "du ",
     "Cantal": "du ",
     "Charente": "de ",
     "Charente-Maritime": "de ",
     "Cher": "du ",
     "Corrèze": "de ",
     "Corse-du-Sud": "de ",
     "Côte-d'Or": "de ",
     "Côtes-d'Armor": "des ",
     "Creuse": "de la ",
     "Deux-Sèvres": "des ",
     "Dordogne": "de la ",
     "Doubs": "du ",
     "Drôme": "de la ",
     "Essonne": "de l'",
     "Eure": "de l'",
     "Eure-et-Loir": "d'",
     "Finistère": "du ",
     "Français établis hors de France": "des ",
     "Gard": "du ",
     "Gers": "du ",
     "Gironde": "de la ",
     "Guadeloupe": "de ",
     "Guyane": "de ",
     "Haut-Rhin": "du ",
     "Haute-Corse": "de ",
     "Haute-Garonne": "de la ",
     "Haute-Loire": "de la ",
     "Haute-Marne": "de la ",
     "Haute-Saône": "de la ",
     "Haute-Savoie": "de ",
     "Haute-Vienne": "de la ",
     "Hautes-Alpes": "des ",
     "Hautes-Pyrénées": "des ",
     "Hauts-de-Seine": "des ",
     "Hérault": "de l'",
     "Ille-et-Vilaine": "d'",
     "Indre": "de l'",
     "Indre-et-Loire": "de l'",
     "Isère": "de l'",
     "Jura": "du ",
     "Landes": "des ",
     "Loir-et-Cher": "du ",
     "Loire": "de la ",
     "Loire-Atlantique": "de ",
     "Loiret": "du ",
     "Lot": "du ",
     "Lot-et-Garonne": "du ",
     "Lozère": "de la ",
     "Maine-et-Loire": "du ",
     "Manche": "de la ",
     "Marne": "de la ",
     "Martinique": "de ",
     "Mayenne": "de la ",
     "Mayotte": "de ",
     "Meurthe-et-Moselle": "de ",
     "Meuse": "de la ",
     "Morbihan": "du ",
     "Moselle": "de la ",
     "Nièvre": "de la ",
     "Nord": "du ",
     "Nouvelle-Calédonie": "de la ",
     "Oise": "de l'",
     "Orne": "de l'",
     "Paris": "de ",
     "Pas-de-Calais": "du ",
     "Polynésie Française": "de la ",
     "Puy-de-Dôme": "du ",
     "Pyrénées-Atlantiques": "des ",
     "Pyrénées-Orientales": "des ",
     "Réunion": "de la ",
     "Rhône": "du ",
     "Saint-Pierre-et-Miquelon": "de ",
     "Saint-Barthélemy et Saint-Martin": "de ",
     "Saône-et-Loire": "de ",
     "Sarthe": "de la ",
     "Savoie": "de ",
     "Seine-et-Marne": "de ",
     "Seine-Maritime": "de ",
     "Seine-Saint-Denis": "de ",
     "Somme": "de la ",
     "Tarn": "du ",
     "Tarn-et-Garonne": "du ",
     "Territoire-de-Belfort": "du ",
     "Territoire de Belfort": "du ",
     "Val-d'Oise": "du ",
     "Val-de-Marne": "du ",
     "Var": "du ",
     "Vaucluse": "du ",
     "Vendée": "de ",
     "Vienne": "de la ",
     "Vosges": "des ",
     "Wallis-et-Futuna": "de ",
     "Yonne": "de l'",
     "Yvelines": "des"
  };

  ns.datize = function(date_str){
    date_str = date_str.trim()
      .replace(/^(\d+)\/(\d+)\/(\d+)$/, '$3-$2-$1');
    return new Date(date_str);
  };

  ns.deputes = {};
  ns.downloadDeputes = function(){
    $.getJSON('http://www.nosdeputes.fr/deputes/enmandat/json', function(data){
      data.deputes.forEach(function(dep){
        var d = dep.depute;
        d.display = d.prenom + ' ' + d.nom_de_famille + ' (' + d.groupe_sigle + ')';
        if (ns.deputes[d.id] == undefined)
          ns.deputes[d.id] = d;
        else for (var key in d)
          ns.deputes[d.id][key] = d[key];
      });
      ns.deputesAr = Object.keys(ns.deputes).map(function(d){
        return ns.deputes[d];
      });
      ns.dep = ns.deputesAr[parseInt(Math.random() * ns.deputesAr.length)];
      ns.buildSelectMenu();
    });
  };

  ns.buildSelectMenu = function(){
    $('#deputes').autocomplete({
      source: function(request, response){
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(ns.clean_accents(request.term)), 'i');
        response($.grep(
          ns.deputesAr.sort(function(a, b){
            return (a.nom_de_famille > b.nom_de_famille ? 1 : -1)
          }).map(function(d){
            return {
              label: d.display,
              value: d.display,
              dep: d
            };
          }),
          function(d){
            return matcher.test(ns.clean_accents(d.label));
          }
        ));
      },
      select: function(event, ui){
        event.preventDefault();
        ns.dep = ui.item.dep;
        ns.displayMP();
      }
    });

    $('#loader').hide();
    $('#content').show();
    ns.displayMP();
  };

  ns.annees = function(date){
    var now = new Date();
    var age = now.getFullYear() - (date instanceof Date ? date : new Date(date)).getFullYear();
    return age + ' an' + (age > 1 ? 's' : '');
  };

  ns.displayMP = function(){
    var sexe = 'Député' + (ns.dep.sexe === 'F' ? 'e' : ''),
      twitter = (ns.dep.twitter ? '@' + ns.dep.twitter : ''),
      plural = (ns.dep.nb_mandats > 2 ? 's' : ''),
      extra_mandats = '
A' + (ns.dep.nb_mandats > 1 ? '' : 'ucun a') + 'utre' + plural + ' mandat' + plural + (ns.dep.nb_mandats > 1 ? ' :

' : '
');

    ns.dep.autres_mandats.forEach(function(m){
      m = m["mandat"].split(' / ');
      var fonction = (/^(pr[eé]sid|maire)/i.test(m[2]) ? '' + m[2] + '' :  m[2]);
      extra_mandats += '
' + m[0] + ' — ' + m[1] + ' (' + fonction + ')
';
    });
    if (ns.dep.nb_mandats > 1) extra_mandats += '
'

    if (!ns.dep.debut_mandat) {
      ns.dep.debut_mandat = ns.datize(ns.dep.mandat_debut);
      ns.dep.anciens_mandats.filter(function(a){
        return a['mandat'].indexOf(' /  / ') === -1;
      }).map(function(a){
        return a['mandat']
          .split(' / ')
          .splice(0, 2)
          .map(function(da){
            return ns.datize(da.trim());
          });
      }).sort(function(a, b){
        return (a[0] < b[0] ? 1 : -1);
      }).forEach(function(a){
        if ((ns.dep.debut_mandat - a[1])/86400000 < 65)
          ns.dep.debut_mandat = a[0];
      });
    }

    $('#name').text(ns.dep.nom);
    $('#descr').text(sexe + ' ' + ns.departements[ns.dep.nom_circo] + ns.dep.nom_circo);
    $('#details').html(ns.annees(ns.dep.date_naissance) + ' - ' + sexe.toLowerCase() + ' depuis ' + ns.annees(ns.dep.debut_mandat) + '
' + ns.dep.profession.replace('declare', 'déclaré'));
    $('#extra').html(twitter);
    $('#logo img').attr('src', 'logos/AN/' + ns.dep.groupe_sigle.toUpperCase() + '.png');
    $('#widget').attr('src', 'http://www.nosdeputes.fr/widget14/' + ns.dep.slug + '?iframe=true&width=950');
    $('#autres').html(extra_mandats);
  };

  ns.setResponsive = function(){
    $('#right').width($(window).width() - $('#incrust').width() - $('#right').css('padding-left').replace('px', '') - 1);
    $('#autres').height($(window).height() - $('#top').height() - 1);
  };

  $(document).ready(function(){
    ns.setResponsive();
    ns.downloadDeputes();
  });
  $(window).resize(ns.setResponsive);

})(window.directparl = window.directparl || {});
<|endoftext|>


<commit_before>angular.module('codepuppy').controller('NavigationCtrl',
    ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {
      $scope.navigationSelectors = [];

      /* Compute the selected attribute for 'navSelector' based on the routing
       * parameter 'targetSuffix' */
      function computeSelected(navSelector, targetSuffix) {
        var endsWith = function(string, query) {
          return (string.length >= query.length &&
            string.substr(string.length - query.length) == query);
        };

        var elements = navSelector.elements;
        for (i = 0; i < elements.length; ++i) {
          if (endsWith(elements[i].url, targetSuffix)) {
            navSelector.selected = elements[i].name;
          }
        }
      }

      var getCourses = function() {
        $http({method: 'GET', url: '/course_terms/active.json'})
        .success(function(data, status, headers, config) {
          var courses = [];
          for (var i = 0; i < data.length; ++i) {
            courses.push({
              'name': data[i].course_name + " ("
                    + data[i].term_name + " "
                    + data[i].period + ")",
              'url': "/#/" + data[i].id
            });
          }
          var courseNav = {'title': 'Courses', 'elements': courses,
            'selected': null};
          if ($routeParams.courseID !== undefined) {
            computeSelected(courseNav, $routeParams.courseID);
          }
          $scope.navigationSelectors[0] = courseNav;
        });
      }

      /* COURSE HANDLING */
      getCourses();

      // If they haven't selected a course, this is all we need to render
      if ($routeParams.courseID === undefined)
        return;

      /* ASSIGNMENT HANDLING */
      var getAssignments = function(courseID) {
        $http({method: 'GET', url: '/course_terms/' + courseID + '/assignments.json'})
        .success(function(data, status, headers, config) {
          var assignments = [];
          for (var i = 0; i < data.length; ++i) {
            assignments.push({
              'name': "Assignment " + data[i].number,
              'url': "/#/" + courseID + "/" + data[i].id
            });
          }
          var assignmentNav = {'title': 'Assignments', 'elements': assignments,
            'selected': null};
          if ($routeParams.assigmentID !== undefined)
            computeSelected(assignmentNav, $routeParams.assignmentID);
          $scope.navigationSelectors[1] = assignmentNav;
        });
      }

      getAssignments($routeParams.courseID);

      // If they haven't selected an assignment, this is all we need to render
      if ($routeParams.assignmentID === undefined)
        return;

      /* SUBMISSION HANDLING */
      var getSubmissions = function(courseID, assignmentID) {
        $http({method: 'GET', url: '/assignments/' + assignmentID + '/submissions.json'})
        .success(function(data, status, headers, config) {
          var submissions = [];
          for (var i = 0; i < data.length; ++i) {
            submissions.push({
              'name': "Submission " + data[i].id,
              'url': "/#/" + courseID + "/" + assignmentID + "/" + data[i].id
            });
          }
          var submissionNav = {'title': 'Submissions', 'elements': submissions,
            'selected': null};
          if ($routeParams.submissionID !== undefined)
            computeSelected(submissionNav, $routeParams.submissionID);
          $scope.navigationSelectors[2] = submissionNav;
        });
      }

      getSubmissions($routeParams.courseID, $routeParams.assignmentID);
    }]);
<commit_msg>Whitespace change to navigation controller<commit_after>angular.module('codepuppy').controller('NavigationCtrl',
['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {

  $scope.navigationSelectors = [];

  /* Compute the selected attribute for 'navSelector' based on the routing
   * parameter 'targetSuffix' */
  function computeSelected(navSelector, targetSuffix) {
    var endsWith = function(string, query) {
      return (string.length >= query.length &&
        string.substr(string.length - query.length) == query);
    };

    var elements = navSelector.elements;
    for (i = 0; i < elements.length; ++i) {
      if (endsWith(elements[i].url, targetSuffix)) {
        navSelector.selected = elements[i].name;
      }
    }
  }

  var getCourses = function() {
    $http({method: 'GET', url: '/course_terms/active.json'})
    .success(function(data, status, headers, config) {
      var courses = [];
      for (var i = 0; i < data.length; ++i) {
        courses.push({
          'name': data[i].course_name + " ("
                + data[i].term_name + " "
                + data[i].period + ")",
          'url': "/#/" + data[i].id
        });
      }
      var courseNav = {'title': 'Courses', 'elements': courses,
        'selected': null};
      if ($routeParams.courseID !== undefined) {
        computeSelected(courseNav, $routeParams.courseID);
      }
      $scope.navigationSelectors[0] = courseNav;
    });
  }

  /* COURSE HANDLING */
  getCourses();

  // If they haven't selected a course, this is all we need to render
  if ($routeParams.courseID === undefined)
    return;

  /* ASSIGNMENT HANDLING */
  var getAssignments = function(courseID) {
    $http({method: 'GET', url: '/course_terms/' + courseID + '/assignments.json'})
    .success(function(data, status, headers, config) {
      var assignments = [];
      for (var i = 0; i < data.length; ++i) {
        assignments.push({
          'name': "Assignment " + data[i].number,
          'url': "/#/" + courseID + "/" + data[i].id
        });
      }
      var assignmentNav = {'title': 'Assignments', 'elements': assignments,
        'selected': null};
      if ($routeParams.assigmentID !== undefined)
        computeSelected(assignmentNav, $routeParams.assignmentID);
      $scope.navigationSelectors[1] = assignmentNav;
    });
  }

  getAssignments($routeParams.courseID);

  // If they haven't selected an assignment, this is all we need to render
  if ($routeParams.assignmentID === undefined)
    return;

  /* SUBMISSION HANDLING */
  var getSubmissions = function(courseID, assignmentID) {
    $http({method: 'GET', url: '/assignments/' + assignmentID + '/submissions.json'})
    .success(function(data, status, headers, config) {
      var submissions = [];
      for (var i = 0; i < data.length; ++i) {
        submissions.push({
          'name': "Submission " + data[i].id,
          'url': "/#/" + courseID + "/" + assignmentID + "/" + data[i].id
        });
      }
      var submissionNav = {'title': 'Submissions', 'elements': submissions,
        'selected': null};
      if ($routeParams.submissionID !== undefined)
        computeSelected(submissionNav, $routeParams.submissionID);
      $scope.navigationSelectors[2] = submissionNav;
    });
  }

  getSubmissions($routeParams.courseID, $routeParams.assignmentID);
}]);
<|endoftext|>


<commit_before>
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = DomElement;
}

/**
 * Wrapper for operatons with dom elements
 * @param {object} element
 */
function DomElement(element) {
    var utils = new DomUtils();

    this.element = element instanceof DomElement ? element.element : element;

    DomElement.prototype.findOne = function(selector, includeSelf) {
        if (typeof includeSelf !== 'undefined' && includeSelf && this.element && this.element.matches(selector)) {
            return this;
        }

        var element = this.element ? this.element.querySelector(selector) : null;

        return new DomElement(element);
    };

    DomElement.prototype.findAll = function(selector, native) {
        var list = this.element ? this.element.querySelectorAll(selector) : null;

        return typeof native !== 'undefined' && native ? list : new DomList(list);
    }

    DomElement.prototype.html = function(setHtml) {
        if (typeof setHtml !== 'undefined') {
            if (this.element) this.element.innerHTML = setHtml;
            return this;
        }

        return this.element ? this.element.innerHTML : '';
    }

    DomElement.prototype.text = function(text) {
        if (typeof text === 'undefined') {
            return this.element ? this.element.textContent : '';
        }

        if (this.element) this.element.textContent = text;
        return this;
    }

    DomElement.prototype.on = function(events, selector, action) {
        if (this.element) {
            utils.listenToEvent(this.element, events, selector, action, false);
        }

        return this;
    }

    DomElement.prototype.one = function(events, selector, action) {
        if (this.element) {
            utils.listenToEvent(this.element, events, selector, action, {once: true, capture: false});
        }

        return this;
    }

    DomElement.prototype.off = function(eventName) {
        if (this.element) this.element.removeEventListener(eventName);

        return this;
    }

    DomElement.prototype.attr = function(name, value) {
        if (typeof value === 'undefined') {
            return this.element ? this.element.getAttribute(name) : '';
        }

        if (this.element) this.element.setAttribute(name, value);

        return this;
    }

    DomElement.prototype.removeAttr = function(name) {
        if (this.element) {
            this.element.removeAttribute(name);
        }

        return this;
    }

    DomElement.prototype.prop = function(name, value) {
        if (typeof value === 'undefined') {
            return this.element ? this.element[name] : null;
        }

        if (this.element) this.element[name] = value;

        return this;
    }

    DomElement.prototype.closest = function(selector) {
        var closest = this.element ? this.element.closest(selector) : null;

        return new DomElement(closest);
    }

    DomElement.prototype.isParentOf = function(element) {
        if (!this.element || !element.element) return false;
        if (this.element === document) return true;

        var parent = element.element;

        while (parent = parent.parentElement) {
            if (parent === this.element) return true;
        }

        return false;
    }

    DomElement.prototype.trigger = function(eventName, options) {
        if (!this.element) return null;

        if (eventName instanceof Event) {
            this.element.dispatchEvent(eventName);
            return eventName;
        }

        var validName = eventName.split('.')[0];
        var defaultOptions = {
            bubbles: true,
            cancelable: true
        };

        if (typeof options === 'undefined') options = {};
        options = cloner.shallow.merge({}, defaultOptions, options);

        if (typeof options.detail === 'undefined') {
            options.detail = {};
        }
        options.detail.fullName = eventName;

        var event = new CustomEvent(validName, options);
        this.element.dispatchEvent(event);

        return event;
    }

    DomElement.prototype.isValid = function() {
        return this.element ? this.element.validity.valid : true;
    }

    DomElement.prototype.setCustomValidity = function(error) {
        if (this.element) {
            this.element.setCustomValidity(error);
        }

        return this;
    }

    DomElement.prototype.is = function(selector) {
        if (!this.element) return false;
        if (typeof selector === 'string') return this.element.matches(selector);
        return this.element === selector.element;
    }

    DomElement.prototype.nextAll = function(selector) {
        if (!this.element) return new DomList(null);

        var result = [];
        var next = this.element;

        while (next = next.nextSibling) {
            if (next.nodeType === 1 && next.matches(selector)) {
                result.push(next);
            }
        }

        return new DomList(result);
    }

    DomElement.prototype.prevAll = function(selector) {
        if (!this.element) return new DomList(null);

        var result = [];
        var prev = this.element;

        while (prev = prev.previousSibling) {
            if (prev.nodeType === 1 && prev.matches(selector)) {
                result.push(prev);
            }
        }

        return new DomList(result);
    }

    DomElement.prototype.hasClass = function(className) {
        return this.element ? this.element.classList.contains(className) : false;
    }

    DomElement.prototype.addClass = function(className) {
        if (this.element) {
            this.element.classList.add(...arguments);
        }

        return this;
    }

    DomElement.prototype.removeClass = function(className) {
        if (this.element) {
            this.element.classList.remove(...arguments);
        }

        return this;
    }

    DomElement.prototype.toggleClass = function(className, state) {
        if (typeof state !== 'undefined') {
            state ? this.addClass(className) : this.removeClass(className);
        } else {
            this.hasClass(className) ?
                this.removeClass(className) :
                this.addClass(className);
        }

        return this;
    }

    DomElement.prototype.parent = function() {
        var parent = this.element ? this.element.parentElement : null;

        return new DomElement(parent);
    }

    DomElement.prototype.remove = function() {
        if (this.element && this.element.parentElement) {
            this.element.parentElement.removeChild(this.element);
        }

        return this;
    }

    DomElement.prototype.show = function() {
        if (!this.element) return this;

        var oldDisplay = this.attr('data-olddisplay');
        if (typeof oldDisplay !== 'undefined' && oldDisplay) {
            this.element.style.display = oldDisplay;
        }

        if (!this.isVisible()) {
            this.element.style.display = 'block';
        }
    }

    DomElement.prototype.hide = function() {
        if (!this.element) return this;

        var oldDisplay = this.element.style.display;

        this.attr('data-olddisplay', oldDisplay);
        this.element.style.display = 'none';

        return this;
    }

    //Getter only
    DomElement.prototype.css = function(name) {
        if (!this.element) return '';

        var styles = getComputedStyle(this.element);
        name = toCamelCase(name);

        return typeof styles[name] !== 'undefined' ? styles[name] : '';
    }

    DomElement.prototype.index = function() {
        if (!this.element || !this.element.parentElement) return -1;

        var parent = this.element.parentElement;
        var siblings = parent.children;

        for (var i = 0; i < siblings.length; i++) {
            if (siblings[i] === this.element) return i;
        }

        return -1;
    }

    DomElement.prototype.children = function() {
        if (!this.element) return new DomList(null);

        var items = [];
        var kids = this.element.children;

        for (var i = 0; i < kids.length; i++) {
            items.push(kids[i]);
        }

        return new DomList(items);
    }

    DomElement.prototype.outerHeight = function() {
        return this.element ? this.element.offsetHeight : 0;
    }

    DomElement.prototype.position = function() {
        if (!this.element) return {top: 0, left: 0};

        return {
            top: this.element.offsetTop,
            left: this.element.offsetLeft
        }
    }

    DomElement.prototype.offset = function() {
        if (!this.element) return {top: 0, left: 0};

        var rect = this.element.getBoundingClientRect();

        return {
            top: rect.top + window.pageYOffset,
            left: rect.left + window.pageXOffset
        };
    }

    DomElement.prototype.scrollTop = function(pos, duration) {
        if (this.element) {
            duration ?
                animateScrollTop(this.element, pos, duration) :
                this.element.scrollTop = pos;
        }

        return this;
    }

    DomElement.prototype.parentsUntil = function(tillSelector, filterSelector) {
        if (!this.element) return new DomList(null);

        var items = [];
        var parent = this.element;

        while (parent = parent.parentElement) {
            var matches =
                (typeof tillSelector === 'undefined' || !parent.matches(tillSelector)) &&
                (typeof filterSelector === 'undefined' || parent.matches(filterSelector));

            if (matches) items.push(parent);
        }

        return new DomList(items);
    }

    DomElement.prototype.width = function(width) {
        if (typeof width === 'undefined') {
            return this.element ? this.element.offsetWidth : 0;
        }

        if (this.element) {
            this.element.style.width = width;
        }

        return this;
    }

    DomElement.prototype.height = function(height) {
        if (typeof height === 'undefined') {
            return this.element ? this.element.offsetHeight : 0;
        }

        if (this.element) {
            this.element.style.height = height;
        }

        return this;
    }

    DomElement.prototype.isVisible = function() {
        if (!this.element) return false;

        return !!(
            this.element.offsetWidth ||
            this.element.offsetHeight ||
            this.element.getClientRects().length
        );
    }

    DomElement.prototype.val = function(value) {
        if (typeof value !== 'undefined') {
            if (this.element) this.element.value = value;

            return this;
        }

        return this.element ? this.element.value : '';
    }

    DomElement.prototype.focus = function(value) {
        if (this.element) {
            this.element.focus();
        }

        return this;
    }

    DomElement.prototype.append = function(element) {
        if (!this.element || !element.element) return this;

        this.element.appendChild(element.element);

        return this;
    }
}
<commit_msg>Dom element prev and next methods<commit_after>
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = DomElement;
}

/**
 * Wrapper for operatons with dom elements
 * @param {object} element
 */
function DomElement(element) {
    var utils = new DomUtils();

    this.element = element instanceof DomElement ? element.element : element;

    DomElement.prototype.findOne = function(selector, includeSelf) {
        if (typeof includeSelf !== 'undefined' && includeSelf && this.element && this.element.matches(selector)) {
            return this;
        }

        var element = this.element ? this.element.querySelector(selector) : null;

        return new DomElement(element);
    };

    DomElement.prototype.findAll = function(selector, native) {
        var list = this.element ? this.element.querySelectorAll(selector) : null;

        return typeof native !== 'undefined' && native ? list : new DomList(list);
    }

    DomElement.prototype.html = function(setHtml) {
        if (typeof setHtml !== 'undefined') {
            if (this.element) this.element.innerHTML = setHtml;
            return this;
        }

        return this.element ? this.element.innerHTML : '';
    }

    DomElement.prototype.text = function(text) {
        if (typeof text === 'undefined') {
            return this.element ? this.element.textContent : '';
        }

        if (this.element) this.element.textContent = text;
        return this;
    }

    DomElement.prototype.on = function(events, selector, action) {
        if (this.element) {
            utils.listenToEvent(this.element, events, selector, action, false);
        }

        return this;
    }

    DomElement.prototype.one = function(events, selector, action) {
        if (this.element) {
            utils.listenToEvent(this.element, events, selector, action, {once: true, capture: false});
        }

        return this;
    }

    DomElement.prototype.off = function(eventName) {
        if (this.element) this.element.removeEventListener(eventName);

        return this;
    }

    DomElement.prototype.attr = function(name, value) {
        if (typeof value === 'undefined') {
            return this.element ? this.element.getAttribute(name) : '';
        }

        if (this.element) this.element.setAttribute(name, value);

        return this;
    }

    DomElement.prototype.removeAttr = function(name) {
        if (this.element) {
            this.element.removeAttribute(name);
        }

        return this;
    }

    DomElement.prototype.prop = function(name, value) {
        if (typeof value === 'undefined') {
            return this.element ? this.element[name] : null;
        }

        if (this.element) this.element[name] = value;

        return this;
    }

    DomElement.prototype.closest = function(selector) {
        var closest = this.element ? this.element.closest(selector) : null;

        return new DomElement(closest);
    }

    DomElement.prototype.isParentOf = function(element) {
        if (!this.element || !element.element) return false;
        if (this.element === document) return true;

        var parent = element.element;

        while (parent = parent.parentElement) {
            if (parent === this.element) return true;
        }

        return false;
    }

    DomElement.prototype.trigger = function(eventName, options) {
        if (!this.element) return null;

        if (eventName instanceof Event) {
            this.element.dispatchEvent(eventName);
            return eventName;
        }

        var validName = eventName.split('.')[0];
        var defaultOptions = {
            bubbles: true,
            cancelable: true
        };

        if (typeof options === 'undefined') options = {};
        options = cloner.shallow.merge({}, defaultOptions, options);

        if (typeof options.detail === 'undefined') {
            options.detail = {};
        }
        options.detail.fullName = eventName;

        var event = new CustomEvent(validName, options);
        this.element.dispatchEvent(event);

        return event;
    }

    DomElement.prototype.isValid = function() {
        return this.element ? this.element.validity.valid : true;
    }

    DomElement.prototype.setCustomValidity = function(error) {
        if (this.element) {
            this.element.setCustomValidity(error);
        }

        return this;
    }

    DomElement.prototype.is = function(selector) {
        if (!this.element) return false;
        if (typeof selector === 'string') return this.element.matches(selector);
        return this.element === selector.element;
    }

    DomElement.prototype.next = function(selector) {
        if (!this.element) return null;

        var next = this.element;
        while ((next = next.nextSibling) && next.nodeType !== 1) {}

        var valid = next && (typeof selector === 'undefined' || !selector || next.matches(selector));

        return valid ? new DomElement(next) : null;
    }

    DomElement.prototype.nextAll = function(selector) {
        if (!this.element) return new DomList(null);

        var result = [];
        var next = this.element;

        while (next = next.nextSibling) {
            if (next.nodeType === 1 && next.matches(selector)) {
                result.push(next);
            }
        }

        return new DomList(result);
    }

    DomElement.prototype.prev = function(selector) {
        if (!this.element) return null;

        var prev = this.element;
        while ((prev = prev.previousSibling) && prev.nodeType !== 1) {}

        var valid = prev && (typeof selector === 'undefined' || !selector || prev.matches(selector));

        return valid ? new DomElement(prev) : null;
    }

    DomElement.prototype.prevAll = function(selector) {
        if (!this.element) return new DomList(null);

        var result = [];
        var prev = this.element;

        while (prev = prev.previousSibling) {
            if (prev.nodeType === 1 && prev.matches(selector)) {
                result.push(prev);
            }
        }

        return new DomList(result);
    }

    DomElement.prototype.hasClass = function(className) {
        return this.element ? this.element.classList.contains(className) : false;
    }

    DomElement.prototype.addClass = function(className) {
        if (this.element) {
            this.element.classList.add(...arguments);
        }

        return this;
    }

    DomElement.prototype.removeClass = function(className) {
        if (this.element) {
            this.element.classList.remove(...arguments);
        }

        return this;
    }

    DomElement.prototype.toggleClass = function(className, state) {
        if (typeof state !== 'undefined') {
            state ? this.addClass(className) : this.removeClass(className);
        } else {
            this.hasClass(className) ?
                this.removeClass(className) :
                this.addClass(className);
        }

        return this;
    }

    DomElement.prototype.parent = function() {
        var parent = this.element ? this.element.parentElement : null;

        return new DomElement(parent);
    }

    DomElement.prototype.remove = function() {
        if (this.element && this.element.parentElement) {
            this.element.parentElement.removeChild(this.element);
        }

        return this;
    }

    DomElement.prototype.show = function() {
        if (!this.element) return this;

        var oldDisplay = this.attr('data-olddisplay');
        if (typeof oldDisplay !== 'undefined' && oldDisplay) {
            this.element.style.display = oldDisplay;
        }

        if (!this.isVisible()) {
            this.element.style.display = 'block';
        }
    }

    DomElement.prototype.hide = function() {
        if (!this.element) return this;

        var oldDisplay = this.element.style.display;

        this.attr('data-olddisplay', oldDisplay);
        this.element.style.display = 'none';

        return this;
    }

    //Getter only
    DomElement.prototype.css = function(name) {
        if (!this.element) return '';

        var styles = getComputedStyle(this.element);
        name = toCamelCase(name);

        return typeof styles[name] !== 'undefined' ? styles[name] : '';
    }

    DomElement.prototype.index = function() {
        if (!this.element || !this.element.parentElement) return -1;

        var parent = this.element.parentElement;
        var siblings = parent.children;

        for (var i = 0; i < siblings.length; i++) {
            if (siblings[i] === this.element) return i;
        }

        return -1;
    }

    DomElement.prototype.children = function() {
        if (!this.element) return new DomList(null);

        var items = [];
        var kids = this.element.children;

        for (var i = 0; i < kids.length; i++) {
            items.push(kids[i]);
        }

        return new DomList(items);
    }

    DomElement.prototype.outerHeight = function() {
        return this.element ? this.element.offsetHeight : 0;
    }

    DomElement.prototype.position = function() {
        if (!this.element) return {top: 0, left: 0};

        return {
            top: this.element.offsetTop,
            left: this.element.offsetLeft
        }
    }

    DomElement.prototype.offset = function() {
        if (!this.element) return {top: 0, left: 0};

        var rect = this.element.getBoundingClientRect();

        return {
            top: rect.top + window.pageYOffset,
            left: rect.left + window.pageXOffset
        };
    }

    DomElement.prototype.scrollTop = function(pos, duration) {
        if (this.element) {
            duration ?
                animateScrollTop(this.element, pos, duration) :
                this.element.scrollTop = pos;
        }

        return this;
    }

    DomElement.prototype.parentsUntil = function(tillSelector, filterSelector) {
        if (!this.element) return new DomList(null);

        var items = [];
        var parent = this.element;

        while (parent = parent.parentElement) {
            var matches =
                (typeof tillSelector === 'undefined' || !parent.matches(tillSelector)) &&
                (typeof filterSelector === 'undefined' || parent.matches(filterSelector));

            if (matches) items.push(parent);
        }

        return new DomList(items);
    }

    DomElement.prototype.width = function(width) {
        if (typeof width === 'undefined') {
            return this.element ? this.element.offsetWidth : 0;
        }

        if (this.element) {
            this.element.style.width = width;
        }

        return this;
    }

    DomElement.prototype.height = function(height) {
        if (typeof height === 'undefined') {
            return this.element ? this.element.offsetHeight : 0;
        }

        if (this.element) {
            this.element.style.height = height;
        }

        return this;
    }

    DomElement.prototype.isVisible = function() {
        if (!this.element) return false;

        return !!(
            this.element.offsetWidth ||
            this.element.offsetHeight ||
            this.element.getClientRects().length
        );
    }

    DomElement.prototype.val = function(value) {
        if (typeof value !== 'undefined') {
            if (this.element) this.element.value = value;

            return this;
        }

        return this.element ? this.element.value : '';
    }

    DomElement.prototype.focus = function(value) {
        if (this.element) {
            this.element.focus();
        }

        return this;
    }

    DomElement.prototype.append = function(element) {
        if (!this.element || !element.element) return this;

        this.element.appendChild(element.element);

        return this;
    }
}
<|endoftext|>


<commit_before>const R = require('ramda');

const removeUserNameAndLevelTime = (rawString) => R.replace(/\(.*?\)/g, ',', rawString);

const parseLevelTime = (str) => R.pipe(
    R.split('.'),
    R.dropLast(1),
    R.insert(3, 'T'),
    R.join('')
  )(str);

const getCorrectTimeFromString = (type, strArray) => R.pipe(
  R.indexOf(type),
  R.flip(R.subtract)(1),
  R.of,
  R.flip(R.path)(strArray),
  parseInt
)(strArray);

const convertStringToTime = (strArray) => ({
  days: R.contains('д', strArray) ? getCorrectTimeFromString('д', strArray) : 0,
  hours: R.contains('ч', strArray) ? getCorrectTimeFromString('ч', strArray) : 0,
  minutes: R.contains('м', strArray) ? getCorrectTimeFromString('м', strArray) : 0,
  seconds: R.contains('с', strArray) ? getCorrectTimeFromString('с', strArray) : 0,
});

const parseBonusPenaltyTime = (str) => R.pipe(
    R.replace('бонус ', ''),
    R.split(' '),
    convertStringToTime
  )(str);

const getBonusesPenaltiesTime = (str) => {
  if (R.test(/бонус/, str)) {
    return { bonus: parseBonusPenaltyTime(str) };
  } else if (R.test(/штраф/, str)) {
    return { penalty: parseBonusPenaltyTime(str) };
  }
  return undefined;
};

const parseBonusesAndPenalties = (str) => R.pipe(
    R.replace('таймаут', ''),
    getBonusesPenaltiesTime
  )(str);

const parseTeamString = (teamString) => ({
  name: R.pathOr('', [0], teamString),
  time: R.isNil(R.path([1], teamString)) ? null : parseLevelTime(teamString[1]),
  additions: R.isNil(R.path([2], teamString)) ? null : parseBonusesAndPenalties(teamString[2]),
});

const getTeamData = (team) => R.pipe(
    R.slice(1, -1),
    R.map(removeUserNameAndLevelTime),
    R.map(R.split(',')),
    R.map(parseTeamString)
  )(team);

exports.getTeamData = (stat) => R.map(getTeamData, stat);
<commit_msg>revert back time changes<commit_after>const R = require('ramda');

const removeUserNameAndLevelTime = (rawString) => R.replace(/\(.*?\)/g, ',', rawString);

const parseLevelTime = (str) => R.pipe(
    R.splitAt(10),
    R.insert(1, 'T'),
    R.join('')
  )(str);

const getCorrectTimeFromString = (type, strArray) => R.pipe(
  R.indexOf(type),
  R.flip(R.subtract)(1),
  R.of,
  R.flip(R.path)(strArray),
  parseInt
)(strArray);

const convertStringToTime = (strArray) => ({
  days: R.contains('д', strArray) ? getCorrectTimeFromString('д', strArray) : 0,
  hours: R.contains('ч', strArray) ? getCorrectTimeFromString('ч', strArray) : 0,
  minutes: R.contains('м', strArray) ? getCorrectTimeFromString('м', strArray) : 0,
  seconds: R.contains('с', strArray) ? getCorrectTimeFromString('с', strArray) : 0,
});

const parseBonusPenaltyTime = (str) => R.pipe(
    R.replace('бонус ', ''),
    R.split(' '),
    convertStringToTime
  )(str);

const getBonusesPenaltiesTime = (str) => {
  if (R.test(/бонус/, str)) {
    return { bonus: parseBonusPenaltyTime(str) };
  } else if (R.test(/штраф/, str)) {
    return { penalty: parseBonusPenaltyTime(str) };
  }
  return undefined;
};

const parseBonusesAndPenalties = (str) => R.pipe(
    R.replace('таймаут', ''),
    getBonusesPenaltiesTime
  )(str);

const parseTeamString = (teamString) => ({
  name: R.pathOr('', [0], teamString),
  time: R.isNil(R.path([1], teamString)) ? null : parseLevelTime(teamString[1]),
  additions: R.isNil(R.path([2], teamString)) ? null : parseBonusesAndPenalties(teamString[2]),
});

const getTeamData = (team) => R.pipe(
    R.slice(1, -1),
    R.map(removeUserNameAndLevelTime),
    R.map(R.split(',')),
    R.map(parseTeamString)
  )(team);

exports.getTeamData = (stat) => R.map(getTeamData, stat);
<|endoftext|>


<commit_before>//= require "codemirror"
//= require "mobileCodeMirror"
//= require "library"
//= require "unsaved"
var focusPanel = 'javascript';
var editors = {};

window.editors = editors;

editors.html = CodeMirror.fromTextArea(document.getElementById('html'), {
  parserfile: [],
  tabMode: 'shift',
  mode: 'text/html',
  onChange: changecontrol,
  theme: jsbin.settings.theme || 'jsbin'
});

editors.javascript = CodeMirror.fromTextArea(document.getElementById('javascript'), {
  mode: 'css',
  tabMode: 'shift',
  onChange: changecontrol,
  theme: jsbin.settings.theme || 'jsbin'
});

setupEditor('javascript');
setupEditor('html');

var editorsReady = setInterval(function () {
  if (editors.html.ready && editors.javascript.ready) {
    clearInterval(editorsReady);
    editors.ready = true;
    if (typeof editors.onReady == 'function') editors.onReady();

    var scrollers = {
      html: $(editors.html.getScrollerElement()),
      javascript: $(editors.javascript.getScrollerElement())
    };

    $document.bind('sizeeditors', function () {
      var top = 0, //$el.offset().top,
          height = $('#bin').height();
      scrollers.html.height(height - top);
      scrollers.javascript.height(height - top - $error.filter(':visible').height());
      editors.javascript.refresh();
      editors.html.refresh();
    });

    $(window).resize(function () {
      setTimeout(function () {
        $document.trigger('sizeeditors');
      }, 100);
    });

    $document.trigger('sizeeditors');
    $document.trigger('jsbinReady');
  }
}, 100);

// $('#javascript').replaceWith('

');
// $('#javascript').css({ height: '100%', width: '100%' });
// $('#html').replaceWith('

');
// $('#html').css({ height: '100%', width: '100%' });
//
// editors.javascript = ace.edit("javascript");
// editors.html = ace.edit("html");
//
// var JavaScriptMode = require("ace/mode/javascript").Mode,
//     HTMLMode = require("ace/mode/html").Mode;
//
// setupAce(editors, 'javascript');
// setupAce(editors, 'html');
//
// function setupAce(editor, type) {
//   var session = editors[type].getSession(),
//       renderer = editors[type].renderer;
//   if (type == 'javascript') {
//     session.setMode(new JavaScriptMode());
//   } else {
//     session.setMode(new HTMLMode());
//   }
//
//   editors[type].setHighlightActiveLine(false);
//   session.setUseWrapMode(true);
//   session.setUseSoftTabs(true);
//   session.setWrapLimitRange(null, null);
//
//   renderer.setShowPrintMargin(false);
//   renderer.setShowGutter(false);
//   renderer.setHScrollBarAlwaysVisible(false);
// }

function focused(editor, event) {
  focusPanel = editor.id;
}

function getFocusedPanel() {
  return focusPanel;
}

function setupEditor(panel) {
  var e = editors[panel],
      focusedPanel = sessionStorage.getItem('panel');

  // overhang from CodeMirror1
  e.setCode = function (str) {
    e.setValue(str);
  };

  e.getCode = function () {
    return e.getValue();
  };

  e.currentLine = function () {
    var pos = e.getCursor();
    return pos.line;
  };

  e.setOption('onChange', changecontrol);
  e.setOption('onKeyEvent', keycontrol);
  e.setOption('onFocus', focused);

  e.id = panel;

  e.win = e.getWrapperElement();
  e.scroller = $(e.getScrollerElement());

  $(e.win).click(function () {
    e.focus();
  });

  var $label = $('.code.' + panel + ' > .label');
  if (document.body.className.indexOf('ie6') === -1) {
    e.scroller.scroll(function (event) {
      if (this.scrollTop > 10) {
        $label.stop().animate({ opacity: 0 }, 50, function () {
          $(this).hide();
        });
      } else {
        $label.show().stop().animate({ opacity: 1 }, 250);
      }
    });
  }

  populateEditor(panel);
  e.ready = true;

  if (focusedPanel == panel || focusedPanel == null && panel == 'javascript') {
    // e.selectLines(e.nthLine(sessionStorage.getItem('line')), sessionStorage.getItem('character'));
    e.focus();
    e.setCursor({ line: (sessionStorage.getItem('line') || 0) * 1, ch: (sessionStorage.getItem('character') || 0) * 1 });
  }
}

function populateEditor(panel) {
  // populate - should eventually use: session, saved data, local storage
  var data = sessionStorage.getItem(panel), // session code
      saved = localStorage.getItem('saved-' + panel), // user template
      sessionURL = sessionStorage.getItem('url'),
      changed = false;

  if (data == template[panel]) { // restored from original saved
    editors[panel].setCode(data);
  } else if (data && sessionURL == template.url) { // try to restore the session first - only if it matches this url
    editors[panel].setCode(data);
    // tell the document that it's currently being edited, but check that it doesn't match the saved template
    // because sessionStorage gets set on a reload
    changed = data != saved;
  } else if (saved !== null && !/edit/.test(window.location) && !window.location.search) { // then their saved preference
    editors[panel].setCode(saved);
  } else { // otherwise fall back on the JS Bin default
    editors[panel].setCode(template[panel]);
  }

  if (changed) {
    $(document).trigger('codeChange', [ /* revert triggered */ false, /* don't use fade */ true ]);
  }
}

// work out the browser platform
var ua = navigator.userAgent;
if (/macintosh|mac os x/.test(ua)) {
  $.browser.platform = 'mac';
} else if (/windows|win32/.test(ua)) {
  $.browser.platform = 'win';
} else if (/linux/.test(ua)) {
  $.browser.platform = 'linux';
} else {
  $.browser.platform = '';
}

function changecontrol(event) {
  // sends message to the document saying that a key has been pressed, we'll ignore the control keys
  // if (! ({ 16:1, 17:1, 18:1, 20:1, 27:1, 37:1, 38:1, 39:1, 40:1, 91:1, 93:1 })[event.which] ) {
    $(document).trigger('codeChange');
  // }

  return true;
}

//= require "keycontrol"<commit_msg>set initial cursor position in html body<commit_after>//= require "codemirror"
//= require "mobileCodeMirror"
//= require "library"
//= require "unsaved"
var focusPanel = 'javascript';
var editors = {};

window.editors = editors;

editors.html = CodeMirror.fromTextArea(document.getElementById('html'), {
  parserfile: [],
  tabMode: 'shift',
  mode: 'text/html',
  onChange: changecontrol,
  theme: jsbin.settings.theme || 'jsbin'
});

editors.javascript = CodeMirror.fromTextArea(document.getElementById('javascript'), {
  mode: 'css',
  tabMode: 'shift',
  onChange: changecontrol,
  theme: jsbin.settings.theme || 'jsbin'
});

setupEditor('javascript');
setupEditor('html');

var editorsReady = setInterval(function () {
  if (editors.html.ready && editors.javascript.ready) {

    editors.html.setCursor(7, 8);

    clearInterval(editorsReady);
    editors.ready = true;
    if (typeof editors.onReady == 'function') editors.onReady();

    var scrollers = {
      html: $(editors.html.getScrollerElement()),
      javascript: $(editors.javascript.getScrollerElement())
    };

    $document.bind('sizeeditors', function () {
      var top = 0, //$el.offset().top,
          height = $('#bin').height();
      scrollers.html.height(height - top);
      scrollers.javascript.height(height - top - $error.filter(':visible').height());
      editors.javascript.refresh();
      editors.html.refresh();
    });

    $(window).resize(function () {
      setTimeout(function () {
        $document.trigger('sizeeditors');
      }, 100);
    });

    $document.trigger('sizeeditors');
    $document.trigger('jsbinReady');
  }
}, 100);

// $('#javascript').replaceWith('

');
// $('#javascript').css({ height: '100%', width: '100%' });
// $('#html').replaceWith('

');
// $('#html').css({ height: '100%', width: '100%' });
//
// editors.javascript = ace.edit("javascript");
// editors.html = ace.edit("html");
//
// var JavaScriptMode = require("ace/mode/javascript").Mode,
//     HTMLMode = require("ace/mode/html").Mode;
//
// setupAce(editors, 'javascript');
// setupAce(editors, 'html');
//
// function setupAce(editor, type) {
//   var session = editors[type].getSession(),
//       renderer = editors[type].renderer;
//   if (type == 'javascript') {
//     session.setMode(new JavaScriptMode());
//   } else {
//     session.setMode(new HTMLMode());
//   }
//
//   editors[type].setHighlightActiveLine(false);
//   session.setUseWrapMode(true);
//   session.setUseSoftTabs(true);
//   session.setWrapLimitRange(null, null);
//
//   renderer.setShowPrintMargin(false);
//   renderer.setShowGutter(false);
//   renderer.setHScrollBarAlwaysVisible(false);
// }

function focused(editor, event) {
  focusPanel = editor.id;
}

function getFocusedPanel() {
  return focusPanel;
}

function setupEditor(panel) {
  var e = editors[panel],
      focusedPanel = sessionStorage.getItem('panel');

  // overhang from CodeMirror1
  e.setCode = function (str) {
    e.setValue(str);
  };

  e.getCode = function () {
    return e.getValue();
  };

  e.currentLine = function () {
    var pos = e.getCursor();
    return pos.line;
  };

  e.setOption('onChange', changecontrol);
  e.setOption('onKeyEvent', keycontrol);
  e.setOption('onFocus', focused);

  e.id = panel;

  e.win = e.getWrapperElement();
  e.scroller = $(e.getScrollerElement());

  $(e.win).click(function () {
    e.focus();
  });

  var $label = $('.code.' + panel + ' > .label');
  if (document.body.className.indexOf('ie6') === -1) {
    e.scroller.scroll(function (event) {
      if (this.scrollTop > 10) {
        $label.stop().animate({ opacity: 0 }, 50, function () {
          $(this).hide();
        });
      } else {
        $label.show().stop().animate({ opacity: 1 }, 250);
      }
    });
  }

  populateEditor(panel);
  e.ready = true;

  if (focusedPanel == panel || focusedPanel == null && panel == 'javascript') {
    // e.selectLines(e.nthLine(sessionStorage.getItem('line')), sessionStorage.getItem('character'));
    e.focus();
    e.setCursor({ line: (sessionStorage.getItem('line') || 0) * 1, ch: (sessionStorage.getItem('character') || 0) * 1 });
  }
}

function populateEditor(panel) {
  // populate - should eventually use: session, saved data, local storage
  var data = sessionStorage.getItem(panel), // session code
      saved = localStorage.getItem('saved-' + panel), // user template
      sessionURL = sessionStorage.getItem('url'),
      changed = false;

  if (data == template[panel]) { // restored from original saved
    editors[panel].setCode(data);
  } else if (data && sessionURL == template.url) { // try to restore the session first - only if it matches this url
    editors[panel].setCode(data);
    // tell the document that it's currently being edited, but check that it doesn't match the saved template
    // because sessionStorage gets set on a reload
    changed = data != saved;
  } else if (saved !== null && !/edit/.test(window.location) && !window.location.search) { // then their saved preference
    editors[panel].setCode(saved);
  } else { // otherwise fall back on the JS Bin default
    editors[panel].setCode(template[panel]);
  }

  if (changed) {
    $(document).trigger('codeChange', [ /* revert triggered */ false, /* don't use fade */ true ]);
  }
}

// work out the browser platform
var ua = navigator.userAgent;
if (/macintosh|mac os x/.test(ua)) {
  $.browser.platform = 'mac';
} else if (/windows|win32/.test(ua)) {
  $.browser.platform = 'win';
} else if (/linux/.test(ua)) {
  $.browser.platform = 'linux';
} else {
  $.browser.platform = '';
}

function changecontrol(event) {
  // sends message to the document saying that a key has been pressed, we'll ignore the control keys
  // if (! ({ 16:1, 17:1, 18:1, 20:1, 27:1, 37:1, 38:1, 39:1, 40:1, 91:1, 93:1 })[event.which] ) {
    $(document).trigger('codeChange');
  // }

  return true;
}

//= require "keycontrol"<|endoftext|>


<commit_before><commit_msg>removed utils folder for now, not needed<commit_after><|endoftext|>