<commit_before>(function (Q, $, window, undefined) {

/**
 * @module Streams-tools
 */

/**
 * Renders a preview for a Streams/image stream
 * @class Streams image preview
 * @constructor
 * @param {Object} [options] any options for the tool
 *   @param {Object} [options.inplace] Any options to pass to the Q/inplace tool -- see its options.
 *   @uses Q inplace
 *   @param {Boolean} [options.showTitle=true] Whether to display the title of the image stream
 *   @param {Boolean} [options.updateTitle=false] Whether to update the title to reflect the file name
 *   of an image
 *   @param {Boolean} [options.dontSetSize=false] If true, shows the image in its natural size instead of using preview.state.imagepicker.showSize
 *   @param {Object} [options.templates] Under the keys "views", "edit" and "create" you can override options for Q.Template.render .
 *     @param {Object} [options.templates.view]
 *       @param {String} [options.templates.view.name='Streams/image/preview/view']
 *       @param {Object} [options.templates.view.fields]
 *         @param {String} [options.templates.view.fields.alt]
 *         @param {String} [options.templates.view.fields.showTitle]
 *         @param {String} [options.templates.view.fields.titleClass]
 *         @param {String} [options.templates.view.fields.titleTag]
 *     @param {Object} [options.templates.edit]
 *       @param {String} [options.templates.edit.name='Streams/image/preview/edit']
 *       @param {Object} [options.templates.edit.fields]
 *         @param {String} [options.templates.edit.fields.alt]
 *         @param {String} [options.templates.view.fields.showTitle]
 *         @param {String} [options.templates.edit.fields.titleClass]
 *         @param {String} [options.templates.edit.fields.titleTag]
 *     @param {Object} [options.templates.create]
 *       @param {String} [options.templates.create.name='Streams/image/preview/create']
 *       @param {Object} [options.templates.create.fields]
 *         @param {String} [options.templates.create.fields.alt]
 *         @param {String} [options.templates.create.fields.showTitle]
 *         @param {String} [options.templates.create.fields.titleClass]
 *         @param {String} [options.templates.create.fields.titleTag]
 */
Q.Tool.define("Streams/image/preview", "Streams/preview", function(options, preview) {
	var tool = this;
	var state = tool.state;
	var ps = preview.state;
	tool.preview = preview;
	if (ps.actions) {
		ps.actions.position = 'tr';
	}
	ps.templates.create.name = 'Streams/image/preview/create';
	ps.templates.create.showTitle = (state.showTitle !== false);
	if (ps.creatable) {
		ps.creatable.streamType = ps.creatable.streamType || 'Streams/image';
		ps.creatable.title = ps.creatable.title || 'New Image';
	}
	ps.onRefresh.add(tool.refresh.bind(tool), tool);
	ps.onComposer.add(tool.composer.bind(tool), tool);
},

{
	inplace: {},
	dontSetSize: false,
	showTitle: true,
	updateTitle: false,
	templates: {
		view: {
			name: 'Streams/image/preview/view',
			fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
		},
		edit: {
			name: 'Streams/image/preview/edit',
			fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
		},
		create: {
			name: 'Streams/image/preview/edit',
			fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
		}
	}
},

{
	refresh: function (stream, onLoad) {
		var tool = this;
		var state = tool.state;
		var ps = tool.preview.state;
		var sf = stream.fields;
		var attributes = sf.attributes && JSON.parse(sf.attributes);

		// set up a pipe to know when the icon has loaded
		var p = Q.pipe(['inplace', 'icon'], function () {
			Q.handle(onLoad, tool);
		});
		// set up the inplace options
		var inplace = null;
		if (state.inplace) {
			var inplaceOptions = Q.extend({
				publisherId: ps.publisherId,
				streamName: ps.streamName,
				field: 'title',
				inplaceType: 'text'
			}, state.inplace);
			var se = ps.editable;
			if (!se || (se !== true && se.indexOf('title') < 0)) {
				inplaceOptions.editable = false;
			}
			inplace = tool.setUpElementHTML('div', 'Streams/inplace', inplaceOptions);
		}
		// render a template
		var f = state.template && state.template.fields;
		var fields = Q.extend({}, state.templates.edit.fields, f, {
			alt: sf.title,
			title: sf.title,
			inplace: inplace,
			showTitle: state.showTitle !== false
		});
		var tpl = (state.editable !== false || stream.testWriteLevel('suggest'))
			? 'edit'
			: 'view';
		Q.Template.render(
			'Streams/image/preview/'+tpl,
			fields,
			function (err, html) {
				if (err) return;
				tool.element.innerHTML = html;
				var $img = tool.$('.Streams_image_preview_icon');
				var src = tool.element.getAttribute('data-icon-src');
				if (src) {
					$img.attr('src', src);
				}
				Q.activate(tool, function () {
					// load the icon
					Q.extend(ps.imagepicker.onSuccess, {
						"Streams/image/preview": function (data, key, file) {
							if (state.updateTitle && file && file.name) {
								ps.stream.fields.title = file.name;
								ps.stream.save({
									changed: { icon: true }
								});
							}
						}
					});
					var $jq = tool.$('img.Streams_image_preview_icon');
					tool.preview.icon($jq[0], p.fill('icon'));
					var child = tool.child('Streams_inplace');
					if (child) {
						child.state.onLoad.add(p.fill('inplace'));
					}
					var parts = ps.imagepicker.showSize.split('x');
					if (!state.dontSetSize) {
						var $img = tool.$('.Streams_image_preview_icon');
						if (parts[0]) {
							$img.width(parts[0]);
						}
						if (parts[1]) {
							$img.height(parts[1]);
						}
					}
				});
			},
			state.templates[tpl]
		);
	},
	composer: function () {
		var tool = this;
		var ps = tool.preview.state;
		var src = Q.url('{{Q}}/img/actions/add.png');
		this.$('img.Streams_preview_add').attr('src', src);

		// add imagepicker
		var ipo = Q.extend({}, ps.imagepicker, 10, {
			preprocess: function (callback) {
				if (ps.creatable && ps.creatable.preprocess) {
					Q.handle(ps.creatable.preprocess, this, [_proceed, tool, event]);
				} else {
					_proceed();
				}
				var r = ps.related;
				Q.Streams.retainWith(tool)
				function _proceed(overrides, weight) {
					if (overrides != undefined && !Q.isPlainObject(overrides)) {
						return;
					}
					var fields = Q.extend({
						publisherId: ps.publisherId,
						type: (ps.creatable && ps.creatable.streamType) || "Streams/image"
					}, 10, overrides);
					Q.Streams.create(fields, function (err, stream, extra) {
						var path, subpath;
						if (err) {
							ps.onError.handle.call(tool, err);
							Q.handle(callback, tool, [{cancel: true}]);
							return err;
						}
						var iconUrl = this.iconUrl(40);
						var p = 'Q/plugins/';
						var i = this.iconUrl(40).indexOf('Q/plugins/');
						if (iconUrl.substr(i+p.length).startsWith('Users/')) {
							// uploading a user icon
							path = 'Q/uploads/Users';
							subpath = ps.publisherId.splitId() + '/icon';
						} else { // uploading a regular stream icon
							path = 'Q/uploads/Streams';
							subpath = ps.publisherId.splitId() + '/'
								+ stream.fields.name + '/icon';
						}
						subpath += '/'+Math.floor(Date.now()/1000);
						callback({ path: path, subpath: subpath });
						tool.element.removeClass('Streams_preview_composer');
						tool.element.addClass('Streams_preview_stream');
						setTimeout(function () {
							tool.preview.loading();
						}, 0);
						ps.streamName = stream.fields.name;
					}, r, ps.creatable && ps.creatable.options);
				}
			},
			onFinish: {'Streams/image/preview': function (data, key, file) {
				Q.Streams.Stream.refresh(ps.publisherId, ps.streamName, null, {
					messages: true,
					changed: {icon: true},
					evenIfNotRetained: true
				});
				ps.onCreate.handle.call(tool, this);
				tool.element.removeClass('Streams_preview_composer');
				tool.element.addClass('Streams_preview_stream');
				tool.preview.preview();
				return false;
			}}
		});
		var p = Q.pipe(['imagepicker', 'load'], function () {
			Q.handle(onLoad, tool, [element]);
		});
		var $element = this.$('.Streams_preview_create')
		.plugin('Q/imagepicker', ipo, p.fill('imagepicker'));
		$element.off('load.Streams-preview')
		.on('load.Streams-preview', p.fill('load'));
		var container = this.$('.Streams_preview_container');
		// override the fastclick handler that the Streams/preview tool set
		container.off([Q.Pointer.fastclick, '.Streams_preview']);
		container.on([Q.Pointer.fastclick, '.Streams_image_preview'], function () {
			return;
			tool.create.bind(tool);
		});
	}
}

);

Q.Template.set('Streams/image/preview/view',
	'
'
	+ ''
	+ '
'
	+ '{{#if showTitle}}'
	+ '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
	+ '{{/if}}'
	+ '

'
);

Q.Template.set('Streams/image/preview/edit',
	'
'
	+ ''
	+ '
'
	+ '{{#if showTitle}}'
	+ '<{{titleTag}} class="Streams_preview_title">{{& inplace}}</{{titleTag}}>'
	+ '{{/if}}'
	+ '

'
);

Q.Template.set('Streams/image/preview/create',
	'
'
	+ ''
	+ '
'
	+ '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
	+ '

'
);

})(Q, Q.$, window);<commit_msg>Fixed Streams/image/preview tool "composer" method . Make possible to relate new streams to relation states of Streams/preview tool.<commit_after>(function (Q, $, window, undefined) {

/**
 * @module Streams-tools
 */

/**
 * Renders a preview for a Streams/image stream
 * @class Streams image preview
 * @constructor
 * @param {Object} [options] any options for the tool
 *   @param {Object} [options.inplace] Any options to pass to the Q/inplace tool -- see its options.
 *   @uses Q inplace
 *   @param {Boolean} [options.showTitle=true] Whether to display the title of the image stream
 *   @param {Boolean} [options.updateTitle=false] Whether to update the title to reflect the file name
 *   of an image
 *   @param {Boolean} [options.dontSetSize=false] If true, shows the image in its natural size instead of using preview.state.imagepicker.showSize
 *   @param {Object} [options.templates] Under the keys "views", "edit" and "create" you can override options for Q.Template.render .
 *     @param {Object} [options.templates.view]
 *       @param {String} [options.templates.view.name='Streams/image/preview/view']
 *       @param {Object} [options.templates.view.fields]
 *         @param {String} [options.templates.view.fields.alt]
 *         @param {String} [options.templates.view.fields.showTitle]
 *         @param {String} [options.templates.view.fields.titleClass]
 *         @param {String} [options.templates.view.fields.titleTag]
 *     @param {Object} [options.templates.edit]
 *       @param {String} [options.templates.edit.name='Streams/image/preview/edit']
 *       @param {Object} [options.templates.edit.fields]
 *         @param {String} [options.templates.edit.fields.alt]
 *         @param {String} [options.templates.view.fields.showTitle]
 *         @param {String} [options.templates.edit.fields.titleClass]
 *         @param {String} [options.templates.edit.fields.titleTag]
 *     @param {Object} [options.templates.create]
 *       @param {String} [options.templates.create.name='Streams/image/preview/create']
 *       @param {Object} [options.templates.create.fields]
 *         @param {String} [options.templates.create.fields.alt]
 *         @param {String} [options.templates.create.fields.showTitle]
 *         @param {String} [options.templates.create.fields.titleClass]
 *         @param {String} [options.templates.create.fields.titleTag]
 */
Q.Tool.define("Streams/image/preview", "Streams/preview", function(options, preview) {
	var tool = this;
	var state = tool.state;
	var ps = preview.state;
	tool.preview = preview;
	if (ps.actions) {
		ps.actions.position = 'tr';
	}
	ps.templates.create.name = 'Streams/image/preview/create';
	ps.templates.create.showTitle = (state.showTitle !== false);
	if (ps.creatable) {
		ps.creatable.streamType = ps.creatable.streamType || 'Streams/image';
		ps.creatable.title = ps.creatable.title || 'New Image';
	}
	ps.onRefresh.add(tool.refresh.bind(tool), tool);
	ps.onComposer.add(tool.composer.bind(tool), tool);
},

{
	inplace: {},
	dontSetSize: false,
	showTitle: true,
	updateTitle: false,
	templates: {
		view: {
			name: 'Streams/image/preview/view',
			fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
		},
		edit: {
			name: 'Streams/image/preview/edit',
			fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
		},
		create: {
			name: 'Streams/image/preview/edit',
			fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
		}
	}
},

{
	refresh: function (stream, onLoad) {
		var tool = this;
		var state = tool.state;
		var ps = tool.preview.state;
		var sf = stream.fields;
		var attributes = sf.attributes && JSON.parse(sf.attributes);

		// set up a pipe to know when the icon has loaded
		var p = Q.pipe(['inplace', 'icon'], function () {
			Q.handle(onLoad, tool);
		});
		// set up the inplace options
		var inplace = null;
		if (state.inplace) {
			var inplaceOptions = Q.extend({
				publisherId: ps.publisherId,
				streamName: ps.streamName,
				field: 'title',
				inplaceType: 'text'
			}, state.inplace);
			var se = ps.editable;
			if (!se || (se !== true && se.indexOf('title') < 0)) {
				inplaceOptions.editable = false;
			}
			inplace = tool.setUpElementHTML('div', 'Streams/inplace', inplaceOptions);
		}
		// render a template
		var f = state.template && state.template.fields;
		var fields = Q.extend({}, state.templates.edit.fields, f, {
			alt: sf.title,
			title: sf.title,
			inplace: inplace,
			showTitle: state.showTitle !== false
		});
		var tpl = (state.editable !== false || stream.testWriteLevel('suggest'))
			? 'edit'
			: 'view';
		Q.Template.render(
			'Streams/image/preview/'+tpl,
			fields,
			function (err, html) {
				if (err) return;
				tool.element.innerHTML = html;
				var $img = tool.$('.Streams_image_preview_icon');
				var src = tool.element.getAttribute('data-icon-src');
				if (src) {
					$img.attr('src', src);
				}
				Q.activate(tool, function () {
					// load the icon
					Q.extend(ps.imagepicker.onSuccess, {
						"Streams/image/preview": function (data, key, file) {
							if (state.updateTitle && file && file.name) {
								ps.stream.fields.title = file.name;
								ps.stream.save({
									changed: { icon: true }
								});
							}
						}
					});
					var $jq = tool.$('img.Streams_image_preview_icon');
					tool.preview.icon($jq[0], p.fill('icon'));
					var child = tool.child('Streams_inplace');
					if (child) {
						child.state.onLoad.add(p.fill('inplace'));
					}
					var parts = ps.imagepicker.showSize.split('x');
					if (!state.dontSetSize) {
						var $img = tool.$('.Streams_image_preview_icon');
						if (parts[0]) {
							$img.width(parts[0]);
						}
						if (parts[1]) {
							$img.height(parts[1]);
						}
					}
				});
			},
			state.templates[tpl]
		);
	},
	composer: function () {
		var tool = this;
		var ps = tool.preview.state;
		var src = Q.url('{{Q}}/img/actions/add.png');
		this.$('img.Streams_preview_add').attr('src', src);

		// add imagepicker
		var ipo = Q.extend({}, ps.imagepicker, 10, {
			preprocess: function (callback) {
				if (ps.creatable && ps.creatable.preprocess) {
					Q.handle(ps.creatable.preprocess, this, [_proceed, tool, event]);
				} else {
					_proceed();
				}
				Q.Streams.retainWith(tool);
				function _proceed(overrides, weight) {
					if (overrides != undefined && !Q.isPlainObject(overrides)) {
						return;
					}
					var fields = Q.extend({
						publisherId: ps.publisherId,
						type: (ps.creatable && ps.creatable.streamType) || "Streams/image"
					}, 10, overrides);
					Q.Streams.create(fields, function (err, stream, extra) {
						var path, subpath;
						if (err) {
							ps.onError.handle.call(tool, err);
							Q.handle(callback, tool, [{cancel: true}]);
							return err;
						}
						var iconUrl = this.iconUrl(40);
						var p = 'Q/plugins/';
						var i = this.iconUrl(40).indexOf('Q/plugins/');
						if (iconUrl.substr(i+p.length).startsWith('Users/')) {
							// uploading a user icon
							path = 'Q/uploads/Users';
							subpath = ps.publisherId.splitId() + '/icon';
						} else { // uploading a regular stream icon
							path = 'Q/uploads/Streams';
							subpath = ps.publisherId.splitId() + '/'
								+ stream.fields.name + '/icon';
						}
						subpath += '/'+Math.floor(Date.now()/1000);
						callback({ path: path, subpath: subpath });
						tool.element.removeClass('Streams_preview_composer');
						tool.element.addClass('Streams_preview_stream');
						setTimeout(function () {
							tool.preview.loading();
						}, 0);
						ps.streamName = stream.fields.name;
					}, ps.related, ps.creatable && ps.creatable.options);
				}
			},
			onFinish: {'Streams/image/preview': function (data, key, file) {
				Q.Streams.Stream.refresh(ps.publisherId, ps.streamName, null, {
					messages: true,
					changed: {icon: true},
					evenIfNotRetained: true
				});
				ps.onCreate.handle.call(tool, this);
				tool.element.removeClass('Streams_preview_composer');
				tool.element.addClass('Streams_preview_stream');
				tool.preview.preview();
				return false;
			}}
		});
		var p = Q.pipe(['imagepicker', 'load'], function () {
			Q.handle(onLoad, tool, [element]);
		});
		var $element = this.$('.Streams_preview_create')
		.plugin('Q/imagepicker', ipo, p.fill('imagepicker'));
		$element.off('load.Streams-preview')
		.on('load.Streams-preview', p.fill('load'));
		var container = this.$('.Streams_preview_container');
		// override the fastclick handler that the Streams/preview tool set
		container.off([Q.Pointer.fastclick, '.Streams_preview']);
		container.on([Q.Pointer.fastclick, '.Streams_image_preview'], function () {
			return;
			tool.create.bind(tool);
		});
	}
}

);

Q.Template.set('Streams/image/preview/view',
	'
'
	+ ''
	+ '
'
	+ '{{#if showTitle}}'
	+ '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
	+ '{{/if}}'
	+ '

'
);

Q.Template.set('Streams/image/preview/edit',
	'
'
	+ ''
	+ '
'
	+ '{{#if showTitle}}'
	+ '<{{titleTag}} class="Streams_preview_title">{{& inplace}}</{{titleTag}}>'
	+ '{{/if}}'
	+ '

'
);

Q.Template.set('Streams/image/preview/create',
	'
'
	+ ''
	+ '
'
	+ '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
	+ '

'
);

})(Q, Q.$, window);<|endoftext|>


<commit_before>// Javascript code for Marvin DAP QA plots/comments on individual plates

// toggle DAP categories
$(function() {
	$('#dapqacat_select').change(function() {
		var key = $(this).val();
		// show category options
		$('.dapqacatoptions').hide();
		$('#dapqacatoptions_'+key).show();
		// show option reminder
		$('.qacomment').html('');
		// set default selection
		setDefault(key);
	});
});

// reset dapqa form on page load
/*$(function() {
	$('.dapqacomment_form').trigger('reset');
	$('.qacomment').html('');
	// load a default
	var key = 'maps';
	setDefault(key);

	var dapqa = new Dapqa('7443','9101','10');
	if (typeof dapqa != 'undefined') {
	console.log('dapqa',dapqa);
	dapqa.print();
	console.log('mainpane',dapqa.mainpane);
	console.log('qaform',dapqa.qaform.find('#dapqacat'));
	}
});*/

// dapqa tab selection
$(function(){
	$('#cubetabs a[href*="dapqapane"]').click(function() {
		var ifu = getIFUHash().slice(1);
		var dapifuform = $('#dapqacomment_form_'+ifu);
		dapifuform.trigger('reset');
		$('.qacomment').html('');
		var key = 'maps';
		var ready = $('#inspectready').val();

		if (ready == 'True') {
			setDefault(key);
		} else {
			var fxn = 'loadDapQaPanel';
			$('#fxn').val(fxn);
			$('#dapqapane_'+ifu).hide();
			$('#loginform').modal('show');
		}
	});
});

// store old values
function storeold(key,mapid,qatype) {
	$('#oldmapid').val(mapid);
	$('#oldqatype').val(qatype);
	$('#oldkey').val(key);
}

// set category default
function setDefault(key) {
	//var html = (key!='radgrad') ? 'cube-none2': 'rss-rad1';
	var html = (key == 'maps') ? 'cube-none2' : (key =='spectra') ? 'cube-all5' : 'rss-rad1';
	var mapid = (key=='maps') ? 'kin' : (key=='radgrad') ? 'emflux': 'spec0';
	$('#qacomment_'+key).html(html);

	// display list and panels, store old values
	displayList(key);
	if (key=='spectra') getSpectraList(key,mapid,html);
	getPanel(key,mapid,html);
	storeold(key,mapid,html)
}

// toggle DAP QA cube/rss
$(function() {
	$('.dropdown-menu.qalist').on('click','li a', function() {
		var id = $(this).attr('id');
		var parentid = $(this).parent().parent().attr('id');
		var type = parentid.split('typelist')[0];
		var key = parentid.split('_')[1];

		// build html reference
		var html = $('#qacomment_'+key).html();
		html = type+'-'+id;
		$('#qacomment_'+key).html(html);

		//display the appropriate list
		displayList(key);

		// get map id
		var mapid = $('#catlist_'+key+' select option:selected').attr('id');

		//for spectra, populate list for first time
		if (key=='spectra') getSpectraList(key,mapid,html);

		//get new panel and store old values
		getPanel(key,mapid,html);
		storeold(key,mapid,html);

	});
});

// Display the appropriate list and reset selection
function displayList(key) {
	$('.catlist').hide();
	$('#catlist_'+key).show();
	$('#catlist_'+key+' select').children().removeProp('selected');

	//set first option as default
	var first = $('#catlist_'+key+' select :first-child');
	first.prop('selected',true);
}

// toggle DAP map selection
$(function() {
	$('.daptoggle').change(function() {
		var id = $(this).attr('id');
		var key = (id.search('map') != -1) ? 'maps' : (id.search('spectra') != -1) ? 'spectra' : (id.search('radgrad') != -1) ? 'radgrad' : ''
		var mapid = $('#'+id+' option:selected').attr('id');
		var qatype = $('#qacomment_'+key).html();

		// get old values
		var oldmapid = $('#oldmapid').val();
		var oldqatype = $('#oldqatype').val();
		var oldkey = $('#oldkey').val();
		console.log('map select id,key,mapid',id,key,mapid,oldmapid,oldqatype,oldkey);

		// get new panel and store old values
		getPanel(key,mapid,qatype);
		storeold(key,mapid,qatype);
	});
});

// build the DAP form
function buildDAPform(newdata=null,ifu=null) {
	var dapform = $('#dapqacomment_form_'+ifu).serializeArray();
	if (newdata) {
		$.each(newdata,function(i,val) {
			dapform.push(val);
		});
	}
	return dapform
}

// parse DAP issues
function parseDAPissues(key=null) {
	var name = (key) ? 'select[id*="dapqa_issue_'+key+'"]' : '.dapqaissuesp';
	var issuelist = getSelected(name);
	return issuelist;
}

// get a DAP panel
function getPanel(key, mapid, qatype) {
	// key = category key
	// qatype = category options from dropdowns
	// mapid = id of option from list selection

	$('.dapqapanel').hide();
	var ifu = $('#ifu').val();
	console.log('ifu field',$('#ifu'));
	var ifuname = $('#ifuname').val();

	// build form data
	issues = parseDAPissues(key);
	newdata = [{'name':'key','value':key},{'name':'mapid','value':mapid},{'name':'cubepk','value':$('#cubepk').val()},
			   {'name':'qatype','value':qatype},{'name':'issues','value':JSON.stringify(issues)}];
	dapformdata = buildDAPform(newdata=newdata,ifu=ifu)
	console.log('dapform',dapformdata);

	$.post($SCRIPT_ROOT + '/marvin/getdappanel', dapformdata,null,'json')
		.done(function(data){
			console.log('ifu',ifu,ifuname);
			var ifupanel = $('#dapqapane_'+ifu).find('#dapqa_'+key);
			console.log(ifupanel);
			ifupanel.show();
			var title = $('#dapqa_'+key+' h4');
			if (data.result['title']) title.html(data.result['title']);

			// setsession status failure
			if (data.result['setsession'] && data.result['setsession']['status'] == 0) {
				var alerthtml = "

"+data.result['setsession']['message']+"

";
				title.html(alerthtml);
			}

			loadImages(key,data.result['images'],data.result['panelmsg']);
			loadComments(key,data.result['getsession']);

		})
		.fail(function(data){
			$('#dapqa_'+key).show();
			var title = $('#dapqa_'+key+' h4');
			var alerthtml = "

Server Error: Failed to retrieve data!

";
			title.html(alerthtml);
		});

}

// get list of DAP spectrum plots available
function getSpectraList(key,mapid,qatype) {

	newdata = [{'name':'key','value':key},{'name':'mapid','value':mapid},{'name':'qatype','value':qatype}];
	dapformdata = buildDAPform(newdata=newdata)

	$.post($SCRIPT_ROOT + '/marvin/getdapspeclist', dapformdata,null,'json')
		.done(function(data){

			var speclist = data.result['speclist'];
			$('#dapspectralist').empty();
			if (speclist) {
				$.each(speclist,function(i,name) {

					var specname = name.split('-')[0];
					var specnum = name.split('-')[1];
					specnum = specnum.replace(/^0+/, '');
					if (specnum.length == 0) specnum='0';
					var id = specname+specnum

					$('#dapspectralist').append($('<option>', {
						id: id,
						value: id,
						text : name,
						selected : (i==0) ? true : false
					}));
				});
			}
		})
		.fail(function(data){
			$('#dapqa_'+key).show();
			var title = $('#dapqa_'+key+' h4');
			var alerthtml = "

Server Error: Failed to retrieve list of spectra!

";
			title.html(alerthtml);
		});
}

// load DAP plot images
function loadImages(key,images, msg) {
	$('#dapqa_'+key+' img').removeProp('src');
	//console.log($('#dapqa_'+key+' img'));
	if (images) {
		$('#dapqa_'+key+' img').each(function(index) {
			//console.log($(this),index,images.length);
			$(this).attr('src',images[index]);
			//$(this).magnify();
		});
	} else {
		var title = $('#dapqa_'+key+' h4');
		var alerthtml = "

"+msg+"

";
		title.html(alerthtml);
	}
}

// reset and load all the issues and comments
function loadComments(key,results) {
	// reset all issues

	// reset all panel comments
    $('[id^=dapqa_comment]').val('');

	console.log('loadComments results', results);

	if (results['status'] == 1) {

        // load new comments
        console.log("Loading results for key="+key+"..."); //delete this print (just for debug)

        if (results['dapqacomments']) {
			$.each(results['dapqacomments'],function(i,panelcomment) {

				console.log('panelcomment',panelcomment);
				$('#dapqa_comment'+panelcomment.catid+'_'+panelcomment.position).val(panelcomment.comment);

				$.each(panelcomment.issues, function(i,issid) {
					//dapqa_issue_{{category.key}}{{"_"+mapnum if mapnum else ""}}
					//issue_{{issid}}{{"_"+mapnum if mapnum else ""}}
					console.log('issue id,index',issid,i);
					$('#issue_'+issid+'_'+panelcomment.position).prop('selected',true);
				});
			});
        }

	} else {
		// getsession status failure
		var title = $('#dapqa_'+key+' h4');
		var alerthtml = "

"+results['message']+"

";
		title.html(alerthtml);
	}

}

// Map magnify toggle
$(function(){
	$('#magtoggle').on('click',function(){
		if ($(this).hasClass('active')){
			//$('.dapqapanel img').parent().removeClass('.magnify');
		} else {
			$('.dapqapanel img').magnify();
		}
	});
});

// Load the DAP image modal
function daploadmodal(img) {
	var src = img.src;
	var name = src.slice(src.search('manga-'));
	$('#dapimgtitle').html(name);
	var image = '';
	$('#dapimgbody').html(image);
}

// Submit DAP QA Comments
function dapaddcomments(ifu) {
	var dapform = $('#dapqacomment_form_'+ifu);
	console.log(dapform.serialize());
}

// Load the DAP QA Panel
function loadDapQaPanel() {
	var key = 'maps';
	var ifu = getIFUHash().slice(1);
	$('#dapqapane_'+ifu).show();
	resetLogin();
	setDefault(key);
}

<commit_msg>dapqa comments<commit_after>// Javascript code for Marvin DAP QA plots/comments on individual plates

// toggle DAP categories
$(function() {
	$('#dapqacat_select').change(function() {
		var key = $(this).val();
		// show category options
		$('.dapqacatoptions').hide();
		$('#dapqacatoptions_'+key).show();
		// show option reminder
		$('.qacomment').html('');
		// set default selection
		setDefault(key);
	});
});

// reset dapqa form on page load
/*$(function() {
	$('.dapqacomment_form').trigger('reset');
	$('.qacomment').html('');
	// load a default
	var key = 'maps';
	setDefault(key);

	var dapqa = new Dapqa('7443','9101','10');
	if (typeof dapqa != 'undefined') {
	console.log('dapqa',dapqa);
	dapqa.print();
	console.log('mainpane',dapqa.mainpane);
	console.log('qaform',dapqa.qaform.find('#dapqacat'));
	}
});*/

// dapqa tab selection
$(function(){
	$('#cubetabs a[href*="dapqapane"]').click(function() {
		var ifu = getIFUHash().slice(1);
		var dapifuform = $('#dapqacomment_form_'+ifu);
		dapifuform.trigger('reset');
		$('.qacomment').html('');
		var key = 'maps';
		var ready = $('#inspectready').val();

		if (ready == 'True') {
			setDefault(key);
		} else {
			var fxn = 'loadDapQaPanel';
			$('#fxn').val(fxn);
			$('#dapqapane_'+ifu).hide();
			$('#loginform').modal('show');
		}
	});
});

// store old values
function storeold(key,mapid,qatype) {
	$('#oldmapid').val(mapid);
	$('#oldqatype').val(qatype);
	$('#oldkey').val(key);
}

// set category default
function setDefault(key) {
	//var html = (key!='radgrad') ? 'cube-none2': 'rss-rad1';
	var html = (key == 'maps') ? 'cube-none2' : (key =='spectra') ? 'cube-all5' : 'rss-rad1';
	var mapid = (key=='maps') ? 'kin' : (key=='radgrad') ? 'emflux': 'spec0';
	$('#qacomment_'+key).html(html);

	// display list and panels, store old values
	displayList(key);
	if (key=='spectra') getSpectraList(key,mapid,html);
	getPanel(key,mapid,html);
	storeold(key,mapid,html)
}

// toggle DAP QA cube/rss
$(function() {
	$('.dropdown-menu.qalist').on('click','li a', function() {
		var id = $(this).attr('id');
		var parentid = $(this).parent().parent().attr('id');
		var type = parentid.split('typelist')[0];
		var key = parentid.split('_')[1];

		// build html reference
		var html = $('#qacomment_'+key).html();
		html = type+'-'+id;
		$('#qacomment_'+key).html(html);

		//display the appropriate list
		displayList(key);

		// get map id
		var mapid = $('#catlist_'+key+' select option:selected').attr('id');

		//for spectra, populate list for first time
		if (key=='spectra') getSpectraList(key,mapid,html);

		//get new panel and store old values
		getPanel(key,mapid,html);
		storeold(key,mapid,html);

	});
});

// Display the appropriate list and reset selection
function displayList(key) {
	$('.catlist').hide();
	$('#catlist_'+key).show();
	$('#catlist_'+key+' select').children().removeProp('selected');

	//set first option as default
	var first = $('#catlist_'+key+' select :first-child');
	first.prop('selected',true);
}

// toggle DAP map selection
$(function() {
	$('.daptoggle').change(function() {
		var id = $(this).attr('id');
		var key = (id.search('map') != -1) ? 'maps' : (id.search('spectra') != -1) ? 'spectra' : (id.search('radgrad') != -1) ? 'radgrad' : ''
		var mapid = $('#'+id+' option:selected').attr('id');
		var qatype = $('#qacomment_'+key).html();

		// get old values
		var oldmapid = $('#oldmapid').val();
		var oldqatype = $('#oldqatype').val();
		var oldkey = $('#oldkey').val();
		console.log('map select id,key,mapid',id,key,mapid,oldmapid,oldqatype,oldkey);

		// get new panel and store old values
		getPanel(key,mapid,qatype);
		storeold(key,mapid,qatype);
	});
});

// build the DAP form
function buildDAPform(newdata=null,ifu=null) {
	var dapform = $('#dapqacomment_form_'+ifu).serializeArray();
	if (newdata) {
		$.each(newdata,function(i,val) {
			dapform.push(val);
		});
	}
	return dapform
}

// parse DAP issues
function parseDAPissues(key=null) {
	var name = (key) ? 'select[id*="dapqa_issue_'+key+'"]' : '.dapqaissuesp';
	var issuelist = getSelected(name);
	return issuelist;
}

// get a DAP panel
function getPanel(key, mapid, qatype) {
	// key = category key
	// qatype = category options from dropdowns
	// mapid = id of option from list selection

	$('.dapqapanel').hide();
	var ifu = $('#ifu').val();
	console.log('ifu field',$('#ifu'));
	var ifuname = $('#ifuname').val();

	// build form data
	issues = parseDAPissues(key);
	newdata = [{'name':'key','value':key},{'name':'mapid','value':mapid},{'name':'cubepk','value':$('#cubepk').val()},
			   {'name':'qatype','value':qatype},{'name':'issues','value':JSON.stringify(issues)}];
	dapformdata = buildDAPform(newdata=newdata,ifu=ifu)
	console.log('dapform',dapformdata);

	$.post($SCRIPT_ROOT + '/marvin/getdappanel', dapformdata,null,'json')
		.done(function(data){
			console.log('ifu',ifu,ifuname);
			var ifupanel = $('#dapqapane_'+ifu).find('#dapqa_'+key);
			console.log(ifupanel);
			ifupanel.show();
			var title = $('#dapqa_'+key+' h4');
			if (data.result['title']) title.html(data.result['title']);

			// setsession status failure
			if (data.result['setsession'] && data.result['setsession']['status'] == 0) {
				var alerthtml = "

"+data.result['setsession']['message']+"

";
				title.html(alerthtml);
			}

			loadImages(key,data.result['images'],data.result['panelmsg']);
			loadComments(key,data.result['getsession']);

		})
		.fail(function(data){
			$('#dapqa_'+key).show();
			var title = $('#dapqa_'+key+' h4');
			var alerthtml = "

Server Error: Failed to retrieve data!

";
			title.html(alerthtml);
		});

}

// get list of DAP spectrum plots available
function getSpectraList(key,mapid,qatype) {

	newdata = [{'name':'key','value':key},{'name':'mapid','value':mapid},{'name':'qatype','value':qatype}];
	dapformdata = buildDAPform(newdata=newdata)

	$.post($SCRIPT_ROOT + '/marvin/getdapspeclist', dapformdata,null,'json')
		.done(function(data){

			var speclist = data.result['speclist'];
			$('#dapspectralist').empty();
			if (speclist) {
				$.each(speclist,function(i,name) {

					var specname = name.split('-')[0];
					var specnum = name.split('-')[1];
					specnum = specnum.replace(/^0+/, '');
					if (specnum.length == 0) specnum='0';
					var id = specname+specnum

					$('#dapspectralist').append($('<option>', {
						id: id,
						value: id,
						text : name,
						selected : (i==0) ? true : false
					}));
				});
			}
		})
		.fail(function(data){
			$('#dapqa_'+key).show();
			var title = $('#dapqa_'+key+' h4');
			var alerthtml = "

Server Error: Failed to retrieve list of spectra!

";
			title.html(alerthtml);
		});
}

// load DAP plot images
function loadImages(key,images, msg) {
	$('#dapqa_'+key+' img').removeProp('src');
	//console.log($('#dapqa_'+key+' img'));
	if (images) {
		$('#dapqa_'+key+' img').each(function(index) {
			//console.log($(this),index,images.length);
			$(this).attr('src',images[index]);
			//$(this).magnify();
		});
	} else {
		var title = $('#dapqa_'+key+' h4');
		var alerthtml = "

"+msg+"

";
		title.html(alerthtml);
	}
}

// reset and load all the issues and comments
function loadComments(key,results) {
	// reset all issues

	// reset all panel comments
    $('[id^=dapqa_comment]').val('');

	// reset all issue options
    $('[id^=dapqa_issue]').selectpicker('deselectAll');

	console.log('loadComments results', results);

	if (results['status'] == 1) {

        // load new comments
        console.log("Loading results for key="+key+"..."); //delete this print (just for debug)

        if (results['dapqacomments']) {
			$.each(results['dapqacomments'],function(i,panelcomment) {

				console.log('panelcomment',panelcomment);
				$('#dapqa_comment'+panelcomment.catid+'_'+panelcomment.position).val(panelcomment.comment);

				$.each(panelcomment.issues, function(i,issid) {
					//dapqa_issue_{{category.key}}{{"_"+mapnum if mapnum else ""}}
					//issue_{{issid}}{{"_"+mapnum if mapnum else ""}}
					console.log('issue id,index',issid,i);
					$('#issue_'+issid+'_'+panelcomment.position).prop('selected',true);
				});
			});
        }

	} else {
		// getsession status failure
		var title = $('#dapqa_'+key+' h4');
		var alerthtml = "

"+results['message']+"

";
		title.html(alerthtml);
	}

	// render the issue multiple selector to update the count
    $('[id^=dapqa_issue]').selectpicker('render');

}

// Map magnify toggle
$(function(){
	$('#magtoggle').on('click',function(){
		if ($(this).hasClass('active')){
			//$('.dapqapanel img').parent().removeClass('.magnify');
		} else {
			$('.dapqapanel img').magnify();
		}
	});
});

// Load the DAP image modal
function daploadmodal(img) {
	var src = img.src;
	var name = src.slice(src.search('manga-'));
	$('#dapimgtitle').html(name);
	var image = '';
	$('#dapimgbody').html(image);
}

// Submit DAP QA Comments
function dapaddcomments(ifu) {
	var dapform = $('#dapqacomment_form_'+ifu);
	console.log(dapform.serialize());
}

// Load the DAP QA Panel
function loadDapQaPanel() {
	var key = 'maps';
	var ifu = getIFUHash().slice(1);
	$('#dapqapane_'+ifu).show();
	resetLogin();
	setDefault(key);
}

<|endoftext|>


<commit_before>/*global ROT, TextBuffer, Player, Level, Being, XY*/
var Game = function () {
  "use strict";
  this.display = null;
  this.text = null;
  this.level = null;
  this.scheduler = null;
  this.engine = null;
  this.WIDTH = 45;
  this.HEIGHT = 20;
  this.TEXT_HEIGHT = 3;
};

Game.prototype.init = function () {
  "use strict";
  window.addEventListener("load", this);
};

Game.prototype.handleEvent = function (e) {
  "use strict";
  var i;
  switch (e.type) {
  case "load":
    window.removeEventListener("load", this);
    this.display = new ROT.Display({
      width: this.WIDTH,
      height: this.HEIGHT + this.TEXT_HEIGHT,
      fontFamily: "Arial"
    });
    document.body.appendChild(this.display.getContainer());
    this.display.setOptions({
      fontSize: this.display.computeFontSize(
        screen.availWidth,
        screen.availHeight
      )
    });
    this.text = new TextBuffer(this.display, this.HEIGHT, this.TEXT_HEIGHT);
    this.scheduler = new ROT.Scheduler.Speed();
    this.engine = new ROT.Engine(this.scheduler);
    this.level = new Level(this.WIDTH, this.HEIGHT);
    this.level.setEntity(new Player("⇑⇗⇒⇘⇓⇙⇐⇖"));
    for (i = 0; i < 10; i += 1) {
      this.level.setEntity(new Being("⇧⬀⇨⬂⇩⬃⇦⬁"));
    }
    for (i in this.level.beings) {
      if (this.level.beings.hasOwnProperty(i)) {
        this.scheduler.add(this.level.beings[i], true);
      }
    }
    this.engine.start();
    break;
  }
};

Game.prototype.over = function () {
  "use strict";
  this.engine.lock();
  /* FIXME show something */
};

var GAME = new Game();
GAME.init();
<commit_msg>JSDoc annotations added<commit_after>/*global ROT, TextBuffer, Level, Player, Being*/

/**
 * @fileoverview The primary file of the game. Contains the Game object and its
 * initialization, and calls all the other objects from their own files.
 */

/**
 * The main class of the game. Holds the objects of its graphical display, its
 * text window under it, its level data, its scheduler and engine. To start the
 * game, the init function has to be called.
 * @constructor
 */
var Game = function () {
  "use strict";
  this.display = null;
  this.text = null;
  this.level = null;
  this.scheduler = null;
  this.engine = null;
  this.WIDTH = 45;
  this.HEIGHT = 20;
  this.TEXT_HEIGHT = 3;
};

Game.prototype.init = function () {
  "use strict";
  window.addEventListener("load", this);
};

Game.prototype.handleEvent = function (e) {
  "use strict";
  var i;
  switch (e.type) {
  case "load":
    window.removeEventListener("load", this);
    this.display = new ROT.Display({
      width: this.WIDTH,
      height: this.HEIGHT + this.TEXT_HEIGHT,
      fontFamily: "Arial"
    });
    document.body.appendChild(this.display.getContainer());
    this.display.setOptions({
      fontSize: this.display.computeFontSize(
        screen.availWidth,
        screen.availHeight
      )
    });
    this.text = new TextBuffer(this.display, this.HEIGHT, this.TEXT_HEIGHT);
    this.scheduler = new ROT.Scheduler.Speed();
    this.engine = new ROT.Engine(this.scheduler);
    this.level = new Level(this.WIDTH, this.HEIGHT);
    this.level.setEntity(new Player("⇑⇗⇒⇘⇓⇙⇐⇖"));
    for (i = 0; i < 10; i += 1) {
      this.level.setEntity(new Being("⇧⬀⇨⬂⇩⬃⇦⬁"));
    }
    for (i in this.level.beings) {
      if (this.level.beings.hasOwnProperty(i)) {
        this.scheduler.add(this.level.beings[i], true);
      }
    }
    this.engine.start();
    break;
  }
};

Game.prototype.over = function () {
  "use strict";
  this.engine.lock();
  /* FIXME show something */
};

var GAME = new Game();
GAME.init();
<|endoftext|>


<commit_before>// Javascript code for Marvin DAP QA plots/comments on individual plates

// toggle DAP categories
$(function() {
	$('#dapqacat_select').change(function() {
		var key = $(this).val();
		// show category options
		$('.dapqacatoptions').hide();
		$('#dapqacatoptions_'+key).show();
		// show option reminder
		$('.qacomment').html('');
		// set default selection
		setDefault(key);
	});
});

// reset dapqa form on page load
/*$(function() {
	$('.dapqacomment_form').trigger('reset');
	$('.qacomment').html('');
	// load a default
	var key = 'maps';
	setDefault(key);

	var dapqa = new Dapqa('7443','9101','10');
	if (typeof dapqa != 'undefined') {
	console.log('dapqa',dapqa);
	dapqa.print();
	console.log('mainpane',dapqa.mainpane);
	console.log('qaform',dapqa.qaform.find('#dapqacat'));
	}
});*/

// dapqa tab selection
$(function(){
	$('#cubetabs a').click(function() {
		var ifu = getIFUHash().slice(1);
		var dapifuform = $('#dapqacomment_form_'+ifu);
		dapifuform.trigger('reset');
		$('.qacomment').html('');
		var key = 'maps';
		//var test = "{{platera|tojson|safe}}";
		//console.log('ready',test);
		setDefault(key);
	});
});

// store old values
function storeold(key,mapid,qatype) {
	$('#oldmapid').val(mapid);
	$('#oldqatype').val(qatype);
	$('#oldkey').val(key);
}

// set category default
function setDefault(key) {
	//var html = (key!='radgrad') ? 'cube-none2': 'rss-rad1';
	var html = (key == 'maps') ? 'cube-none2' : (key =='spectra') ? 'cube-all5' : 'rss-rad1';
	var mapid = (key=='maps') ? 'kin' : (key=='radgrad') ? 'emflux': 'spec0';
	$('#qacomment_'+key).html(html);

	// display list and panels, store old values
	displayList(key);
	if (key=='spectra') getSpectraList(key,mapid,html);
	getPanel(key,mapid,html);
	storeold(key,mapid,html)
}

// toggle DAP QA cube/rss
$(function() {
	$('.dropdown-menu.qalist').on('click','li a', function() {
		var id = $(this).attr('id');
		var parentid = $(this).parent().parent().attr('id');
		var type = parentid.split('typelist')[0];
		var key = parentid.split('_')[1];

		// build html reference
		var html = $('#qacomment_'+key).html();
		html = type+'-'+id;
		$('#qacomment_'+key).html(html);

		//display the appropriate list
		displayList(key);

		// get map id
		var mapid = $('#catlist_'+key+' select option:selected').attr('id');

		//for spectra, populate list for first time
		if (key=='spectra') getSpectraList(key,mapid,html);

		//get new panel and store old values
		getPanel(key,mapid,html);
		storeold(key,mapid,html);

	});
});

// Display the appropriate list and reset selection
function displayList(key) {
	$('.catlist').hide();
	$('#catlist_'+key).show();
	$('#catlist_'+key+' select').children().removeProp('selected');

	//set first option as default
	var first = $('#catlist_'+key+' select :first-child');
	first.prop('selected',true);
}

// toggle DAP map selection
$(function() {
	$('.daptoggle').change(function() {
		var id = $(this).attr('id');
		var key = (id.search('map') != -1) ? 'maps' : (id.search('spectra') != -1) ? 'spectra' : (id.search('radgrad') != -1) ? 'radgrad' : ''
		var mapid = $('#'+id+' option:selected').attr('id');
		var qatype = $('#qacomment_'+key).html();

		// get old values
		var oldmapid = $('#oldmapid').val();
		var oldqatype = $('#oldqatype').val();
		var oldkey = $('#oldkey').val();
		console.log('map select id,key,mapid',id,key,mapid,oldmapid,oldqatype,oldkey);

		// get new panel and store old values
		getPanel(key,mapid,qatype);
		storeold(key,mapid,qatype);
	});
});

// build the DAP form
function buildDAPform(newdata=null,ifu=null) {
	var dapform = $('#dapqacomment_form_'+ifu).serializeArray();
	if (newdata) {
		$.each(newdata,function(i,val) {
			dapform.push(val);
		});
	}
	return dapform
}

// parse DAP issues
function parseDAPissues(key=null) {
	var name = (key) ? 'select[id*="dapqa_issue_'+key+'"]' : '.dapqaissuesp';
	var issuelist = getSelected(name);
	return issuelist;
}

// get a DAP panel
function getPanel(key, mapid, qatype) {
	// key = category key
	// qatype = category options from dropdowns
	// mapid = id of option from list selection

	$('.dapqapanel').hide();
	var ifu = $('#ifu').val();
	console.log('ifu field',$('#ifu'));
	var ifuname = $('#ifuname').val();

	// build form data
	issues = parseDAPissues(key);
	newdata = [{'name':'key','value':key},{'name':'mapid','value':mapid},{'name':'cubepk','value':$('#cubepk').val()},
			   {'name':'qatype','value':qatype},{'name':'issues','value':JSON.stringify(issues)}];
	dapformdata = buildDAPform(newdata=newdata,ifu=ifu)
	console.log('dapform',dapformdata);

	$.post($SCRIPT_ROOT + '/marvin/getdappanel', dapformdata,null,'json')
		.done(function(data){
			console.log('ifu',ifu,ifuname);
			var ifupanel = $('#dapqapane_'+ifu).find('#dapqa_'+key);
			console.log(ifupanel);
			ifupanel.show();
			var title = $('#dapqa_'+key+' h4');
			if (data.result['title']) title.html(data.result['title']);

			// setsession status failure
			if (data.result['setsession'] && data.result['setsession']['status'] == 0) {
				var alerthtml = "

"+data.result['setsession']['message']+"

";
				title.html(alerthtml);
			}

			loadImages(key,data.result['images'],data.result['panelmsg']);
			loadComments(key,data.result['getsession']);

		})
		.fail(function(data){
			$('#dapqa_'+key).show();
			var title = $('#dapqa_'+key+' h4');
			var alerthtml = "

Server Error: Failed to retrieve data!

";
			title.html(alerthtml);
		});

}

// get list of DAP spectrum plots available
function getSpectraList(key,mapid,qatype) {

	newdata = [{'name':'key','value':key},{'name':'mapid','value':mapid},{'name':'qatype','value':qatype}];
	dapformdata = buildDAPform(newdata=newdata)

	$.post($SCRIPT_ROOT + '/marvin/getdapspeclist', dapformdata,null,'json')
		.done(function(data){

			var speclist = data.result['speclist'];
			$('#dapspectralist').empty();
			if (speclist) {
				$.each(speclist,function(i,name) {

					var specname = name.split('-')[0];
					var specnum = name.split('-')[1];
					specnum = specnum.replace(/^0+/, '');
					if (specnum.length == 0) specnum='0';
					var id = specname+specnum

					$('#dapspectralist').append($('<option>', {
						id: id,
						value: id,
						text : name,
						selected : (i==0) ? true : false
					}));
				});
			}
		})
		.fail(function(data){
			$('#dapqa_'+key).show();
			var title = $('#dapqa_'+key+' h4');
			var alerthtml = "

Server Error: Failed to retrieve list of spectra!

";
			title.html(alerthtml);
		});
}

// load DAP plot images
function loadImages(key,images, msg) {
	$('#dapqa_'+key+' img').removeProp('src');
	//console.log($('#dapqa_'+key+' img'));
	if (images) {
		$('#dapqa_'+key+' img').each(function(index) {
			//console.log($(this),index,images.length);
			$(this).attr('src',images[index]);
			//$(this).magnify();
		});
	} else {
		var title = $('#dapqa_'+key+' h4');
		var alerthtml = "

"+msg+"

";
		title.html(alerthtml);
	}
}

// reset and load all the issues and comments
function loadComments(key,results) {
	// reset all issues

	if (results['status'] == 1) {

        // load new comments
        console.log("Loading results for key="+key+"...") //delete this print (just for debug)
        for panelcomment in results['dapqacomments'] {

            //replace this print with actual javascript to replace the panel comments with panelcomment in this loop over results
            //print "Brian, please loadcomment for panelname="+panelcomment['panel']+", panelnumber="+panelcomment['position']+", comment="+panelcomment['comment']+", issueids="+panelcomment['issues']+"!"

            console.log('panelcomment',panelcomment);
            $('#dapqa_comment'+panelcomment.catid+'_'+panelcomment.position).val(panelcomment.comment);
        }

	} else {
		// getsession status failure
		var title = $('#dapqa_'+key+' h4');
		var alerthtml = "

"+results['message']+"

";
		title.html(alerthtml);
	}

}

// Map magnify toggle
$(function(){
	$('#magtoggle').on('click',function(){
		if ($(this).hasClass('active')){
			//$('.dapqapanel img').parent().removeClass('.magnify');
		} else {
			$('.dapqapanel img').magnify();
		}
	});
});

// Load the DAP image modal
function daploadmodal(img) {
	var src = img.src;
	var name = src.slice(src.search('manga-'));
	$('#dapimgtitle').html(name);
	var image = '';
	$('#dapimgbody').html(image);
}

// Submit DAP QA Comments
function dapaddcomments(ifu) {
	var dapform = $('#dapqacomment_form_'+ifu);
	console.log(dapform.serialize());
}

<commit_msg>test comment dapqa load<commit_after>// Javascript code for Marvin DAP QA plots/comments on individual plates

// toggle DAP categories
$(function() {
	$('#dapqacat_select').change(function() {
		var key = $(this).val();
		// show category options
		$('.dapqacatoptions').hide();
		$('#dapqacatoptions_'+key).show();
		// show option reminder
		$('.qacomment').html('');
		// set default selection
		setDefault(key);
	});
});

// reset dapqa form on page load
/*$(function() {
	$('.dapqacomment_form').trigger('reset');
	$('.qacomment').html('');
	// load a default
	var key = 'maps';
	setDefault(key);

	var dapqa = new Dapqa('7443','9101','10');
	if (typeof dapqa != 'undefined') {
	console.log('dapqa',dapqa);
	dapqa.print();
	console.log('mainpane',dapqa.mainpane);
	console.log('qaform',dapqa.qaform.find('#dapqacat'));
	}
});*/

// dapqa tab selection
$(function(){
	$('#cubetabs a').click(function() {
		var ifu = getIFUHash().slice(1);
		var dapifuform = $('#dapqacomment_form_'+ifu);
		dapifuform.trigger('reset');
		$('.qacomment').html('');
		var key = 'maps';
		//var test = "{{platera|tojson|safe}}";
		//console.log('ready',test);
		setDefault(key);
	});
});

// store old values
function storeold(key,mapid,qatype) {
	$('#oldmapid').val(mapid);
	$('#oldqatype').val(qatype);
	$('#oldkey').val(key);
}

// set category default
function setDefault(key) {
	//var html = (key!='radgrad') ? 'cube-none2': 'rss-rad1';
	var html = (key == 'maps') ? 'cube-none2' : (key =='spectra') ? 'cube-all5' : 'rss-rad1';
	var mapid = (key=='maps') ? 'kin' : (key=='radgrad') ? 'emflux': 'spec0';
	$('#qacomment_'+key).html(html);

	// display list and panels, store old values
	displayList(key);
	if (key=='spectra') getSpectraList(key,mapid,html);
	getPanel(key,mapid,html);
	storeold(key,mapid,html)
}

// toggle DAP QA cube/rss
$(function() {
	$('.dropdown-menu.qalist').on('click','li a', function() {
		var id = $(this).attr('id');
		var parentid = $(this).parent().parent().attr('id');
		var type = parentid.split('typelist')[0];
		var key = parentid.split('_')[1];

		// build html reference
		var html = $('#qacomment_'+key).html();
		html = type+'-'+id;
		$('#qacomment_'+key).html(html);

		//display the appropriate list
		displayList(key);

		// get map id
		var mapid = $('#catlist_'+key+' select option:selected').attr('id');

		//for spectra, populate list for first time
		if (key=='spectra') getSpectraList(key,mapid,html);

		//get new panel and store old values
		getPanel(key,mapid,html);
		storeold(key,mapid,html);

	});
});

// Display the appropriate list and reset selection
function displayList(key) {
	$('.catlist').hide();
	$('#catlist_'+key).show();
	$('#catlist_'+key+' select').children().removeProp('selected');

	//set first option as default
	var first = $('#catlist_'+key+' select :first-child');
	first.prop('selected',true);
}

// toggle DAP map selection
$(function() {
	$('.daptoggle').change(function() {
		var id = $(this).attr('id');
		var key = (id.search('map') != -1) ? 'maps' : (id.search('spectra') != -1) ? 'spectra' : (id.search('radgrad') != -1) ? 'radgrad' : ''
		var mapid = $('#'+id+' option:selected').attr('id');
		var qatype = $('#qacomment_'+key).html();

		// get old values
		var oldmapid = $('#oldmapid').val();
		var oldqatype = $('#oldqatype').val();
		var oldkey = $('#oldkey').val();
		console.log('map select id,key,mapid',id,key,mapid,oldmapid,oldqatype,oldkey);

		// get new panel and store old values
		getPanel(key,mapid,qatype);
		storeold(key,mapid,qatype);
	});
});

// build the DAP form
function buildDAPform(newdata=null,ifu=null) {
	var dapform = $('#dapqacomment_form_'+ifu).serializeArray();
	if (newdata) {
		$.each(newdata,function(i,val) {
			dapform.push(val);
		});
	}
	return dapform
}

// parse DAP issues
function parseDAPissues(key=null) {
	var name = (key) ? 'select[id*="dapqa_issue_'+key+'"]' : '.dapqaissuesp';
	var issuelist = getSelected(name);
	return issuelist;
}

// get a DAP panel
function getPanel(key, mapid, qatype) {
	// key = category key
	// qatype = category options from dropdowns
	// mapid = id of option from list selection

	$('.dapqapanel').hide();
	var ifu = $('#ifu').val();
	console.log('ifu field',$('#ifu'));
	var ifuname = $('#ifuname').val();

	// build form data
	issues = parseDAPissues(key);
	newdata = [{'name':'key','value':key},{'name':'mapid','value':mapid},{'name':'cubepk','value':$('#cubepk').val()},
			   {'name':'qatype','value':qatype},{'name':'issues','value':JSON.stringify(issues)}];
	dapformdata = buildDAPform(newdata=newdata,ifu=ifu)
	console.log('dapform',dapformdata);

	$.post($SCRIPT_ROOT + '/marvin/getdappanel', dapformdata,null,'json')
		.done(function(data){
			console.log('ifu',ifu,ifuname);
			var ifupanel = $('#dapqapane_'+ifu).find('#dapqa_'+key);
			console.log(ifupanel);
			ifupanel.show();
			var title = $('#dapqa_'+key+' h4');
			if (data.result['title']) title.html(data.result['title']);

			// setsession status failure
			if (data.result['setsession'] && data.result['setsession']['status'] == 0) {
				var alerthtml = "

"+data.result['setsession']['message']+"

";
				title.html(alerthtml);
			}

			loadImages(key,data.result['images'],data.result['panelmsg']);
			loadComments(key,data.result['getsession']);

		})
		.fail(function(data){
			$('#dapqa_'+key).show();
			var title = $('#dapqa_'+key+' h4');
			var alerthtml = "

Server Error: Failed to retrieve data!

";
			title.html(alerthtml);
		});

}

// get list of DAP spectrum plots available
function getSpectraList(key,mapid,qatype) {

	newdata = [{'name':'key','value':key},{'name':'mapid','value':mapid},{'name':'qatype','value':qatype}];
	dapformdata = buildDAPform(newdata=newdata)

	$.post($SCRIPT_ROOT + '/marvin/getdapspeclist', dapformdata,null,'json')
		.done(function(data){

			var speclist = data.result['speclist'];
			$('#dapspectralist').empty();
			if (speclist) {
				$.each(speclist,function(i,name) {

					var specname = name.split('-')[0];
					var specnum = name.split('-')[1];
					specnum = specnum.replace(/^0+/, '');
					if (specnum.length == 0) specnum='0';
					var id = specname+specnum

					$('#dapspectralist').append($('<option>', {
						id: id,
						value: id,
						text : name,
						selected : (i==0) ? true : false
					}));
				});
			}
		})
		.fail(function(data){
			$('#dapqa_'+key).show();
			var title = $('#dapqa_'+key+' h4');
			var alerthtml = "

Server Error: Failed to retrieve list of spectra!

";
			title.html(alerthtml);
		});
}

// load DAP plot images
function loadImages(key,images, msg) {
	$('#dapqa_'+key+' img').removeProp('src');
	//console.log($('#dapqa_'+key+' img'));
	if (images) {
		$('#dapqa_'+key+' img').each(function(index) {
			//console.log($(this),index,images.length);
			$(this).attr('src',images[index]);
			//$(this).magnify();
		});
	} else {
		var title = $('#dapqa_'+key+' h4');
		var alerthtml = "

"+msg+"

";
		title.html(alerthtml);
	}
}

// reset and load all the issues and comments
function loadComments(key,results) {
	// reset all issues

	console.log('loadComments results', results);

	if (results['status'] == 1) {

        // load new comments
        console.log("Loading results for key="+key+"..."); //delete this print (just for debug)
        for panelcomment in results['dapqacomments'] {

            //replace this print with actual javascript to replace the panel comments with panelcomment in this loop over results
            //print "Brian, please loadcomment for panelname="+panelcomment['panel']+", panelnumber="+panelcomment['position']+", comment="+panelcomment['comment']+", issueids="+panelcomment['issues']+"!"

            console.log('panelcomment',panelcomment);
            $('#dapqa_comment'+panelcomment.catid+'_'+panelcomment.position).val(panelcomment.comment);
        }

	} else {
		// getsession status failure
		var title = $('#dapqa_'+key+' h4');
		var alerthtml = "

"+results['message']+"

";
		title.html(alerthtml);
	}

}

// Map magnify toggle
$(function(){
	$('#magtoggle').on('click',function(){
		if ($(this).hasClass('active')){
			//$('.dapqapanel img').parent().removeClass('.magnify');
		} else {
			$('.dapqapanel img').magnify();
		}
	});
});

// Load the DAP image modal
function daploadmodal(img) {
	var src = img.src;
	var name = src.slice(src.search('manga-'));
	$('#dapimgtitle').html(name);
	var image = '';
	$('#dapimgbody').html(image);
}

// Submit DAP QA Comments
function dapaddcomments(ifu) {
	var dapform = $('#dapqacomment_form_'+ifu);
	console.log(dapform.serialize());
}

<|endoftext|>


<commit_before>var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var game = {
  createCanvas : function(){
    // 创建界面
    this.c = document.createElement('canvas');
    this.ctx = this.c.getContext('2d');
    this.c.id = 'canvas';
    this.c.width = WIDTH;
    this.c.height = HEIGHT;
    document.body.appendChild(this.c);
  },
  init : function(){
    this.createCanvas();
    this.gravity = true;
    this.jumpFrame = 0;
    map.init(WIDTH,HEIGHT);
    this.drawAll();

    this.start();
  },
  start : function(){
    // animationFrame = window.requestAnimationFrame(game.animate,game.c);
    animationFrame = setInterval(game.animate,30)
  },
  checkGravity : function(){
    if(this.gravity){
      var ph = player.y+player.h - map.grounds[0].y;
      if(ph < 0){
        this.movePlayerTo(player.x,player.y+10);
        if(ph >= -player.h/7){
          this.movePlayerTo(player.x,map.grounds[0].y-player.h);
          player.canControl = true;
        }
      }
    }
  },
  checkKeydown : function(event){
    player.isJumping = true;
    var e = event||window.event;
    switch(e.keyCode){
      case 65:
      case 37:player.left = true;break;
      case 87:
      case 38:player.top = true;break;
      case 68:
      case 39:player.right = true;break;
      case 83:
      case 40:player.bottom = true;break;
    }
    return false;
  },
  limitPlayer : function(){
    if(player.x<0){
      player.x = 0;
    }
    if(player.y<0){
      player.y = 0;
    }
    if(player.x+player.w > WIDTH){
      player.x = WIDTH - player.w;
    }
  },
  movePlayerTo : function(x,y){
    player.x = x;
    player.y = y;
  },
  createRect : function(x,y,w,h,color){
    this.ctx.fillStyle = color;
    this.ctx.fillRect(x,y,w,h);
  },
  animate : function(){
    game.ctx.clearRect(0,0,WIDTH,HEIGHT);
    game.checkGravity();
    if(player.canControl){
      if(!player.isJumping){
        document.onkeydown = game.checkKeydown;
      }else{
        document.onkeydown = null;
        game.playerJump();
        player.top = player.left = player.right = player.bottom = false;
      }

    }
    game.limitPlayer();
    game.drawAll();
  },
  playerJump:function(){
    if(player.isJumping){
      if(player.right){
        player.isJumping = 'right';
      } else if(player.left){
        player.isJumping = 'left';
      }
    }
    if(player.isJumping === 'right'){
      player.x += player.jumpHor/player.jumpFs;
      player.y -= player.jumpVer/(player.jumpFs/2);
      this.jumpFrame++;
      if(this.jumpFrame>player.jumpFs/2){
        player.y += player.jumpVer/(player.jumpFs/2);
      }
      if(this.jumpFrame>player.jumpFs){
        player.isJumping = false;
        this.jumpFrame = 0;
      }
    }
    if(player.isJumping === 'left'){
      player.x -= player.jumpHor/player.jumpFs;
      player.y -= player.jumpVer/(player.jumpFs/2);

      this.jumpFrame++;
      if(this.jumpFrame>player.jumpFs/2){
        player.y += player.jumpVer/(player.jumpFs/2);
      }
      if(this.jumpFrame>player.jumpFs){
        player.isJumping = false;
        this.jumpFrame = 0;
      }
    }
  },
  drawAll : function(){
    var i;
    for(i=0; i<map.grounds.length; i++){
      this.createRect(map.grounds[i].x,map.grounds[i].y,map.grounds[i].w,map.grounds[i].h,'green');
    }
    this.createRect(player.x,player.y,player.w,player.h,'lightblue');
  }

}
var map = {
  world : {},
  grounds : [],
  // player : [],
  init : function(w,h){
    this.world.width = w;
    this.world.height = h;
    this.grounds.push({x:0,y:Math.round(h-h/30),w:w,h:h/30});
  },
}
var player = {
  x:0,
  y:0,
  w:20,
  h:100,
  top:false,
  left:false,
  right:false,
  top:false,
  isJumping:false,
  canControl:false,
  jumpHor:120,// 跳跃的水平距离
  jumpVer:320,// 跳跃的垂直距离
  jumpFs:30,// 跳跃需要的帧数
}
window.onload = function(){
  game.init();
  // console.log('----------------\n有的时候\n觉得自己不断在努力\n但是事实上\n一直没走出那个枷锁\nBy Fakefish\n----------------');
}
<commit_msg>准备插入移动的矩形<commit_after>var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var game = {
  createCanvas : function(){
    // 创建界面
    this.c = document.createElement('canvas');
    this.ctx = this.c.getContext('2d');
    this.c.id = 'canvas';
    this.c.width = WIDTH;
    this.c.height = HEIGHT;
    document.body.appendChild(this.c);
  },
  init : function(){
    this.createCanvas();
    this.gravity = true;
    this.jumpFrame = 0;
    map.init(WIDTH,HEIGHT);
    this.drawAll();

    this.start();
  },
  start : function(){
    // animationFrame = window.requestAnimationFrame(game.animate,game.c);
    animationFrame = setInterval(game.animate,30)
  },
  checkGravity : function(){
    if(this.gravity){
      var ph = player.y+player.h - map.grounds[0].y;
      if(ph < 0){
        this.movePlayerTo(player.x,player.y+10);
        if(ph >= -player.h/7){
          this.movePlayerTo(player.x,map.grounds[0].y-player.h);
          player.canControl = true;
        }
      }
    }
  },
  checkKeydown : function(event){
    player.isJumping = true;
    var e = event||window.event;
    switch(e.keyCode){
      case 65:
      case 37:player.left = true;break;
      case 87:
      case 38:player.top = true;break;
      case 68:
      case 39:player.right = true;break;
      case 83:
      case 40:player.bottom = true;break;
    }
    return false;
  },
  limitPlayer : function(){
    if(player.x<0){
      player.x = 0;
    }
    if(player.y<0){
      player.y = 0;
    }
    if(player.x+player.w > WIDTH){
      player.x = WIDTH - player.w;
    }
  },
  movePlayerTo : function(x,y){
    player.x = x;
    player.y = y;
  },
  createRect : function(x,y,w,h,color){
    this.ctx.fillStyle = color;
    this.ctx.fillRect(x,y,w,h);
  },
  animate : function(){
    game.ctx.clearRect(0,0,WIDTH,HEIGHT);
    game.checkGravity();
    if(player.canControl){
      if(!player.isJumping){
        document.onkeydown = game.checkKeydown;
      }else{
        document.onkeydown = null;
        game.playerJump();
        player.top = player.left = player.right = player.bottom = false;
      }

    }
    game.limitPlayer();
    game.drawAll();
  },
  playerJump:function(){
    if(player.isJumping){
      if(player.right){
        player.isJumping = 'right';
      } else if(player.left){
        player.isJumping = 'left';
      }
    }
    if(player.isJumping === 'right'){
      player.x += player.jumpHor/player.jumpFs;
      player.y -= player.jumpVer/(player.jumpFs/2);
      this.jumpFrame++;
      if(this.jumpFrame>player.jumpFs/2){
        player.y += player.jumpVer/(player.jumpFs/2);
      }
      if(this.jumpFrame>player.jumpFs){
        player.isJumping = false;
        this.jumpFrame = 0;
      }
    }
    if(player.isJumping === 'left'){
      player.x -= player.jumpHor/player.jumpFs;
      player.y -= player.jumpVer/(player.jumpFs/2);

      this.jumpFrame++;
      if(this.jumpFrame>player.jumpFs/2){
        player.y += player.jumpVer/(player.jumpFs/2);
      }
      if(this.jumpFrame>player.jumpFs){
        player.isJumping = false;
        this.jumpFrame = 0;
      }
    }
  },
  drawAll : function(){
    var i;
    for(i=0; i<map.grounds.length; i++){
      this.createRect(map.grounds[i].x,map.grounds[i].y,map.grounds[i].w,map.grounds[i].h,'green');
    }
    this.createRect(player.x,player.y,player.w,player.h,player.background);
  }

}
var map = {
  world : {},
  grounds : [],
  // player : [],
  init : function(w,h){
    this.world.width = w;
    this.world.height = h;
    this.grounds.push({x:0,y:Math.round(h-h/30),w:w,h:h/30});
  },
}
var player = {
  x:0,
  y:0,
  w:20,
  h:100,
  background:'lightblue',
  top:false,
  left:false,
  right:false,
  top:false,
  isJumping:false,
  canControl:false,
  jumpHor:120,// 跳跃的水平距离
  jumpVer:315,// 跳跃的垂直距离
  jumpFs:30,// 跳跃需要的帧数
};
var enemy = {
  w:100,
  h:20,
  dir:right,
  init: function(x,y){

  }
};
window.onload = function(){
  game.init();
  // console.log('----------------\n有的时候\n觉得自己不断在努力\n但是事实上\n一直没走出那个枷锁\nBy Fakefish\n----------------');
}
<|endoftext|>


<commit_before>
var stage = new createjs.Stage("main_canvas");
var Hexes = [];

var p1 = null;
var p2 = null;
var p3 = null;
var p4 = null;

function Player(_x, _y) {
    this.x = _x;
    this.y = _y;
}

Player.prototype.getCurrentHex = function() {
    return Hexes[this.y][this.x];
}

function setAnimationInterval(interval) {

    createjs.Ticker.addEventListener('tick', function() {
        console.log("Tick");

        stage.update();
    });

    createjs.Ticker.setInterval(interval);
}

/* radius passed in is the radius of the hex polygon */
function drawGrid(radius) {

    var id = 0;
    var side_offset = 2;

    var y = side_offset;

    var h_rad = 0.5*radius;
    var hex_halfheight = Math.sqrt(radius*radius - h_rad*h_rad);

    while (y < (stage.canvas.height - 2*radius)) {

        var x = side_offset
        var idx = Hexes.push([]) - 1;

        //even rows are drawn inwards
        if (idx % 2 === 1) {
            x += 1.5*radius;
        }

        while (x < (stage.canvas.width - 2*radius)) {
            var hex = drawHex(x + radius, y + radius, radius, 1);
            hex.myprops.id = id;
            id++;
            Hexes[idx].push(hex);

            x += 3*radius;
        }

        y += hex_halfheight;
    }
}

function drawHex(x, y, radius, thickness) {

    var hex = new createjs.Shape();
    hex.graphics
        .setStrokeStyle(thickness)
        .beginStroke("#000")
        .drawPolyStar(0, 0, radius, 6, 0, 0);
    hex.x = x;
    hex.y = y;
    stage.addChild(hex);

    hex.myprops = {};
    hex.myprops.radius = radius;
    hex.myprops.thickness = thickness;

    return hex;
}

function changeHexColor(hex, color) {
    if (!(hex.myprops && hex.myprops.radius && hex.myprops.thickness)) {
        return;
    }
    var r = hex.myprops.radius;
    hex.graphics.clear()
       .beginFill(color)
       .drawPolyStar(0, 0, r, 6, 0, 0);

    return hex;
}

/* each player starts out at one corner of the board
 * and has a name so we know who they are. if there
 * are fewer than 4 players for a round, we just pass
 * in null for that player */
function placePlayers(a, b, c, d) {

    if (a) {
        p1 = new Player(0, 0);
        p1.name = a;
    }

    if (b) {
        p2 = new Player(0, Hexes.length-1);
        p2.name = b;
    }

    if (c) {
        p3 = new Player(Hexes[0].length-1, 0);
        p3.name = c;
    }

    if (d) {
        p4 = new Player(Hexes[Hexes.length-1].length-1, Hexes.length-1);
        p4.name = d;
    }
}

function init() {
    setAnimationInterval(100);
    drawGrid(15);
    placePlayers("Alpha", "Beta", "Gamma", "Delta");
}

init();
<commit_msg>Fixed grid coords and added player movement<commit_after>
var stage = new createjs.Stage("main_canvas");

var Hexes = [];

var p1 = null;
var p2 = null;
var p3 = null;
var p4 = null;

function Player(_x, _y) {
    this.x = _x;
    this.y = _y;

    this.name = "";
}

Player.prototype.getCurrentHex = function() {
    return Hexes[this.x][this.y];
}

/* direction is an integer from 0 to 5 where 0 is moving to the hex in an
 * upper-right direction, 1 is moving to the hex above the current one, and so
 * on
 *
 * If there is a hex available in that direction for the player to move onto
 * (regardless of whether there is a Trail or another player at that hex) this
 * returns true; otherwise it returns false.
 */
Player.prototype.move = function(direction) {

  var x_cur = this.x;
  var y_cur = this.y;

  var x_new;
  var y_new;

  var even_col = x_cur % 2 === 0;

  switch (direction) {
    case 0:
      x_new = x_cur + 1;
      y_new = even_col ? y_cur - 1 : y_cur;
      break;

    case 1:
      y_new = y_cur - 1;
      x_new = x_cur;
      break;

    case 2:
      x_new = x_cur - 1;
      y_new = even_col ? y_cur - 1: y_cur;
      break;

    case 3:
      x_new = x_cur - 1;
      y_new = even_col ? y_cur: y_cur + 1;
      break;

    case 4:
      y_new = y_cur + 1;
      x_new = x_cur;
      break;

    case 5:
      x_new = x_cur + 1;
      y_new = even_col ? y_cur : y_cur + 1;
      break;

    default:
      return false;
  }

  if (Hexes[x_new] && Hexes[x_new][y_new]) {
    this.x = x_new;
    this.y = y_new;
    return true;
  }

  return false;
}

function setAnimationInterval(interval) {

    createjs.Ticker.addEventListener('tick', function() {
        //console.log("Tick");

        stage.update();
    });

    createjs.Ticker.setInterval(interval);
}

/* radius passed in is the radius of the hex polygon */
function drawGrid(radius) {

    var id = 0;
    var side_offset = 2;

    var x = side_offset;

    var h_rad = 0.5*radius;
    var hex_halfheight = Math.sqrt(radius*radius - h_rad*h_rad);

    while (x < (stage.canvas.width - 2*radius)) {

      var y = side_offset;
      var idx = Hexes.push([]) - 1;

      if (idx % 2 !== 0) {
        y += hex_halfheight;
      }

      while (y < (stage.canvas.height - 2*radius)) {
        var hex = drawHex(x + radius, y + radius, radius, 1);
        hex.myprops.id = id;
        id++;
        Hexes[idx].push(hex);
        y += 2 * hex_halfheight;
      }
      x += 1.5*radius;
    }
}

function drawHex(x, y, radius, thickness) {

    var hex = new createjs.Shape();
    hex.graphics
        .setStrokeStyle(thickness)
        .beginStroke("#000")
        .drawPolyStar(0, 0, radius, 6, 0, 0);
    hex.x = x;
    hex.y = y;
    stage.addChild(hex);

    hex.myprops = {};
    hex.myprops.radius = radius;
    hex.myprops.thickness = thickness;

    return hex;
}

function changeHexColor(hex, color) {
    if (!(hex.myprops && hex.myprops.radius && hex.myprops.thickness)) {
        return;
    }
    var r = hex.myprops.radius;
    hex.graphics.clear()
       .beginFill(color)
       .drawPolyStar(0, 0, r, 6, 0, 0);

    return hex;
}

/* each player starts out at one corner of the board
 * and has a name so we know who they are. if there
 * are fewer than 4 players for a round, we just pass
 * in null for that player */
function placePlayers(a, b, c, d) {

    if (a) {
        p1 = new Player(0, 0);
        p1.name = a;
    }

    if (b) {
        p2 = new Player(Hexes.length-1, 0);
        p2.name = b;
    }

    if (c) {
        p3 = new Player(0, Hexes[0].length-1);
        p3.name = c;
    }

    if (d) {
        p4 = new Player(Hexes.length -1, Hexes[Hexes.length-1].length-1);
        p4.name = d;
    }
}

function init() {
    setAnimationInterval(100);
    drawGrid(15);
    placePlayers("Alpha", "Beta", "Gamma", "Delta");
}

init();
<|endoftext|>


<commit_before>/**
 * Created by shaibenvalid on 1/20/17.
 */

var gameOptions = {
    gameWidth: 960,    // game width, in pixels
    gameHeight: 600,   // game height, in pixels
    tileSize: 60,     // tile size, in pixels
    colors: [0xff0000, 0x00ff00, 0x0000ff, 0xffff00] // tile colors
}

var gameLevel = [
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0]
]

window.onload = function () {

    //  Note that this html file is set to pull down Phaser 2.5.0 from the JS Delivr CDN.
    //  Although it will work fine with this tutorial, it's almost certainly not the most current version.
    //  Be sure to replace it with an updated version before you start experimenting with adding your own code.

    var game = new Phaser.Game(960, 600, Phaser.AUTO, '', {preload: preload, create: create, update: update});

    function preload() {

        game.load.image('logo', 'phaser.png');

        game.load.image('mosque', 'assets/mosque.png');

        game.load.image('synagogue', 'assets/synagogue.png');

        game.load.image('church', 'assets/church.png');

        game.load.image('block', 'assets/blue_tile.png');
    }

    function update() {

    }

    function create() {

        drawBoard(gameLevel)

    }

    function drawBoard(board) {
        for (var i = 0; i < board.length; i++) {
            var row = board[i];
            for (var j = 0; j < row.length; j++) {
                var tileType = row[j];
                var x = j* gameOptions.tileSize;
                var y = i* gameOptions.tileSize;
                var assetName = 'block';
                if(tileType == 1){
                    assetName = 'mosque';

                }
                var sprite = game.add.sprite(x, y, assetName);

            }

        }

    }

};
<commit_msg>drawBoard to update<commit_after>/**
 * Created by shaibenvalid on 1/20/17.
 */

var gameOptions = {
    gameWidth: 960,    // game width, in pixels
    gameHeight: 600,   // game height, in pixels
    tileSize: 60,     // tile size, in pixels
    colors: [0xff0000, 0x00ff00, 0x0000ff, 0xffff00] // tile colors
}

var gameLevel = [
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0]
]

window.onload = function () {

    //  Note that this html file is set to pull down Phaser 2.5.0 from the JS Delivr CDN.
    //  Although it will work fine with this tutorial, it's almost certainly not the most current version.
    //  Be sure to replace it with an updated version before you start experimenting with adding your own code.

    var game = new Phaser.Game(960, 600, Phaser.AUTO, '', {preload: preload, create: create, update: update});

    function preload() {

        game.load.image('logo', 'phaser.png');

        game.load.image('mosque', 'assets/mosque.png');

        game.load.image('synagogue', 'assets/synagogue.png');

        game.load.image('church', 'assets/church.png');

        game.load.image('block', 'assets/blue_tile.png');
    }

    function update() {

        drawBoard(gameLevel);

    }

    function create() {

        drawBoard(gameLevel);

    }

    function drawBoard(board) {
        for (var i = 0; i < board.length; i++) {
            var row = board[i];
            for (var j = 0; j < row.length; j++) {
                var tileType = row[j];
                var x = j* gameOptions.tileSize;
                var y = i* gameOptions.tileSize;
                var assetName = 'block';
                if(tileType == 1){
                    assetName = 'mosque';

                }
                var sprite = game.add.sprite(x, y, assetName);

            }

        }

    }

};
<|endoftext|>


<commit_before>import {Motion, TransitionMotion} from 'react-motion';
import React, {Component} from 'react';
import spring from './spring.js'

class SceneNavigator extends Component{
    constructor(props) {
        super(props);
        var {state, data, url} = props.stateNavigator.stateContext;
        this.state = {scenes: {[url]: state.renderScene(data)}};
        this.onNavigate = this.onNavigate.bind(this);
    }
    componentDidMount() {
        this.props.stateNavigator.onNavigate(this.onNavigate);
    }
    componentWillUnmount() {
        this.props.stateNavigator.offNavigate(this.onNavigate);
    }
    onNavigate(oldState, state, data, asyncData) {
        this.setState((prevState) => {
            var {url, crumbs} = this.props.stateNavigator.stateContext;
            var scenes = {[url]: state.renderScene(data, asyncData)};
            for(var i = 0; i < crumbs.length; i++) {
                scenes[crumbs[i].url] = prevState.scenes[crumbs[i].url];
            }
            return {scenes};
        });
    }
    //TODO - rename parent to something more obscure so no fear of user choosing same style prop
    renderScene({key, data: {scene, state, data, mount}, style: {parent,...parentStyle}}) {
        var {mountedStyle, mountedBackStyle, children} = this.props;
        var style = getStyleAccessor(mount ? mountedStyle : mountedBackStyle)(state, data);
        return (
            <Motion key={key} style={parent ? parentStyle : style}>
                {(tweenStyle) => children(tweenStyle, scene, state, data)}
            </Motion>
        );
    }
    render() {
        var {oldState, state, data, url, crumbs} = this.props.stateNavigator.stateContext;
        var {mountedStyle, unmountedStyle} = this.props;
        var sceneContexts = crumbs.concat({state, data, url, mount: true});
        return (
            <TransitionMotion
                willEnter={() => ({...stripStyle(getStyleAccessor(unmountedStyle)(state, data)), parent: 1})}
                willLeave={() => ({...getStyleAccessor(unmountedStyle)(state, data), parent: 1})}
                styles={sceneContexts.map(({state, data, url, mount}) => ({
                    key: url,
                    data: {scene: this.state.scenes[url], state, data, mount},
                    style: {...getStyleAccessor(mountedStyle)(state, data), parent: spring(0)}
                }))}>
                {tweenStyles =>
{tweenStyles.map((config) => this.renderScene(config))}
}
            </TransitionMotion>
        );
    }
}

function stripStyle(style) {
    var strippedStyle = {};
    for(var key in style)
        strippedStyle[key] = typeof style[key] === 'number' ? style[key] : style[key].val;
    return strippedStyle;
}

function getStyleAccessor(styleProp) {
    return typeof styleProp === 'function' ? styleProp : () => styleProp;
}

export default SceneNavigator;
<commit_msg>Passed old state and data for willLeave style<commit_after>import {Motion, TransitionMotion} from 'react-motion';
import React, {Component} from 'react';
import spring from './spring.js'

class SceneNavigator extends Component{
    constructor(props) {
        super(props);
        var {state, data, url} = props.stateNavigator.stateContext;
        this.state = {scenes: {[url]: state.renderScene(data)}};
        this.onNavigate = this.onNavigate.bind(this);
    }
    componentDidMount() {
        this.props.stateNavigator.onNavigate(this.onNavigate);
    }
    componentWillUnmount() {
        this.props.stateNavigator.offNavigate(this.onNavigate);
    }
    onNavigate(oldState, state, data, asyncData) {
        this.setState((prevState) => {
            var {url, crumbs} = this.props.stateNavigator.stateContext;
            var scenes = {[url]: state.renderScene(data, asyncData)};
            for(var i = 0; i < crumbs.length; i++) {
                scenes[crumbs[i].url] = prevState.scenes[crumbs[i].url];
            }
            return {scenes};
        });
    }
    //TODO - rename parent to something more obscure so no fear of user choosing same style prop
    renderScene({key, data: {scene, state, data, mount}, style: {parent,...parentStyle}}) {
        var {mountedStyle, mountedBackStyle, children} = this.props;
        var style = getStyleAccessor(mount ? mountedStyle : mountedBackStyle)(state, data);
        return (
            <Motion key={key} style={parent ? parentStyle : style}>
                {(tweenStyle) => children(tweenStyle, scene, state, data)}
            </Motion>
        );
    }
    render() {
        var {oldState, oldData, state, data, url, crumbs} = this.props.stateNavigator.stateContext;
        var {mountedStyle, unmountedStyle} = this.props;
        var sceneContexts = crumbs.concat({state, data, url, mount: true});
        return (
            <TransitionMotion
                willEnter={() => ({...stripStyle(getStyleAccessor(unmountedStyle)(state, data)), parent: 1})}
                willLeave={() => ({...getStyleAccessor(unmountedStyle)(oldState, oldData), parent: 1})}
                styles={sceneContexts.map(({state, data, url, mount}) => ({
                    key: url,
                    data: {scene: this.state.scenes[url], state, data, mount},
                    style: {...getStyleAccessor(mountedStyle)(state, data), parent: spring(0)}
                }))}>
                {tweenStyles =>
{tweenStyles.map((config) => this.renderScene(config))}
}
            </TransitionMotion>
        );
    }
}

function stripStyle(style) {
    var strippedStyle = {};
    for(var key in style)
        strippedStyle[key] = typeof style[key] === 'number' ? style[key] : style[key].val;
    return strippedStyle;
}

function getStyleAccessor(styleProp) {
    return typeof styleProp === 'function' ? styleProp : () => styleProp;
}

export default SceneNavigator;
<|endoftext|>


<commit_before>//global variables
var duke_cachestatus;
var duke_status;
var duke_privatemode = false;
var globalLoadTimeout = 500;

// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
	window.applicationCache.addEventListener('updateready', function(e) {
		duke_cachestatus = 'updateready';
		duke_status = window.applicationCache.status;
	}, false);
	window.applicationCache.addEventListener("error", function(e) {
		duke_cachestatus = 'error';
	});
	window.applicationCache.addEventListener("cached", function(e) {
		duke_cachestatus = 'cached';
	});
	window.applicationCache.addEventListener("noupdate", function(e) {
		duke_cachestatus = 'noupdate';
	});
}, false);

////////////////////////////////
// fixscroll.js:
// call loadP and unloadP when body loads/unloads and scroll position will not move
function getScrollXY() {
    var x = 0, y = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        // Netscape
        x = window.pageXOffset;
        y = window.pageYOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        // DOM
        x = document.body.scrollLeft;
        y = document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        // IE6 standards compliant mode
        x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    }
    return [x, y];
}

function setScrollXY(x, y) {
    window.scrollTo(x, y);
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

var closeCookieDisclaimer = function () {
	createCookie('dukecon.cookiesConfirmed', '1', 1);
	document.getElementById('cookies').style.display = "none";
};

function loadP(pageref){
	x=readCookie(pageref+'x');
	y=readCookie(pageref+'y');
	console.log("Scrolling to x=" + x + " and y=" + y);
	setScrollXY(x,y);
}
function unloadP(pageref){
	s=getScrollXY();
	console.log("Current scroll position x=" + s[0] + " and y=" + s[1]);
	createCookie(pageref+'x',s[0],0.1);
	createCookie(pageref+'y',s[1],0.1);
}

var hideLoading = function (delayMs, pageId) {
	// tried knockout-event-catching (ko.bindingHandlers...) but it doesn't work, so adding a minimal timeout here to avoid watching the screen render
	setTimeout(function () {
		var loadingDiv = $('#loading'), contentDivs = $('.header, .footer, .content, #login-area, #search-area');
		contentDivs.removeClass('hidden');
		if (!loadingDiv.hasClass('hidden')) {
			loadingDiv.addClass('hidden');
		}
		loadP(pageId || 'dukeConMain');
	}, delayMs ? delayMs : 5);
};

// check if it's a Microsoft-browser
if (window.ActiveXObject || "ActiveXObject" in window || window.navigator.userAgent.indexOf("Edge") >= 0 ){
    window.addEventListener('load', function() {
    	document.querySelector("body").innerHTML =
			"
" +
			"
Leider funktioniert das Offline-Caching unserer Seite nicht mit " +
			"Microsoft-Browsern. Wir suchen derzeit nach einer Lösung und " +
			"bitten, die Unannehmlichkeiten zu entschuldigen.
" +
			"
Unfortunately, Microsoft's offline-cache handling cannot handle our site, " +
            "please use another browser. Sorry for the inconvenience. We're working on this.
" +
			"
";
    });
}<commit_msg>#98 revert it; the problem only seems to be on localhost<commit_after>//global variables
var duke_cachestatus;
var duke_status;
var duke_privatemode = false;
var globalLoadTimeout = 500;

// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
	window.applicationCache.addEventListener('updateready', function(e) {
		duke_cachestatus = 'updateready';
		duke_status = window.applicationCache.status;
	}, false);
	window.applicationCache.addEventListener("error", function(e) {
		duke_cachestatus = 'error';
	});
	window.applicationCache.addEventListener("cached", function(e) {
		duke_cachestatus = 'cached';
	});
	window.applicationCache.addEventListener("noupdate", function(e) {
		duke_cachestatus = 'noupdate';
	});
}, false);

////////////////////////////////
// fixscroll.js:
// call loadP and unloadP when body loads/unloads and scroll position will not move
function getScrollXY() {
    var x = 0, y = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        // Netscape
        x = window.pageXOffset;
        y = window.pageYOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        // DOM
        x = document.body.scrollLeft;
        y = document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        // IE6 standards compliant mode
        x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    }
    return [x, y];
}

function setScrollXY(x, y) {
    window.scrollTo(x, y);
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

var closeCookieDisclaimer = function () {
	createCookie('dukecon.cookiesConfirmed', '1', 1);
	document.getElementById('cookies').style.display = "none";
};

function loadP(pageref){
	x=readCookie(pageref+'x');
	y=readCookie(pageref+'y');
	console.log("Scrolling to x=" + x + " and y=" + y);
	setScrollXY(x,y);
}
function unloadP(pageref){
	s=getScrollXY();
	console.log("Current scroll position x=" + s[0] + " and y=" + s[1]);
	createCookie(pageref+'x',s[0],0.1);
	createCookie(pageref+'y',s[1],0.1);
}

var hideLoading = function (delayMs, pageId) {
	// tried knockout-event-catching (ko.bindingHandlers...) but it doesn't work, so adding a minimal timeout here to avoid watching the screen render
	setTimeout(function () {
		var loadingDiv = $('#loading'), contentDivs = $('.header, .footer, .content, #login-area, #search-area');
		contentDivs.removeClass('hidden');
		if (!loadingDiv.hasClass('hidden')) {
			loadingDiv.addClass('hidden');
		}
		loadP(pageId || 'dukeConMain');
	}, delayMs ? delayMs : 5);
};
<|endoftext|>


<commit_before>(function () {
    "use strict";
    Mapbender.Digitizer.AllScheme = function () {

        Mapbender.Digitizer.Scheme.apply(this, arguments);

        this.schemaName = 'all';

    };

    Mapbender.Digitizer.AllScheme.prototype = {

        assert: function() {
            var schema = this;
            console.assert(!!schema.tableFields,"Schema "+schema.schemaName+" does not have Tablefields");
        },

        getGeomType: function() {
            return 'all';
        },

        getStyleMapOptions: function (label) {
            var schema = this;
            var widget = schema.widget;

            var rules = [];

            _.each(widget.getBasicSchemes(), function (scheme) {

                var rule = new OpenLayers.Rule({
                    symbolizer: scheme.layer.styleMap.styles[label].defaultStyle,
                    evaluate: function (feature) {
                        var equals = feature.attributes.schemaName === scheme.schemaName;
                        return equals;
                    }
                });

                rules.push(rule);
            });

            // Regel zur Darstellung von nicht-digitizer Features wie den Modification Vertices
            rules.push(new OpenLayers.Rule({

                symbolizer: OpenLayers.Feature.Vector.style['default'],
                evaluate: function (feature) {
                    return !feature.attributes.schemaName; // Feature ohne Schemaname ist keine Digitizer Feature
                }
            }));

            return {
                rules: rules
            }
        },

        createToolset: function () {
            var schema = this;
            var widget = schema.widget;
            var toolset = [];
            _.each(widget.getBasicSchemes(), function (scheme) {
                $.each(scheme.toolset, function (i, rawButton) {

                    // Avoid duplicates, i.e. elements with same 'type' property
                    if (toolset.filter(function (t) {
                        return t.type === rawButton.type && !Mapbender.Digitizer.Utilities.isAddingToolsetType(t.type);
                    }).length === 0) {
                        if (Mapbender.Digitizer.Utilities.isAddingToolsetType(rawButton.type)) {
                            rawButton.schema = scheme.getRestrictedVersion();
                        }
                        toolset.push(rawButton);
                    }

                });

            });

            // TODO find better place for all possible controls in array
            var config = ['drawPoint', 'drawLine', 'drawPolygon', 'drawRectangle', 'drawCircle', 'drawEllipse', 'drawDonut', 'drawText', 'modifyFeature', 'moveFeature', 'selectFeature', 'removeSelected'];

            toolset = toolset.sort(function (a, b) {
                return config.indexOf(a.type) > config.indexOf(b.type) ? 1 : ( a.schema && b.schema && (a.schema.index >q b.schema.index) ? 1 : -1) ;
            });

            return toolset;
        },

        createFormItemsCollection: function(formItems) {
            //Do Nothing - All Scheme does not administer formItemsCollection
        },

        updateConfigurationAfterSwitching: function(updatedSchemes) {
            var schema = this;
            var widget = schema.widget;
            _.each(widget.getBasicSchemes(), function (scheme,schemaName) {
                scheme.createFormItemsCollection(updatedSchemes[schemaName].formItems); // Update formItems Of All Schemes when switiching
            });
        },

        initTableFields: function() {
            var schemes = this.widget.schemes;
            this.tableFields = schemes[Object.keys(schemes)[1]].tableFields; // TODO Only solvable when Data of different Features is already aggregated in the database query

        },

        getSchemaByFeature: function (feature) {
            var schema = this;
            var widget = schema.widget;
            var scheme = widget.getSchemaByName(feature.attributes.schemaName);
            return scheme.getRestrictedVersion();

        }
    };

    Object.setPrototypeOf(Mapbender.Digitizer.AllScheme.prototype, Mapbender.Digitizer.Scheme.prototype);

})();
<commit_msg>Rearrange Control Buttons<commit_after>(function () {
    "use strict";
    Mapbender.Digitizer.AllScheme = function () {

        Mapbender.Digitizer.Scheme.apply(this, arguments);

        this.schemaName = 'all';

    };

    Mapbender.Digitizer.AllScheme.prototype = {

        assert: function() {
            var schema = this;
            console.assert(!!schema.tableFields,"Schema "+schema.schemaName+" does not have Tablefields");
        },

        getGeomType: function() {
            return 'all';
        },

        getStyleMapOptions: function (label) {
            var schema = this;
            var widget = schema.widget;

            var rules = [];

            _.each(widget.getBasicSchemes(), function (scheme) {

                var rule = new OpenLayers.Rule({
                    symbolizer: scheme.layer.styleMap.styles[label].defaultStyle,
                    evaluate: function (feature) {
                        var equals = feature.attributes.schemaName === scheme.schemaName;
                        return equals;
                    }
                });

                rules.push(rule);
            });

            // Regel zur Darstellung von nicht-digitizer Features wie den Modification Vertices
            rules.push(new OpenLayers.Rule({

                symbolizer: OpenLayers.Feature.Vector.style['default'],
                evaluate: function (feature) {
                    return !feature.attributes.schemaName; // Feature ohne Schemaname ist keine Digitizer Feature
                }
            }));

            return {
                rules: rules
            }
        },

        createToolset: function () {
            var schema = this;
            var widget = schema.widget;
            var toolset = [];
            _.each(widget.getBasicSchemes(), function (scheme) {
                $.each(scheme.toolset, function (i, rawButton) {

                    // Avoid duplicates, i.e. elements with same 'type' property
                    if (toolset.filter(function (t) {
                        return t.type === rawButton.type && !Mapbender.Digitizer.Utilities.isAddingToolsetType(t.type);
                    }).length === 0) {
                        if (Mapbender.Digitizer.Utilities.isAddingToolsetType(rawButton.type)) {
                            rawButton.schema = scheme.getRestrictedVersion();
                        }
                        toolset.push(rawButton);
                    }

                });

            });

            // TODO find better place for all possible controls in array
            var config = ['drawPoint', 'drawLine', 'drawPolygon', 'drawRectangle', 'drawCircle', 'drawEllipse', 'drawDonut', 'drawText', 'modifyFeature', 'moveFeature', 'selectFeature', 'removeSelected'];

            toolset = toolset.sort(function (a, b) {
                return config.indexOf(a.type) > config.indexOf(b.type) ? 1 : ( a.schema && b.schema && (a.schema.index > b.schema.index) ? 1 : -1) ;
            });

            return toolset;
        },

        createFormItemsCollection: function(formItems) {
            //Do Nothing - All Scheme does not administer formItemsCollection
        },

        updateConfigurationAfterSwitching: function(updatedSchemes) {
            var schema = this;
            var widget = schema.widget;
            _.each(widget.getBasicSchemes(), function (scheme,schemaName) {
                scheme.createFormItemsCollection(updatedSchemes[schemaName].formItems); // Update formItems Of All Schemes when switiching
            });
        },

        initTableFields: function() {
            var schemes = this.widget.schemes;
            this.tableFields = schemes[Object.keys(schemes)[1]].tableFields; // TODO Only solvable when Data of different Features is already aggregated in the database query

        },

        getSchemaByFeature: function (feature) {
            var schema = this;
            var widget = schema.widget;
            var scheme = widget.getSchemaByName(feature.attributes.schemaName);
            return scheme.getRestrictedVersion();

        }
    };

    Object.setPrototypeOf(Mapbender.Digitizer.AllScheme.prototype, Mapbender.Digitizer.Scheme.prototype);

})();
<|endoftext|>