<commit_before>/*
* Name :  BarChart.js
* Module : UnitTest
* Location : /frontend/test/unit/Model
*
* History :
* Version       Date        Programmer                  Description
* =================================================================================================
* 0.3.0			2015-05-21	Francesco Rossetto			Restructured test
*
* 0.2.3         2015-05-21  Maria Giovanna Chinellato   Fix code
*
* 0.2.2			2015-05-21	Maria Giovanna Chinellato	Fix test of Model::BarChart
*
* 0.2.1			2015-05-21	Maria Giovanna Chinellato	Fix methods test
*
* 0.2.0			2015-05-21	Maria Giovanna Chinellato	Add test of all the methods of LineChart classes
*
* 0.1.0			2015-05-21	Maria Giovanna Chinellato	Add test of Model::BarChart.js
*
* 0.0.1			2015-05-20	Maria Giovanna Chinellato	Initial code
* =================================================================================================
*
*/

describe('BarChart', function(){
	'use strict';

	var BarChartFactory;
	var BarChartFlowFactory;

	beforeEach(angular.mock.module('norris-nrti'));

	beforeEach(inject(function(_BarChartFactory_, $injector){
		BarChartFactory = _BarChartFactory_;
		BarChartFlowFactory = $injector.get('BarChartFlowFactory');
	}));

	describe('Constructor', function(){

		var json = {
			'title' : 'fottutissimografico',
			'socketURL' : 'localhost/page1/grafico1'
		};
		var BarChart;

		beforeEach(function(){
			BarChart = BarChartFactory.build(json);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('BarChart created', function(){
			expect(BarChart).toBeDefined();
		});
		it('graph Constructor called', function(){
			expect(BarChart.getTitle()).toEqual('fottutissimografico');
		});
		it('graph Constructor called', function(){
			expect(BarChart.getUrl()).toEqual('localhost/page1/grafico1');
		});
		it('graph created with the correct axisX', function(){
			expect(BarChart.getX()).toEqual(null);
		});
		it('graph created with the correct axisY', function(){
			expect(BarChart.getY()).toEqual(null);
		});
		it('graph created with the correct barOrientation', function(){
			expect(BarChart.getBarOrientation()).toEqual('V');
		});
		it('graph created with the correct headers', function(){
			expect(BarChart.getHeaders()).toEqual([]);
		});
		it('graph created with the correct background', function(){
			expect(BarChart.getBackground()).toEqual('#FFF');
		});
		it('graph created with the correct sortable', function(){
			expect(BarChart.getSortable()).toEqual(true);
		});
		it('graph created with the correct grouping control', function(){
			expect(BarChart.getGroupingControl()).toEqual(true);
		});
		it('graph created with the correct legendOnPoint', function(){
			expect(BarChart.getLegendOnPoint()).toEqual(false);
		});
		it('graph created with the correct flow', function(){
			expect(BarChart.getFlowList().length).toEqual(0);
		});
		it('graph created with the correct horizontalGrid', function(){
			expect(BarChart.getHGrid()).toEqual(false);
		});

	});

	/*deeescribe('split', function(){
		var res;
		var json = {};
		var json1 = json;
		json = json1;
		json = {
			'title' : 'grafico',
			'height' : 300,
			'width' : 300,
			'enabledLegend' : true,
			'legend' : {},
			'horizontalGrid' : true,
			'verticalGrid' : true,
			'axisX' : {},
			'axisY' : {},
			'barOrientation' : 'horizontal',
			'background' : '#FFF',
			'sortable' : false,
			'barsGrouping' : 'stacked'
		};
		var g = {
			'title' : 'grafico',
			'height' : 300,
			'width' : 300,
			'enabledLegend' : true,
			'legend' : {},
			'horizontalGrid' : true,
			'verticalGrid' : true
		};
		var b = {
			'axisX' : {},
			'axisY' : {},
			'barOrientation' : 'horizontal',
			'background' : '#FFF',
			'sortable' : false,
			'barsGrouping' : 'stacked'
		};

		beforeEach(function(){
			res = BarChart.Test('split(json)');
		});

		it('json splitted in the correct way', function(){
			expect(res.graphJson).toEqual(g);
			expect(res.barJson).toEqual(b);
		});

	});*/

	describe('#updateParameters', function(){
		var json = {
			'title' : 'graficonuovo',
			'height' : 400,
			'width' : 400,
			'enabledLegend' : false,
			'axisX' : {},
			'axisY' : {},
			'barOrientation' : 'vertical',
			'headers' : ['colonna1'],
			'backgroundColor' : '#F0F',
			'sortable' : false,
			'groupingControl' : false,
			'legendOnPoint' : true,
			'grid' : false,
			'flows' : [{'ID' : 'f1'},{ 'ID' : 'f2'},{'ID' : 'f3'}]
		};
		var BarChart;

		beforeEach(function(){
			BarChart = BarChartFactory.build();
			BarChart.updateParameters(json);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('BarChart created', function(){
			expect(BarChart).toBeDefined();
		});
		it('graph updated with the correct axisX', function(){
			expect(BarChart.getX()).toEqual(null);
		});
		it('graph updated with the correct axisY', function(){
			expect(BarChart.getY()).toEqual(null);
		});
		it('graph updated with the correct barOrientation', function(){
			expect(BarChart.getBarOrientation()).toEqual('vertical');
		});
		it('graph updated with the correct headers', function(){
			expect(BarChart.getHeaders().length).toEqual(1);
		});
		it('graph updated with the correct background', function(){
			expect(BarChart.getBackground()).toEqual('#F0F');
		});
		it('graph updated with the correct sortable', function(){
			expect(BarChart.getSortable()).toEqual(false);
		});
		it('graph updated with the correct grouping control', function(){
			expect(BarChart.getGroupingControl()).toEqual(false);
		});
		it('graph updated with the correct legendOnPoint', function(){
			expect(BarChart.getLegendOnPoint()).toEqual(true);
		});
		it('graph updated with the correct flow', function(){
			expect(BarChart.getFlowList().length).toEqual(3);
		});
		it('graph updated with the correct horizontalGrid', function(){
			expect(BarChart.getHGrid()).toEqual(false);
		});

	});

	describe('#addFlow', function(){

		var json = {
			'ID' : 	'flusso1'
		};
		var fJson = {
			'name' : 'flusso1',
			'flowColor' : '#F2F'
		};
		var newflow;
		var BarChart;

		beforeEach(function(){
			newflow = BarChartFlowFactory.build(fJson);
			BarChart = BarChartFactory.build();
			BarChart.addFlow(json.ID, newflow);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('graph addFlow called with the correct parameters', function(){
			expect(BarChart.getFlowList().length).toEqual(1);
		});

	});

	describe('#deleteFlow', function(){

		var json1 = {
			'ID' : 	'flusso1',
			'name' : 'sonda 1'
		};

		var json2 = {
			'ID' : 	'flusso2',
			'name' : 'sonda 2'
		};
		var BarChart, Flow1, Flow2;

		beforeEach(function(){
			Flow1 = BarChartFlowFactory.build();
			Flow2 = BarChartFlowFactory.build();
			BarChart = BarChartFactory.build();
			BarChart.addFlow(json1.ID, Flow1);
			BarChart.addFlow(json2.ID, Flow2);
			BarChart.deleteFlow('flusso1');
		});

		afterEach(function(){
			Flow1 = null;
			Flow2 = null;
			BarChart = null;
		});

		it('delete flow from graph', function(){
			expect(BarChart.getFlowList().length).toEqual(1);
		});

	});

	describe('#replaceData', function(){

		var json1 = {
			'ID' : 	'flusso1',
			'name' : 'sonda 1',
			'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }, {'NorrisRecordID' : 'record3', 'value' : [4,4] }]
		};

		var json = {
			'ID' : 'flusso1',
			'records' :	[{'NorrisRecordID' : 'record4', 'value' : [5,5] }, {'NorrisRecordID' : 'record5', 'value' : [6,6] }]
		};

		var BarChart, Flow;

		beforeEach(function(){
			Flow = BarChartFlowFactory.build();
			Flow.initializeData(json1);
			BarChart = BarChartFactory.build();
			BarChart.addFlow(json1.ID, Flow);
			BarChart.replaceData(json);
		});

		afterEach(function(){
			Flow = null;
			BarChart = null;
		});

		it('delete flow from graph', function(){
			expect(BarChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(5);
			expect(BarChart.getFlowList()[0].flow.getData()[1].value[0]).toEqual(6);
		});

	});

	describe('#initializeData', function(){

		var data = [
			{
				'ID' : '1',
				'records' : [{ 'NorrisRecordID' : '234321', 'value' : [0,1]},{}]
			}
		];
		var newFlow;
		var BarChart;

		beforeEach(function(){
			newFlow = BarChartFlowFactory.build();
			BarChart = BarChartFactory.build();
			BarChart.addFlow(data[0].ID, newFlow);
			BarChart.initializeData(data);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('BarChartFlow inizializeData called in the right way', function(){
			expect(BarChart.getFlowList()[0].flow.getData().length).toEqual(2);
		});

	});

	describe('#inPlaceUpdate', function(){

		var data = [
			{
				'ID' : '2',
				'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }]
			}
		];
		var data1 = 	{
			'ID' : '2',
			'NorrisRecordID' : 'record2',
			'value' : [4,4]
		};
		var newFlow;
		var BarChart;

		beforeEach(function(){
			newFlow = BarChartFlowFactory.build();
			BarChart = BarChartFactory.build();
			BarChart.addFlow(data[0].ID, newFlow);
			BarChart.initializeData(data);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('BarChartFlow inPlaceUpdate called in the right way', function(){
			expect(BarChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(3);
			BarChart.inPlaceUpdate(data1);
			expect(BarChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(4);
		});
	});

	describe('#deleteData', function(){

		var data = [
			{
				'ID' : '2',
				'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }]
			}
		];

		var delData = {
			'ID' : '2',
			'NorrisRecordID' : 'record2'
		};

		var newFlow;
		var BarChart;

		beforeEach(function(){
			newFlow = BarChartFlowFactory.build();
			BarChart = BarChartFactory.build();
			BarChart.addFlow(data[0].ID, newFlow);
			BarChart.initializeData(data);
			BarChart.deleteData(delData);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('deleteData in the correct way', function(){
			expect(BarChart.getFlowList()[0].flow.getData().length).toEqual(0);
		});
	});

});<commit_msg>fix bar chart spec<commit_after>/*
* Name :  BarChart.js
* Module : UnitTest
* Location : /frontend/test/unit/Model
*
* History :
* Version       Date        Programmer                  Description
* =================================================================================================
* 0.3.0			2015-05-21	Francesco Rossetto			Restructured test
*
* 0.2.3         2015-05-21  Maria Giovanna Chinellato   Fix code
*
* 0.2.2			2015-05-21	Maria Giovanna Chinellato	Fix test of Model::BarChart
*
* 0.2.1			2015-05-21	Maria Giovanna Chinellato	Fix methods test
*
* 0.2.0			2015-05-21	Maria Giovanna Chinellato	Add test of all the methods of LineChart classes
*
* 0.1.0			2015-05-21	Maria Giovanna Chinellato	Add test of Model::BarChart.js
*
* 0.0.1			2015-05-20	Maria Giovanna Chinellato	Initial code
* =================================================================================================
*
*/

describe('BarChart', function(){
	'use strict';

	var BarChartFactory;
	var BarChartFlowFactory;

	beforeEach(angular.mock.module('norris-nrti'));

	beforeEach(inject(function(_BarChartFactory_, $injector){
		BarChartFactory = _BarChartFactory_;
		BarChartFlowFactory = $injector.get('BarChartFlowFactory');
	}));

	describe('Constructor', function(){

		var json = {
			'title' : 'fottutissimografico',
			'socketURL' : 'localhost/page1/grafico1'
		};
		var BarChart;

		beforeEach(function(){
			BarChart = BarChartFactory.build(json);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('BarChart created', function(){
			expect(BarChart).toBeDefined();
		});
		it('graph Constructor called', function(){
			expect(BarChart.getTitle()).toEqual('fottutissimografico');
		});
		it('graph Constructor called', function(){
			expect(BarChart.getUrl()).toEqual('localhost/page1/grafico1');
		});
		it('graph created with the correct axisX', function(){
			expect(BarChart.getX()).toEqual(null);
		});
		it('graph created with the correct axisY', function(){
			expect(BarChart.getY()).toEqual(null);
		});
		it('graph created with the correct barOrientation', function(){
			expect(BarChart.getBarOrientation()).toEqual('V');
		});
		it('graph created with the correct headers', function(){
			expect(BarChart.getHeaders()).toEqual([]);
		});
		it('graph created with the correct background', function(){
			expect(BarChart.getBackground()).toEqual('#FFF');
		});
		it('graph created with the correct sortable', function(){
			expect(BarChart.getSortable()).toEqual(true);
		});
		it('graph created with the correct grouping control', function(){
			expect(BarChart.getGroupingControl()).toEqual(true);
		});
		it('graph created with the correct legendOnPoint', function(){
			expect(BarChart.getLegendOnPoint()).toEqual(false);
		});
		it('graph created with the correct flow', function(){
			expect(BarChart.getFlowList().length).toEqual(0);
		});
		it('graph created with the correct horizontalGrid', function(){
			expect(BarChart.getHGrid()).toEqual(false);
		});

	});

	/*deeescribe('split', function(){
		var res;
		var json = {};
		var json1 = json;
		json = json1;
		json = {
			'title' : 'grafico',
			'height' : 300,
			'width' : 300,
			'enabledLegend' : true,
			'legend' : {},
			'horizontalGrid' : true,
			'verticalGrid' : true,
			'axisX' : {},
			'axisY' : {},
			'barOrientation' : 'horizontal',
			'background' : '#FFF',
			'sortable' : false,
			'barsGrouping' : 'stacked'
		};
		var g = {
			'title' : 'grafico',
			'height' : 300,
			'width' : 300,
			'enabledLegend' : true,
			'legend' : {},
			'horizontalGrid' : true,
			'verticalGrid' : true
		};
		var b = {
			'axisX' : {},
			'axisY' : {},
			'barOrientation' : 'horizontal',
			'background' : '#FFF',
			'sortable' : false,
			'barsGrouping' : 'stacked'
		};

		beforeEach(function(){
			res = BarChart.Test('split(json)');
		});

		it('json splitted in the correct way', function(){
			expect(res.graphJson).toEqual(g);
			expect(res.barJson).toEqual(b);
		});

	});*/

	describe('#updateParameters', function(){
		var json = {
			'title' : 'graficonuovo',
			'height' : 400,
			'width' : 400,
			'enableLegend' : false,
			'legend' : {position: 'E'},
			'socketURL' : 'http://example.com',
			'axisX' : { name: 'asseX' },
			'axisY' : { name: 'asseY' },
			'barOrientation' : 'vertical',
			'headers' : ['colonna1'],
			'backgroundColor' : '#F0F',
			'sortable' : false,
			'groupingControl' : false,
			'legendOnPoint' : true,
			'grid' : false,
			'flows' : [{'ID' : 'f1'},{ 'ID' : 'f2'},{'ID' : 'f3'}]
		};
		var BarChart;

		beforeEach(function(){
			BarChart = BarChartFactory.build();
			BarChart.updateParameters(json);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('BarChart created', function(){
			expect(BarChart).toBeDefined();
		});
		it('graph updated with the correct height', function(){
			expect(BarChart.getHeight()).toEqual(400);
		});
		it('graph updated with the correct width', function(){
			expect(BarChart.getWidth()).toEqual(400);
		});
		it('graph updated with the correct axisX', function(){
			expect(BarChart.getX()).not.toEqual(null);
		});
		it('graph updated with the correct axisY', function(){
			expect(BarChart.getY()).not.toEqual(null);
		});
		it('graph updated with the correct barOrientation', function(){
			expect(BarChart.getBarOrientation()).toEqual('vertical');
		});
		it('graph updated with the correct headers', function(){
			expect(BarChart.getHeaders().length).toEqual(1);
		});
		it('graph updated with the correct background', function(){
			expect(BarChart.getBackground()).toEqual('#F0F');
		});
		it('graph updated with the correct sortable', function(){
			expect(BarChart.getSortable()).toEqual(false);
		});
		it('graph updated with the correct grouping control', function(){
			expect(BarChart.getGroupingControl()).toEqual(false);
		});
		it('graph updated with the correct legendOnPoint', function(){
			expect(BarChart.getLegendOnPoint()).toEqual(true);
		});
		it('graph updated with the correct flow', function(){
			expect(BarChart.getFlowList().length).toEqual(3);
		});
		it('graph updated with the correct horizontalGrid', function(){
			expect(BarChart.getHGrid()).toEqual(false);
		});

	});

	describe('#addFlow', function(){

		var json = {
			'ID' : 	'flusso1'
		};
		var fJson = {
			'name' : 'flusso1',
			'flowColor' : '#F2F'
		};
		var newflow;
		var BarChart;

		beforeEach(function(){
			newflow = BarChartFlowFactory.build(fJson);
			BarChart = BarChartFactory.build();
			BarChart.addFlow(json.ID, newflow);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('graph addFlow called with the correct parameters', function(){
			expect(BarChart.getFlowList().length).toEqual(1);
		});

	});

	describe('#deleteFlow', function(){

		var json1 = {
			'ID' : 	'flusso1',
			'name' : 'sonda 1'
		};

		var json2 = {
			'ID' : 	'flusso2',
			'name' : 'sonda 2'
		};
		var BarChart, Flow1, Flow2;

		beforeEach(function(){
			Flow1 = BarChartFlowFactory.build();
			Flow2 = BarChartFlowFactory.build();
			BarChart = BarChartFactory.build();
			BarChart.addFlow(json1.ID, Flow1);
			BarChart.addFlow(json2.ID, Flow2);
			BarChart.deleteFlow('flusso1');
		});

		afterEach(function(){
			Flow1 = null;
			Flow2 = null;
			BarChart = null;
		});

		it('delete flow from graph', function(){
			expect(BarChart.getFlowList().length).toEqual(1);
		});

	});

	describe('#replaceData', function(){

		var json1 = {
			'ID' : 	'flusso1',
			'name' : 'sonda 1',
			'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }, {'NorrisRecordID' : 'record3', 'value' : [4,4] }]
		};

		var json = {
			'ID' : 'flusso1',
			'records' :	[{'NorrisRecordID' : 'record4', 'value' : [5,5] }, {'NorrisRecordID' : 'record5', 'value' : [6,6] }]
		};

		var BarChart, Flow;

		beforeEach(function(){
			Flow = BarChartFlowFactory.build();
			Flow.initializeData(json1);
			BarChart = BarChartFactory.build();
			BarChart.addFlow(json1.ID, Flow);
			BarChart.replaceData(json);
		});

		afterEach(function(){
			Flow = null;
			BarChart = null;
		});

		it('delete flow from graph', function(){
			expect(BarChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(5);
			expect(BarChart.getFlowList()[0].flow.getData()[1].value[0]).toEqual(6);
		});

	});

	describe('#initializeData', function(){

		var data = [
			{
				'ID' : '1',
				'records' : [{ 'NorrisRecordID' : '234321', 'value' : [0,1]},{}]
			}
		];
		var newFlow;
		var BarChart;

		beforeEach(function(){
			newFlow = BarChartFlowFactory.build();
			BarChart = BarChartFactory.build();
			BarChart.addFlow(data[0].ID, newFlow);
			BarChart.initializeData(data);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('BarChartFlow inizializeData called in the right way', function(){
			expect(BarChart.getFlowList()[0].flow.getData().length).toEqual(2);
		});

	});

	describe('#inPlaceUpdate', function(){

		var data = [
			{
				'ID' : '2',
				'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }]
			}
		];
		var data1 = 	{
			'ID' : '2',
			'NorrisRecordID' : 'record2',
			'value' : [4,4]
		};
		var newFlow;
		var BarChart;

		beforeEach(function(){
			newFlow = BarChartFlowFactory.build();
			BarChart = BarChartFactory.build();
			BarChart.addFlow(data[0].ID, newFlow);
			BarChart.initializeData(data);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('BarChartFlow inPlaceUpdate called in the right way', function(){
			expect(BarChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(3);
			BarChart.inPlaceUpdate(data1);
			expect(BarChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(4);
		});
	});

	describe('#addRecords', function(){

		var data = {
			'ID' : 'flusso1',
			'records' : [
				{
					'NorrisRecordID' : 'record1',
					'value' : [ 1, 1]
				}
			]
		};

		var add = {
			'ID' : 'flusso1',
			'records' : [
				{	'NorrisRecordID' : 'record2',
					'value' : [ 1, 2]
				}
			]
		};

		var BarChart;

		beforeEach(function(){
			BarChart = BarChartFactory.build();
			BarChart.initializeData(data);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('data updated in the correct way', function(){
			expect(BarChart.getFlowList()[0].getData().length).toEqual(1);
			BarChart.addRecords(add);
			expect(BarChart.getFlowList()[0].getData().length).toEqual(2);
		});
	});

	describe('#deleteData', function(){

		var data = [
			{
				'ID' : '2',
				'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }]
			}
		];

		var delData = {
			'ID' : '2',
			'NorrisRecordID' : 'record2'
		};

		var newFlow;
		var BarChart;

		beforeEach(function(){
			newFlow = BarChartFlowFactory.build();
			BarChart = BarChartFactory.build();
			BarChart.addFlow(data[0].ID, newFlow);
			BarChart.initializeData(data);
			BarChart.deleteData(delData);
		});

		afterEach(function(){
			BarChart = null;
		});

		it('deleteData in the correct way', function(){
			expect(BarChart.getFlowList()[0].flow.getData().length).toEqual(0);
		});
	});

});<|endoftext|>


<commit_before>/***
|''Name''|ToggleTiddlerPrivacyPlugin|
|''Version''|0.6.5|
|''Status''|@@beta@@|
|''Description''|Allows you to set the privacy of new tiddlers and external tiddlers within an EditTemplate|
|''Requires''|TiddlySpaceConfig|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/ToggleTiddlerPrivacyPlugin.js|
!Notes
When used in conjunction with TiddlySpaceTiddlerIconsPlugin changing the privacy setting will also interact with any privacy icons.

Currently use of
{{{<<setPrivacy defaultValue:public>>}}} is in conflict with {{{<<newTiddler fields:"server.workspace:x_private">>}}}
!Params
defaultValue:[private|public]
Allows you to set the default privacy value (Default is private)

!Code
***/
//{{{
(function($) {

var tiddlyspace = config.extensions.tiddlyspace;
var macro = config.macros.setPrivacy = {
	default_state: "private",

	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		if(readOnly) {
			return;
		}
		var el = $(story.findContainingTiddler(place));
		var args = paramString.parseParams("name", null, true, false, true)[0];
		var container = $("<div />").addClass("privacySettings").appendTo(place)[0];
		var currentSpace = tiddlyspace.currentSpace.name;
		var currentBag = tiddler ? tiddler.fields["server.bag"] : false;
		var isNewTiddler = el.hasClass("missing") || !currentBag; // XXX: is this reliable?
		var status = tiddlyspace.getTiddlerStatusType(tiddler);
		var customFields = $(el).attr("tiddlyfields");
		customFields = customFields ? customFields.decodeHashMap() : {};
		if(isNewTiddler || !["public", "private"].contains(status)) {
			var defaultValue = args.defaultValue;
			defaultValue = defaultValue ? "%0_%1".format([currentSpace, defaultValue[0]]) : customFields["server.bag"];
			var options = config.macros.tiddlerOrigin ?
				config.macros.tiddlerOrigin.getOptions(paramString) : {};
			this.createRoundel(container, tiddler, currentSpace, defaultValue, options);
		}
	},
	updateEditFields: function(tiddlerEl, bag) {
		var saveBagField = $("[edit=server.bag]", tiddlerEl);
		var saveWorkspaceField = $("[edit=server.workspace]", tiddlerEl);
		var input = $("<input />").attr("type", "hidden");
		if(saveBagField.length === 0) {
			input.clone().attr("edit", "server.bag").val(bag).appendTo(tiddlerEl);
		} else {
			saveBagField.val(bag);
		}
		var workspace = "bags/%0".format([bag]);
		if(saveWorkspaceField.length === 0) {
			input.clone().attr("edit", "server.workspace").val(workspace).appendTo(tiddlerEl);
		} else {
			saveWorkspaceField.val(workspace);
		}
	},
	setBag: function(tiddlerEl, newBag, options) {
		var title = $(tiddlerEl).attr("tiddler");
		var tiddler = store.getTiddler(title);
		var originButton = $(".originButton", tiddlerEl)[0];
		var refreshIcon = function(type) {
			var originMacro = config.macros.tiddlerOrigin;
			if(originButton && originMacro) {
				options.noclick = true;
				originMacro.showPrivacyRoundel(tiddler, type, originButton, options);
			}
		};
		macro.updateEditFields(tiddlerEl, newBag);
		var newWorkspace = "bags/%0".format([newBag]);
		if(tiddler) {
			tiddler.fields["server.bag"] = newBag;
			tiddler.fields["server.workspace"] = newWorkspace; // for external tiddlers
		}
		var rPrivate = $("input[type=radio].isPrivate", tiddlerEl);
		var rPublic = $("input[type=radio].isPublic", tiddlerEl);
		if(newBag.indexOf("_public") > -1) {
			rPublic.attr("checked", true);
			rPrivate.attr("checked", false);
			status = "public";
		} else {
			rPrivate.attr("checked", true);
			rPublic.attr("checked", false); // explicitly do this for ie
			status = "private";
		}
		refreshIcon(status);
	},
	createRoundel: function(container, tiddler, currentSpace, defaultValue, options) {
		var privateBag = "%0_private".format([currentSpace]);
		var publicBag = "%0_public".format([currentSpace]);
		var rbtn = $("<input />").attr("type", "radio").attr("name", tiddler.title);
		var rPrivate = rbtn.clone().val("private").addClass("isPrivate").appendTo(container);
		$("<label />").text("private").appendTo(container); // TODO: i18n
		var rPublic = rbtn.clone().val("public").addClass("isPublic").appendTo(container);
		$("<label />").text("public").appendTo(container); // TODO: i18n
		var status = macro.default_state;
		var el = story.findContainingTiddler(container);
		$("[type=radio]", container).click(function(ev) {
			var btn = $(ev.target);
			tiddler.fields["server.page.revision"] = "false";
			if(btn.hasClass("isPrivate")) { // private button clicked.
				$(el).addClass("isPrivate").removeClass("isPublic");
				macro.setBag(el, privateBag, options);
			} else {
				$(el).addClass("isPublic").removeClass("isPrivate");
				macro.setBag(el, publicBag, options);
			}
		});
		if(!defaultValue) {
			defaultValue = macro.default_state == "public" ? publicBag : privateBag;
		}
		window.setTimeout(function() {
			macro.setBag(el, defaultValue, options);
		}, 100);
		// annoyingly this is needed as customFields are added to end of EditTemplate so are not present yet
		// and don't seem to respect any existing customFields.
	}
};

})(jQuery);
//}}}
<commit_msg>updated ToggleTiddlerPrivacy to not show radio buttons for unsynced states.<commit_after>/***
|''Name''|ToggleTiddlerPrivacyPlugin|
|''Version''|0.6.6|
|''Status''|@@beta@@|
|''Description''|Allows you to set the privacy of new tiddlers and external tiddlers within an EditTemplate|
|''Requires''|TiddlySpaceConfig|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/ToggleTiddlerPrivacyPlugin.js|
!Notes
When used in conjunction with TiddlySpaceTiddlerIconsPlugin changing the privacy setting will also interact with any privacy icons.

Currently use of
{{{<<setPrivacy defaultValue:public>>}}} is in conflict with {{{<<newTiddler fields:"server.workspace:x_private">>}}}
!Params
defaultValue:[private|public]
Allows you to set the default privacy value (Default is private)

!Code
***/
//{{{
(function($) {

var tiddlyspace = config.extensions.tiddlyspace;
var macro = config.macros.setPrivacy = {
	default_state: "private",

	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		if(readOnly) {
			return;
		}
		var el = $(story.findContainingTiddler(place));
		var args = paramString.parseParams("name", null, true, false, true)[0];
		var container = $("<div />").addClass("privacySettings").appendTo(place)[0];
		var currentSpace = tiddlyspace.currentSpace.name;
		var currentBag = tiddler ? tiddler.fields["server.bag"] : false;
		var isNewTiddler = el.hasClass("missing") || !currentBag; // XXX: is this reliable?
		var status = tiddlyspace.getTiddlerStatusType(tiddler);
		var customFields = $(el).attr("tiddlyfields");
		customFields = customFields ? customFields.decodeHashMap() : {};
		if(isNewTiddler || !["public", "private", "unsyncedPrivate", "unsyncedPublic"].contains(status)) {
			var defaultValue = args.defaultValue;
			defaultValue = defaultValue ? "%0_%1".format([currentSpace, defaultValue[0]]) : customFields["server.bag"];
			var options = config.macros.tiddlerOrigin ?
				config.macros.tiddlerOrigin.getOptions(paramString) : {};
			this.createRoundel(container, tiddler, currentSpace, defaultValue, options);
		}
	},
	updateEditFields: function(tiddlerEl, bag) {
		var saveBagField = $("[edit=server.bag]", tiddlerEl);
		var saveWorkspaceField = $("[edit=server.workspace]", tiddlerEl);
		var input = $("<input />").attr("type", "hidden");
		if(saveBagField.length === 0) {
			input.clone().attr("edit", "server.bag").val(bag).appendTo(tiddlerEl);
		} else {
			saveBagField.val(bag);
		}
		var workspace = "bags/%0".format([bag]);
		if(saveWorkspaceField.length === 0) {
			input.clone().attr("edit", "server.workspace").val(workspace).appendTo(tiddlerEl);
		} else {
			saveWorkspaceField.val(workspace);
		}
	},
	setBag: function(tiddlerEl, newBag, options) {
		var title = $(tiddlerEl).attr("tiddler");
		var tiddler = store.getTiddler(title);
		var originButton = $(".originButton", tiddlerEl)[0];
		var refreshIcon = function(type) {
			var originMacro = config.macros.tiddlerOrigin;
			if(originButton && originMacro) {
				options.noclick = true;
				originMacro.showPrivacyRoundel(tiddler, type, originButton, options);
			}
		};
		macro.updateEditFields(tiddlerEl, newBag);
		var newWorkspace = "bags/%0".format([newBag]);
		if(tiddler) {
			tiddler.fields["server.bag"] = newBag;
			tiddler.fields["server.workspace"] = newWorkspace; // for external tiddlers
		}
		var rPrivate = $("input[type=radio].isPrivate", tiddlerEl);
		var rPublic = $("input[type=radio].isPublic", tiddlerEl);
		if(newBag.indexOf("_public") > -1) {
			rPublic.attr("checked", true);
			rPrivate.attr("checked", false);
			status = "public";
		} else {
			rPrivate.attr("checked", true);
			rPublic.attr("checked", false); // explicitly do this for ie
			status = "private";
		}
		refreshIcon(status);
	},
	createRoundel: function(container, tiddler, currentSpace, defaultValue, options) {
		var privateBag = "%0_private".format([currentSpace]);
		var publicBag = "%0_public".format([currentSpace]);
		var rbtn = $("<input />").attr("type", "radio").attr("name", tiddler.title);
		var rPrivate = rbtn.clone().val("private").addClass("isPrivate").appendTo(container);
		$("<label />").text("private").appendTo(container); // TODO: i18n
		var rPublic = rbtn.clone().val("public").addClass("isPublic").appendTo(container);
		$("<label />").text("public").appendTo(container); // TODO: i18n
		var status = macro.default_state;
		var el = story.findContainingTiddler(container);
		$("[type=radio]", container).click(function(ev) {
			var btn = $(ev.target);
			tiddler.fields["server.page.revision"] = "false";
			if(btn.hasClass("isPrivate")) { // private button clicked.
				$(el).addClass("isPrivate").removeClass("isPublic");
				macro.setBag(el, privateBag, options);
			} else {
				$(el).addClass("isPublic").removeClass("isPrivate");
				macro.setBag(el, publicBag, options);
			}
		});
		if(!defaultValue) {
			defaultValue = macro.default_state == "public" ? publicBag : privateBag;
		}
		window.setTimeout(function() {
			macro.setBag(el, defaultValue, options);
		}, 100);
		// annoyingly this is needed as customFields are added to end of EditTemplate so are not present yet
		// and don't seem to respect any existing customFields.
	}
};

})(jQuery);
//}}}
<|endoftext|>


<commit_before>var win = Titanium.UI.currentWindow;
win.backgroundColor = '#13386c';

//
// BASE INDICATOR
//
var actInd = Titanium.UI.createActivityIndicator({
	bottom:10,
	height:50,
	width:50,
	style:Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN
});

var button0 = Titanium.UI.createButton({
	title:'Hide',
	height:35,
	width:130,
	top:10,
	right:20
});

button0.addEventListener('click', function()
{
	actInd.message = null;
	actInd.hide();
});

//
// BASIC ACTIVITY INDICATOR
//
var button1 = Titanium.UI.createButton({
	title:'Show (Basic)',
	height:35,
	width:130,
	top:10,
	left:20
});

button1.addEventListener('click', function()
{
	actInd.show();
});

//
// ACTIVITY INDICATOR (BIG)
//
var button2 = Titanium.UI.createButton({
	title:'Show Indicator (BIG)',
	height:35,
	width:200,
	top:55
});

button2.addEventListener('click', function()
{
	actInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.BIG;
	actInd.show();
});

//
// ACTIVITY INDICATOR (DARK)
//
var button3 = Titanium.UI.createButton({
	title:'Show Indicator (DARK)',
	height:35,
	width:200,
	top:100
});

button3.addEventListener('click', function()
{
	actInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.DARK;
	actInd.show();
});

//
// ACTIVITY INDICATOR (MESSAGE)
//
var button4 = Titanium.UI.createButton({
	title:'Show Indicator (Message)',
	height:35,
	width:200,
	top:145
});

button4.addEventListener('click', function()
{
	actInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN;
	actInd.font = {fontFamily:'Helvetica Neue', fontSize:15,fontWeight:'bold'};
	actInd.color = 'white';
	actInd.message = 'Loading...';
	actInd.width = 210;
	actInd.show();
});

//
// ACTIVITY INDICATOR (TOOLBAR)
//
var toolActInd = Titanium.UI.createActivityIndicator();

var button5 = Titanium.UI.createButton({
	title:'Show Indicator (Toolbar)',
	height:35,
	width:200,
	top:190
});

button5.addEventListener('click', function()
{
	toolActInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN;
	toolActInd.font = {fontFamily:'Helvetica Neue', fontSize:15,fontWeight:'bold'};
	toolActInd.color = 'white';
	toolActInd.message = 'Loading...';
	win.setToolbar([toolActInd],{animated:true});
	toolActInd.show();
	setTimeout(function()
	{
		toolActInd.hide();
		win.setToolbar(null,{animated:true});
	},3000);

});

//
// ACTIVITY INDICATOR (NAVBAR)
//
var navActInd = Titanium.UI.createActivityIndicator();

var button6 = Titanium.UI.createButton({
	title:'Show Indicator (Navbar)',
	height:35,
	width:200,
	top:235
});

button6.addEventListener('click', function()
{

	win.setRightNavButton(navActInd);
	navActInd.show();
	setTimeout(function()
	{
		navActInd.hide();
		win.setRightNavButton(null);

	},3000);

});

//
// ACTIVITY INDICATOR (TITLE CONTROL)
//
var button7 = Titanium.UI.createButton({
	title:'Show Indicator (Title)',
	height:35,
	width:200,
	top:280
});

button7.addEventListener('click', function()
{
	win.setTitleControl(actInd);
	actInd.show();

	setTimeout(function()
	{
		actInd.hide();
		win.setTitleControl(null);
		win.title = 'Activity Indicator';

	},3000);
});

win.add(actInd);

// add iphone elements
if (Titanium.Platform.name == 'iPhone OS')
{
	win.add(button1);
	win.add(button0);
	win.add(button2);
	win.add(button3);
	win.add(button4);
	win.add(button5);
	win.add(button6);
	win.add(button7);
}
else
{
	actInd.show();
	actInd.message = 'Loading...';
	setTimeout(function()
	{
		actInd.hide();
	},2000);
}
<commit_msg>[TIMOB-9489] Fix activityindicator sample<commit_after>var win = Titanium.UI.currentWindow;
win.backgroundColor = '#13386c';
var indicatorAdded = false
//
// BASE INDICATOR
//
var actInd = Titanium.UI.createActivityIndicator({
	bottom:10,
	height:30,
	width:30,
	style:Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN
});

var button0 = Titanium.UI.createButton({
	title:'Hide',
	height:35,
	width:130,
	top:10,
	right:20
});

button0.addEventListener('click', function()
{
	if(indicatorAdded)
	{
		actInd.message = null;
		actInd.width = 30;
		actInd.hide();
		win.remove(actInd);
		indicatorAdded = false
	}
});

//
// BASIC ACTIVITY INDICATOR
//
var button1 = Titanium.UI.createButton({
	title:'Show (Basic)',
	height:35,
	width:130,
	top:10,
	left:20
});

button1.addEventListener('click', function()
{
	actInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN;
	if(!indicatorAdded)
	{
		win.add(actInd);
		actInd.show();
		indicatorAdded = true;
	}
});

//
// ACTIVITY INDICATOR (BIG)
//
var button2 = Titanium.UI.createButton({
	title:'Show Indicator (BIG)',
	height:35,
	width:200,
	top:55
});

button2.addEventListener('click', function()
{
	actInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.BIG;
	if(!indicatorAdded)
	{
		win.add(actInd);
		actInd.show();
		indicatorAdded = true;
	}
});

//
// ACTIVITY INDICATOR (DARK)
//
var button3 = Titanium.UI.createButton({
	title:'Show Indicator (DARK)',
	height:35,
	width:200,
	top:100
});

button3.addEventListener('click', function()
{
	actInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.DARK;
	if(!indicatorAdded)
	{
		win.add(actInd);
		actInd.show();
		indicatorAdded = true;
	}
});

//
// ACTIVITY INDICATOR (MESSAGE)
//
var button4 = Titanium.UI.createButton({
	title:'Show Indicator (Message)',
	height:35,
	width:200,
	top:145
});

button4.addEventListener('click', function()
{
	actInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN;
	actInd.font = {fontFamily:'Helvetica Neue', fontSize:15,fontWeight:'bold'};
	actInd.color = 'white';
	actInd.message = 'Loading...';
	actInd.width = 210;
	if(!indicatorAdded)
	{
		win.add(actInd);
		actInd.show();
		indicatorAdded = true;
	}
});

//
// ACTIVITY INDICATOR (TOOLBAR)
//
var toolActInd = Titanium.UI.createActivityIndicator();

var button5 = Titanium.UI.createButton({
	title:'Show Indicator (Toolbar)',
	height:35,
	width:200,
	top:190
});

button5.addEventListener('click', function()
{
	toolActInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN;
	toolActInd.font = {fontFamily:'Helvetica Neue', fontSize:15,fontWeight:'bold'};
	toolActInd.color = 'white';
	toolActInd.message = 'Loading...';
	win.setToolbar([toolActInd],{animated:true});
	toolActInd.show();
	setTimeout(function()
	{
		win.setToolbar(null,{animated:true});
	},3000);

});

//
// ACTIVITY INDICATOR (NAVBAR)
//
var navActInd = Titanium.UI.createActivityIndicator();

var button6 = Titanium.UI.createButton({
	title:'Show Indicator (Navbar)',
	height:35,
	width:200,
	top:235
});

button6.addEventListener('click', function()
{

	win.setRightNavButton(navActInd);
	navActInd.show();
	setTimeout(function()
	{
		win.setRightNavButton(null);
	},3000);

});

//
// ACTIVITY INDICATOR (TITLE CONTROL)
//
var button7 = Titanium.UI.createButton({
	title:'Show Indicator (Title)',
	height:35,
	width:200,
	top:280
});

button7.addEventListener('click', function()
{
	if(indicatorAdded)
	{
		actInd.message = null;
		actInd.width = 30;
		actInd.hide();
		win.remove(actInd);
	}
	win.setTitleControl(actInd);
	actInd.show();
	indicatorAdded = true;
	button0.enabled = false;
	button4.enabled = false;
	setTimeout(function()
	{
		actInd.hide();
		win.setTitleControl(null);
		indicatorAdded = false;
		button0.enabled = true;
		button4.enabled = true;
		win.title = 'Activity Indicator';

	},3000);
});

// add iphone elements
if (Titanium.Platform.name == 'iPhone OS')
{
	win.add(button1);
	win.add(button0);
	win.add(button2);
	win.add(button3);
	win.add(button4);
	win.add(button5);
	win.add(button6);
	win.add(button7);
}
else
{
	win.add(actInd);
	actInd.show();
	actInd.message = 'Loading...';
	setTimeout(function()
	{
		actInd.hide();
	},2000);
}
<|endoftext|>


<commit_before>(function(){
    $(document).foundation();

    _post_api_url         = '/post';

    $new_post_form        = $('#new_post');
    _new_post_field       = '.post__new_post';
    _new_post__size_limit = 140;

    var $make_request = function (URL, METHOD, DATA, CALLBACK) {
        $.ajax({
            url: URL,
            type: METHOD,
            data: DATA,
            success: CALLBACK,
            fail: function(err){
                CALLBACK({'status': 'failed', 'error': err})
            }
        });
    }

    var $api = {
        'add' : function (DATA) {
            $make_request(_post_api_url, 'POST', DATA, (data) => console.log(data))
        },

        'get' : function (ID) {
            _URL = _post_api_url;
            if(ID && typeof ID == 'number')
                _URL += '/' + ID;

            $make_request(_URL, 'GET', {}, (data) => console.log(data))
        }
    }

    $new_post_form.submit(function (event) {
        event.preventDefault();
        var content = $(_new_post_field, this).val();

        if(content && content.length <= _new_post__size_limit){
            $api.add({'text': content})
        }
    })
})()
<commit_msg>Replaced $.ajax with native fetch<commit_after>(function(){
    $(document).foundation();

    _post_api_url         = '/post';

    $new_post_form        = $('#new_post');
    _new_post_field       = '.post__new_post';
    _new_post__size_limit = 140;

    var $make_request = function (URL, METHOD, DATA, CALLBACK) {

        fetch(URL, {
            method  : METHOD,
            credentials : 'same-origin',
            headers : {
                'Accept'       : 'application/json',
                'Content-Type' : 'application/json'
            },
            body    : JSON.stringify(DATA)
        }).then(function (response) {
            return response.json()
        }).then(function (json) {
            CALLBACK(json)
        }).catch(function (err) {
            CALLBACK({'status': 'failed', 'error': err})
        })
    }

    var $api = {
        'add' : function (DATA) {
            $make_request(_post_api_url, 'POST', DATA, (data) => console.log(data));
        },

        'get' : function (ID) {
            _URL = _post_api_url;
            if(ID && typeof ID == 'number')
                _URL += '/' + ID;

            $make_request(_URL, 'GET', {}, (data) => console.log(data));
        }
    }

    $new_post_form.submit(function (event) {
        event.preventDefault();
        var content = $(_new_post_field, this).val();

        if(content && content.length <= _new_post__size_limit)
            $api.add({'text': content});
    })
})()
<|endoftext|>


<commit_before>define(['angular'], function() {
    var research = {
        actions: {
            list: new Array(),
            bought: new Array(),
            upTypes: 10
        },

        getCurrent: function(type, Index) {
            var index;

            switch (type) {
                case 0:
                    for (var i = 0; i < this.actions.list.length; i++) {
                        if (!this.actions.bought[i] && this.actions.list[i].upType == Index) {
                            index = i;
                            i = this.actions.list.length;
                        };
                    };
                    break;
                case 1:
                    break;
            };

            return index;
        },

        getCheapest: function(type) {
            var index;
            var cheapest;

            switch (type) {
                case 0:
                    cheapest = 1e308; // max value in JS by default
                    for (var i = 0; i < this.actions.list.length; i++) {
                        if (!this.actions.bought[i] && this.actions.list[i].price < cheapest) {
                            cheapest = this.actions.list[i].price;
                            index = i;
                        };
                    };
                    break;
                case 1:
                    break;
            };

            return index;
        },

        countBought: function(type) {
            var bought = 0;

            switch (type) {
                case 0:
                    for (var i = 0; i < this.actions.bought.length; i++) {
                        if (this.actions.bought[i])
                            bought++;
                    };
                    break;
                case 1:
                    break;
            };

            return bought;
        },

        create: function(name, desc, price, str, who, effect, otherStr, otherWho, otherEffect, type, upType) {
            this.name = name;
            this.desc = desc;
            this.price = price;
            this.str = str;
            this.who = who;
            this.effect = effect;
            this.otherWho = otherWho;
            this.otherStr = otherStr;
            this.otherEffect = otherEffect;
            this.type = type;
            this.upType = upType;
        },

        buy: function(type, upgradeIndex) {
            switch (type) {
                case 0:
                    var price = this.actions.list[upgradeIndex].price;

                    var what = this.actions.list[upgradeIndex].str;
                    var whoInWhat = this.actions.list[upgradeIndex].who;
                    var effect = this.actions.list[upgradeIndex].effect;

                    var otherWhat = this.actions.list[upgradeIndex].otherStr;
                    var otherWhoInWhat = this.actions.list[upgradeIndex].otherWho;
                    var otherEffect = this.actions.list[upgradeIndex].otherEffect;

                    if (game.money >= price && !this.actions.bought[upgradeIndex]) {
                        game.money -= price;
                        this.actions.bought[upgradeIndex] = true;

                        if (whoInWhat !== 'n') {
                            var value = window["game"]["actions"][what][whoInWhat];
                            window["game"]["actions"][what][whoInWhat] = eval(value + effect);
                        } else {
                            var value = window["game"]["actions"][what];
                            window["game"]["actions"][what] = eval(value + effect);
                        };

                        if (otherWhat && otherWhoInWhat && otherEffect !== 'undefined') {
                            if (otherWhoInWhat !== 'n') {
                                var value = window["game"]["actions"][what][otherWhoInWhat];
                                window["game"]["actions"][otherWhat][otherWhoInWhat] = eval(value + otherEffect);
                            } else {
                                var value = window["game"]["actions"][otherWhat];
                                window["game"]["actions"][otherWhat] = eval(value + otherEffect);
                            };
                        };
                    };

                    game.actions.display();
                    break;
                case 1: // for production research upgrades
                    break;
            };

            this.display();
        },

        quickbuy: function(type, upgradeIndex) {
            var indexOfCheapest = this.getCheapest(type);
            return this.buy(type, indexOfCheapest);
        },

        display: function() {
            for (var i = 0; i < this.actions.upTypes; i++) {
                var index = game.research.getCurrent(0, i);
                var bought = this.countBought(0);
                var total = this.actions.bought.length;
                var html = {
                    name: this.actions.list[index].name,
                    desc: this.actions.list[index].desc,
                    price: this.actions.list[index].price
                };

                $("#research-actions-total").html("(" + bought + "/" + total + ")");
                $("#research-actions-upgrade-" + (i + 1)).html('' + html.name + 'Cost $' + fix(html.price, 2) + '
' + html.desc);
                $("#research-actions-upgrade-" + (i + 1)).attr('onclick', 'game.research.buy(0, ' + index + ');');
            };

            var indexOfCheapest = game.research.getCheapest(0);
            var htmlOfCheapest = {
                name: this.actions.list[indexOfCheapest].name,
                desc: this.actions.list[indexOfCheapest].desc,
                price: this.actions.list[indexOfCheapest].price
            };

            $("#action-quickbuy-button").html(htmlOfCheapest.name + " ($" + fix(htmlOfCheapest.price, 0) + ")");
        },

        varInit: function() {
            this.actions.list = [ // todo: fix when buying latest upgrade of each upType
                new this.create("Shooting I", "Shooting reward x3Reputation reward x3", 250000, "rewardMultiplier", "0", "*3", 'reputationMultiplier', "0", "*3", 0, 0),
                new this.create("Shooting II", "Shooting reward x3Reputation reward x3", 1000000000000, "rewardMultiplier", "0", "*3", 'reputationMultiplier', "0", "*3", 0, 0),

                new this.create("Fight club I", "Fight club reward x3Reputation reward x3", 750000, "rewardMultiplier", "1", "*3", 'reputationMultiplier', "1", "*3", 0, 1),
                new this.create("Fight club II", "Fight club reward x3Reputation reward x3", 25000000000000, "rewardMultiplier", "1", "*3", 'reputationMultiplier', "1", "*3", 0, 1),

                new this.create("Pickpocket I", "Pickpocket reward x3Reputation reward x3", 2500000, "rewardMultiplier", "2", "*3", 'reputationMultiplier', "2", "*3", 0, 2),
                new this.create("Pickpocket II", "Pickpocket reward x3Reputation reward x3", 50000000000000, "rewardMultiplier", "2", "*3", 'reputationMultiplier', "2", "*3", 0, 2),

                new this.create("Scammer I", "Scam reward x3Reputation reward x3", 5000000, "rewardMultiplier", "3", "*3", 'reputationMultiplier', "3", "*3", 0, 3),
                new this.create("Scammer II", "Scam reward x3Reputation reward x3", 100000000000000, "rewardMultiplier", "3", "*3", 'reputationMultiplier', "3", "*3", 0, 3),

                new this.create("Steal car I", "Steal car reward x3Reputation reward x3", 25000000, "rewardMultiplier", "4", "*3", 'reputationMultiplier', "4", "*3", 0, 4),
                new this.create("Steal car II", "Steal car reward x3Reputation reward x3", 750000000000000, "rewardMultiplier", "4", "*3", 'reputationMultiplier', "4", "*3", 0, 4),

                new this.create("Jewelry robbery I", "Jewelry robbery reward x3Reputation reward x3", 500000000, "rewardMultiplier", "5", "*3", 'reputationMultiplier', "5", "*3", 0, 5),
                new this.create("Jewelry robbery II", "Jewelry robbery reward x3Reputation reward x3", 2500000000000000, "rewardMultiplier", "5", "*3", 'reputationMultiplier', "5", "*3", 0, 5),

                new this.create("Hacking I", "Hacking reward x3Reputation reward x3", 10000000000, "rewardMultiplier", "6", "*3", 'reputationMultiplier', "6", "*3", 0, 6),
                new this.create("Hacking II", "Hacking reward x3Reputation reward x3", 10000000000000000, "rewardMultiplier", "6", "*3", 'reputationMultiplier', "6", "*3", 0, 6),

                new this.create("Arms dealer I", "Arms sales reward x3Reputation reward x3", 50000000000, "rewardMultiplier", "7", "*3", 'reputationMultiplier', "7", "*3", 0, 7),
                new this.create("Arms dealer II", "Arms sales reward x3Reputation reward x3", 20000000000000000, "rewardMultiplier", "7", "*3", 'reputationMultiplier', "7", "*3", 0, 7),

                new this.create("Dealer I", "Drugs sales reward x3Reputation reward x3", 50000000000, "rewardMultiplier", "8", "*3", 'reputationMultiplier', "8", "*3", 0, 8),
                new this.create("Dealer II", "Drugs sales reward x3Reputation reward x3", 20000000000000000, "rewardMultiplier", "8", "*3", 'reputationMultiplier', "8", "*3", 0, 8),

                new this.create("All actions I", "All actions reward x3Reputation reward x3", 250000000000, "totalRewardMultiplier", "n", "*3", 'totalReputationMultiplier', "n", "*3", 0, 9),
                new this.create("All actions II", "All actions reward x3Reputation reward x3", 75000000000000000, "totalRewardMultiplier", "n", "*3", 'totalReputationMultiplier', "n", "*3", 0, 9)
            ];

            for (var i = 0; i < this.actions.list.length; i++) {
                this.actions.bought.push(false);
            };
        },

        domInit: function() {
            for (var i = 0; i < this.actions.upTypes; i++) {
                $("#research-actions").append('

');
                $("#research-actions-upgrade-" + (i + 1)).attr('onclick', 'game.research.buy(0, ' + i + ');');
            };

            var height = $("body").height();
            $("#research-actions").css({
                'max-height': (height + 200) + 'px',
                'overflow-y': 'auto'
            })

            this.display();
        },

        angularInit: function() {
            this.domInit();
        },

        init: function() {
            this.varInit();

            window["game"]["research"] = this;
            log("Research center init.");
        }
    };

    return research.init();
});
<commit_msg>Fix for issue "Failed loading save game #6"<commit_after>define(['angular'], function() {
    var research = {
        actions: {
            list: new Array(),
            bought: new Array(),
            upTypes: 10
        },

        getCurrent: function(type, Index) {
            var index;

            switch (type) {
                case 0:
                    for (var i = 0; i < this.actions.list.length; i++) {
                        if (!this.actions.bought[i] && this.actions.list[i].upType == Index) {
                            index = i;
                            i = this.actions.list.length;
                        };
                    };
                    break;
                case 1:
                    break;
            };

            return index;
        },

        getCheapest: function(type) {
            var index;
            var cheapest;

            switch (type) {
                case 0:
                    cheapest = 1e308; // max value in JS by default
                    for (var i = 0; i < this.actions.list.length; i++) {
                        if (!this.actions.bought[i] && this.actions.list[i].price < cheapest) {
                            cheapest = this.actions.list[i].price;
                            index = i;
                        };
                    };
                    break;
                case 1:
                    break;
            };

            return index;
        },

        countBought: function(type) {
            var bought = 0;

            switch (type) {
                case 0:
                    for (var i = 0; i < this.actions.bought.length; i++) {
                        if (this.actions.bought[i])
                            bought++;
                    };
                    break;
                case 1:
                    break;
            };

            return bought;
        },

        create: function(name, desc, price, str, who, effect, otherStr, otherWho, otherEffect, type, upType) {
            this.name = name;
            this.desc = desc;
            this.price = price;
            this.str = str;
            this.who = who;
            this.effect = effect;
            this.otherWho = otherWho;
            this.otherStr = otherStr;
            this.otherEffect = otherEffect;
            this.type = type;
            this.upType = upType;
        },

        buy: function(type, upgradeIndex) {
            switch (type) {
                case 0:
                    var price = this.actions.list[upgradeIndex].price;

                    var what = this.actions.list[upgradeIndex].str;
                    var whoInWhat = this.actions.list[upgradeIndex].who;
                    var effect = this.actions.list[upgradeIndex].effect;

                    var otherWhat = this.actions.list[upgradeIndex].otherStr;
                    var otherWhoInWhat = this.actions.list[upgradeIndex].otherWho;
                    var otherEffect = this.actions.list[upgradeIndex].otherEffect;

                    if (game.money >= price && !this.actions.bought[upgradeIndex]) {
                        game.money -= price;
                        this.actions.bought[upgradeIndex] = true;

                        if (whoInWhat !== 'n') {
                            var value = window["game"]["actions"][what][whoInWhat];
                            window["game"]["actions"][what][whoInWhat] = eval(value + effect);
                        } else {
                            var value = window["game"]["actions"][what];
                            window["game"]["actions"][what] = eval(value + effect);
                        };

                        if (otherWhat && otherWhoInWhat && otherEffect !== 'undefined') {
                            if (otherWhoInWhat !== 'n') {
                                var value = window["game"]["actions"][what][otherWhoInWhat];
                                window["game"]["actions"][otherWhat][otherWhoInWhat] = eval(value + otherEffect);
                            } else {
                                var value = window["game"]["actions"][otherWhat];
                                window["game"]["actions"][otherWhat] = eval(value + otherEffect);
                            };
                        };
                    };

                    game.actions.display();
                    break;
                case 1: // for production research upgrades
                    break;
            };

            this.display();
        },

        quickbuy: function(type, upgradeIndex) {
            var indexOfCheapest = this.getCheapest(type);
            return this.buy(type, indexOfCheapest);
        },

        display: function() {
            for (var i = 0; i < this.actions.upTypes; i++) {
                var index = game.research.getCurrent(0, i);
                var bought = this.countBought(0);
                var total = this.actions.bought.length;
                if (typeof this.actions.list[index] !== "undefined") {
                    var html = {
                            name: this.actions.list[index].name,
                            desc: this.actions.list[index].desc,
                            price: this.actions.list[index].price
                        };
                    $("#research-actions-total").html("(" + bought + "/" + total + ")");
                    $("#research-actions-upgrade-" + (i + 1)).html('' + html.name + 'Cost $' + fix(html.price, 2) + '
' + html.desc);
                    $("#research-actions-upgrade-" + (i + 1)).attr('onclick', 'game.research.buy(0, ' + index + ');');
                } else {
                    $("#research-actions-upgrade-" + (i + 1)).html('All available Upgrades baught!');
                }
            };

            var indexOfCheapest = game.research.getCheapest(0);
            var htmlOfCheapest = {
                name: this.actions.list[indexOfCheapest].name,
                desc: this.actions.list[indexOfCheapest].desc,
                price: this.actions.list[indexOfCheapest].price
            };

            $("#action-quickbuy-button").html(htmlOfCheapest.name + " ($" + fix(htmlOfCheapest.price, 0) + ")");
        },

        varInit: function() {
            this.actions.list = [ // todo: fix when buying latest upgrade of each upType
                new this.create("Shooting I", "Shooting reward x3Reputation reward x3", 250000, "rewardMultiplier", "0", "*3", 'reputationMultiplier', "0", "*3", 0, 0),
                new this.create("Shooting II", "Shooting reward x3Reputation reward x3", 1000000000000, "rewardMultiplier", "0", "*3", 'reputationMultiplier', "0", "*3", 0, 0),

                new this.create("Fight club I", "Fight club reward x3Reputation reward x3", 750000, "rewardMultiplier", "1", "*3", 'reputationMultiplier', "1", "*3", 0, 1),
                new this.create("Fight club II", "Fight club reward x3Reputation reward x3", 25000000000000, "rewardMultiplier", "1", "*3", 'reputationMultiplier', "1", "*3", 0, 1),

                new this.create("Pickpocket I", "Pickpocket reward x3Reputation reward x3", 2500000, "rewardMultiplier", "2", "*3", 'reputationMultiplier', "2", "*3", 0, 2),
                new this.create("Pickpocket II", "Pickpocket reward x3Reputation reward x3", 50000000000000, "rewardMultiplier", "2", "*3", 'reputationMultiplier', "2", "*3", 0, 2),

                new this.create("Scammer I", "Scam reward x3Reputation reward x3", 5000000, "rewardMultiplier", "3", "*3", 'reputationMultiplier', "3", "*3", 0, 3),
                new this.create("Scammer II", "Scam reward x3Reputation reward x3", 100000000000000, "rewardMultiplier", "3", "*3", 'reputationMultiplier', "3", "*3", 0, 3),

                new this.create("Steal car I", "Steal car reward x3Reputation reward x3", 25000000, "rewardMultiplier", "4", "*3", 'reputationMultiplier', "4", "*3", 0, 4),
                new this.create("Steal car II", "Steal car reward x3Reputation reward x3", 750000000000000, "rewardMultiplier", "4", "*3", 'reputationMultiplier', "4", "*3", 0, 4),

                new this.create("Jewelry robbery I", "Jewelry robbery reward x3Reputation reward x3", 500000000, "rewardMultiplier", "5", "*3", 'reputationMultiplier', "5", "*3", 0, 5),
                new this.create("Jewelry robbery II", "Jewelry robbery reward x3Reputation reward x3", 2500000000000000, "rewardMultiplier", "5", "*3", 'reputationMultiplier', "5", "*3", 0, 5),

                new this.create("Hacking I", "Hacking reward x3Reputation reward x3", 10000000000, "rewardMultiplier", "6", "*3", 'reputationMultiplier', "6", "*3", 0, 6),
                new this.create("Hacking II", "Hacking reward x3Reputation reward x3", 10000000000000000, "rewardMultiplier", "6", "*3", 'reputationMultiplier', "6", "*3", 0, 6),

                new this.create("Arms dealer I", "Arms sales reward x3Reputation reward x3", 50000000000, "rewardMultiplier", "7", "*3", 'reputationMultiplier', "7", "*3", 0, 7),
                new this.create("Arms dealer II", "Arms sales reward x3Reputation reward x3", 20000000000000000, "rewardMultiplier", "7", "*3", 'reputationMultiplier', "7", "*3", 0, 7),

                new this.create("Dealer I", "Drugs sales reward x3Reputation reward x3", 50000000000, "rewardMultiplier", "8", "*3", 'reputationMultiplier', "8", "*3", 0, 8),
                new this.create("Dealer II", "Drugs sales reward x3Reputation reward x3", 20000000000000000, "rewardMultiplier", "8", "*3", 'reputationMultiplier', "8", "*3", 0, 8),

                new this.create("All actions I", "All actions reward x3Reputation reward x3", 250000000000, "totalRewardMultiplier", "n", "*3", 'totalReputationMultiplier', "n", "*3", 0, 9),
                new this.create("All actions II", "All actions reward x3Reputation reward x3", 75000000000000000, "totalRewardMultiplier", "n", "*3", 'totalReputationMultiplier', "n", "*3", 0, 9)
            ];

            for (var i = 0; i < this.actions.list.length; i++) {
                this.actions.bought.push(false);
            };
        },

        domInit: function() {
            for (var i = 0; i < this.actions.upTypes; i++) {
                $("#research-actions").append('

');
                $("#research-actions-upgrade-" + (i + 1)).attr('onclick', 'game.research.buy(0, ' + i + ');');
            };

            var height = $("body").height();
            $("#research-actions").css({
                'max-height': (height + 200) + 'px',
                'overflow-y': 'auto'
            })

            this.display();
        },

        angularInit: function() {
            this.domInit();
        },

        init: function() {
            this.varInit();

            window["game"]["research"] = this;
            log("Research center init.");
        }
    };

    return research.init();
});
<|endoftext|>


<commit_before>define([ "Phase", "PlayFormat", "Ship", "Team", "process/Selector" ],
        function(Phase, PlayFormat, Ship, Team, Selector)
        {
            "use strict";
            var Connector = {};

            Connector.MessageAreaUI =
            {
                mapStateToProps: function(state, ownProps)
                {
                    var userMessage = state.userMessage;

                    return (
                    {
                        userMessage: userMessage,
                    });
                },
            };

            Connector.PilotCardUI =
            {
                mapStateToProps: function(state, ownProps)
                {
                    InputValidator.validateNotNull("token", ownProps.token);
                    InputValidator.validateNotNull("isCompact", ownProps.isCompact);

                    var token = ownProps.token;
                    var isCompact = ownProps.isCompact;

                    return (
                    {
                        key: token.id(),
                        isCompact: isCompact,
                        initialToken: token
                    });
                },
            };

            Connector.PilotsUI =
            {
                mapStateToProps: function(state, ownProps)
                {
                    InputValidator.validateNotNull("environment", ownProps.environment);
                    InputValidator.validateNotNull("team", ownProps.team);

                    var environment = ownProps.environment;
                    var team = ownProps.team;
                    var tokens = environment.getTokensForTeam(team);
                    tokens.sort(function(token0, token1)
                    {
                        var answer = token1.pilotSkillValue() - token0.pilotSkillValue();

                        if (answer === 0)
                        {
                            answer = token0.id() - token1.id();
                        }

                        return answer;
                    });

                    return (
                    {
                        tokens: tokens,
                    });
                },
            };

            Connector.PlayAreaUI =
            {
                EXPLOSION_PHASES: [ Phase.COMBAT_DEAL_DAMAGE ],
                LASER_AUDIO_PHASES: [ Phase.COMBAT_ROLL_ATTACK_DICE, ],
                LASER_BEAM_PHASES: [ Phase.COMBAT_DECLARE_TARGET, Phase.COMBAT_ROLL_ATTACK_DICE,
                        Phase.COMBAT_MODIFY_ATTACK_DICE, Phase.COMBAT_ROLL_DEFENSE_DICE,
                        Phase.COMBAT_MODIFY_DEFENSE_DICE, Phase.COMBAT_COMPARE_RESULTS, Phase.COMBAT_DEAL_DAMAGE, ],
                MANEUVER_PHASES: [ Phase.ACTIVATION_REVEAL_DIAL, Phase.ACTIVATION_SET_TEMPLATE,
                        Phase.ACTIVATION_EXECUTE_MANEUVER, Phase.ACTIVATION_CHECK_PILOT_STRESS,
                        Phase.ACTIVATION_CLEAN_UP, ],

                mapStateToProps: function(state, ownProps)
                {
                    LOGGER.trace("Connector.PlayAreaUI.mapStateToProps()");

                    InputValidator.validateNotNull("environment", ownProps.environment);

                    var environment = ownProps.environment;
                    var scale = state.playAreaScale;
                    var image = (state.playFormatKey === PlayFormat.STANDARD ? "pia13845.jpg"
                            : "horsehead_nebula_02092008.jpg");
                    var width = (state.playFormatKey === PlayFormat.STANDARD ? 915 : 1830);
                    var tokenPositions = environment.createTokenPositions();

                    var answer =
                    {
                        playFormatKey: state.playFormatKey,
                        scale: state.playAreaScale,
                        width: scale * width,
                        height: scale * 915,
                        image: image,
                        tokenPositions: tokenPositions,
                    };

                    var activeToken = Selector.activeToken(state);
                    LOGGER.debug("activeToken = " + activeToken);

                    if (activeToken)
                    {
                        checkManeuver(state, activeToken, answer);
                        checkLaserBeam(state, activeToken, answer);
                        checkExplosion(state, activeToken, answer);
                    }

                    return answer;

                    function checkExplosion(state, activeToken, answer)
                    {
                        if (Connector.PlayAreaUI.EXPLOSION_PHASES.vizziniContains(state.phaseKey))
                        {
                            var combatAction = activeToken.combatState().combatAction();

                            if (combatAction)
                            {
                                var attacker = combatAction.attacker();
                                var fromPosition = combatAction.attackerPosition();

                                if (fromPosition)
                                {
                                    var toPosition = combatAction.defenderPosition();

                                    if (toPosition)
                                    {
                                        var isPrimary = combatAction.weapon().isPrimary();
                                        var teamColor = attacker.pilot().shipTeam.team.color;

                                        var defender = combatAction.defender();

                                        if (defender && defender.isDestroyed())
                                        {
                                            LOGGER.debug("setting explosion data");

                                            answer.explosion =
                                            {
                                                position: toPosition,
                                                shipBase: defender.pilot().shipTeam.ship.shipBase,
                                                audioClip: document.getElementById("explosionAudio"),
                                            };
                                        }
                                    }
                                }
                            }
                        }
                    }

                    function checkLaserBeam(state, activeToken, answer)
                    {
                        if (Connector.PlayAreaUI.LASER_BEAM_PHASES.vizziniContains(state.phaseKey))
                        {
                            var combatAction = activeToken.combatState().combatAction();
                            LOGGER.debug("combatAction = " + combatAction);

                            if (combatAction)
                            {
                                var attacker = combatAction.attacker();
                                var fromPosition = combatAction.attackerPosition();
                                LOGGER.debug("fromPosition = " + fromPosition);

                                if (fromPosition)
                                {
                                    var defender = combatAction.defender();
                                    var toPosition = combatAction.defenderPosition();
                                    LOGGER.debug("toPosition = " + toPosition);

                                    if (toPosition && !defender.isDestroyed())
                                    {
                                        var isPrimary = combatAction.weapon().isPrimary();
                                        var teamColor = attacker.pilot().shipTeam.team.color;
                                        var audioClip;

                                        if (Connector.PlayAreaUI.LASER_AUDIO_PHASES.vizziniContains(state.phaseKey))
                                        {
                                            audioClip = getLaserAudioClip(attacker);
                                        }
                                        LOGGER.debug("setting laser beam data");

                                        answer.laserBeam =
                                        {
                                            fromPosition: fromPosition,
                                            toPosition: toPosition,
                                            isPrimary: isPrimary,
                                            teamColor: teamColor,
                                            audioClip: audioClip,
                                        };
                                    }
                                }
                            }
                        }
                    }

                    function checkManeuver(state, activeToken, answer)
                    {
                        if (Connector.PlayAreaUI.MANEUVER_PHASES.vizziniContains(state.phaseKey))
                        {
                            var maneuverAction = activeToken.activationState().maneuverAction();

                            if (maneuverAction)
                            {
                                var maneuver = maneuverAction.maneuver();
                                var fromPosition = maneuverAction.fromPosition();
                                var shipBase = maneuverAction.shipBase();
                                LOGGER.debug("setting maneuver data");

                                answer.maneuver =
                                {
                                    maneuver: maneuver,
                                    fromPosition: fromPosition,
                                    shipBase: shipBase,
                                };
                            }
                        }
                    }

                    function getLaserAudioClip(token)
                    {
                        var answer;

                        var shipKey = token.pilot().shipTeam.shipKey;

                        if (shipKey === Ship.YT_1300 || shipKey === Ship.YT_2400)
                        {
                            answer = document.getElementById("millenniumFalconLaserAudio");
                        }
                        else if (shipKey === Ship.FIRESPRAY_31)
                        {
                            answer = document.getElementById("slave1LaserAudio");
                        }
                        else
                        {
                            var teamKey = token.pilot().shipTeam.teamKey;

                            if (teamKey === Team.IMPERIAL)
                            {
                                answer = document.getElementById("tieFighterLaserAudio");
                            }
                            else
                            {
                                answer = document.getElementById("xWingLaserAudio");
                            }
                        }

                        return answer;
                    }
                },
            };

            Connector.StatusBarUI =
            {
                mapStateToProps: function(state, ownProps)
                {
                    InputValidator.validateNotNull("environment", ownProps.environment);

                    var environment = ownProps.environment;
                    var activeToken = environment.getTokenById(state.activeTokenId);
                    var activeShipName = (activeToken ? activeToken.name() : "");

                    return (
                    {
                        round: state.round,
                        phaseKey: state.phaseKey,
                        activeShipName: activeShipName,
                    });
                },
            };

            if (Object.freeze)
            {
                Object.freeze(Connector);
            }

            return Connector;
        });
<commit_msg>Changed so that isCompact is optional for PilotCardUI.<commit_after>define([ "Phase", "PlayFormat", "Ship", "Team", "process/Selector" ],
        function(Phase, PlayFormat, Ship, Team, Selector)
        {
            "use strict";
            var Connector = {};

            Connector.MessageAreaUI =
            {
                mapStateToProps: function(state, ownProps)
                {
                    var userMessage = state.userMessage;

                    return (
                    {
                        userMessage: userMessage,
                    });
                },
            };

            Connector.PilotCardUI =
            {
                mapStateToProps: function(state, ownProps)
                {
                    InputValidator.validateNotNull("token", ownProps.token);
                    // isCompact is optional.

                    var token = ownProps.token;
                    var isCompact = ownProps.isCompact;

                    return (
                    {
                        key: token.id(),
                        isCompact: isCompact,
                        initialToken: token
                    });
                },
            };

            Connector.PilotsUI =
            {
                mapStateToProps: function(state, ownProps)
                {
                    InputValidator.validateNotNull("environment", ownProps.environment);
                    InputValidator.validateNotNull("team", ownProps.team);

                    var environment = ownProps.environment;
                    var team = ownProps.team;
                    var tokens = environment.getTokensForTeam(team);
                    tokens.sort(function(token0, token1)
                    {
                        var answer = token1.pilotSkillValue() - token0.pilotSkillValue();

                        if (answer === 0)
                        {
                            answer = token0.id() - token1.id();
                        }

                        return answer;
                    });

                    return (
                    {
                        tokens: tokens,
                    });
                },
            };

            Connector.PlayAreaUI =
            {
                EXPLOSION_PHASES: [ Phase.COMBAT_DEAL_DAMAGE ],
                LASER_AUDIO_PHASES: [ Phase.COMBAT_ROLL_ATTACK_DICE, ],
                LASER_BEAM_PHASES: [ Phase.COMBAT_DECLARE_TARGET, Phase.COMBAT_ROLL_ATTACK_DICE,
                        Phase.COMBAT_MODIFY_ATTACK_DICE, Phase.COMBAT_ROLL_DEFENSE_DICE,
                        Phase.COMBAT_MODIFY_DEFENSE_DICE, Phase.COMBAT_COMPARE_RESULTS, Phase.COMBAT_DEAL_DAMAGE, ],
                MANEUVER_PHASES: [ Phase.ACTIVATION_REVEAL_DIAL, Phase.ACTIVATION_SET_TEMPLATE,
                        Phase.ACTIVATION_EXECUTE_MANEUVER, Phase.ACTIVATION_CHECK_PILOT_STRESS,
                        Phase.ACTIVATION_CLEAN_UP, ],

                mapStateToProps: function(state, ownProps)
                {
                    LOGGER.trace("Connector.PlayAreaUI.mapStateToProps()");

                    InputValidator.validateNotNull("environment", ownProps.environment);

                    var environment = ownProps.environment;
                    var scale = state.playAreaScale;
                    var image = (state.playFormatKey === PlayFormat.STANDARD ? "pia13845.jpg"
                            : "horsehead_nebula_02092008.jpg");
                    var width = (state.playFormatKey === PlayFormat.STANDARD ? 915 : 1830);
                    var tokenPositions = environment.createTokenPositions();

                    var answer =
                    {
                        playFormatKey: state.playFormatKey,
                        scale: state.playAreaScale,
                        width: scale * width,
                        height: scale * 915,
                        image: image,
                        tokenPositions: tokenPositions,
                    };

                    var activeToken = Selector.activeToken(state);
                    LOGGER.debug("activeToken = " + activeToken);

                    if (activeToken)
                    {
                        checkManeuver(state, activeToken, answer);
                        checkLaserBeam(state, activeToken, answer);
                        checkExplosion(state, activeToken, answer);
                    }

                    return answer;

                    function checkExplosion(state, activeToken, answer)
                    {
                        if (Connector.PlayAreaUI.EXPLOSION_PHASES.vizziniContains(state.phaseKey))
                        {
                            var combatAction = activeToken.combatState().combatAction();

                            if (combatAction)
                            {
                                var attacker = combatAction.attacker();
                                var fromPosition = combatAction.attackerPosition();

                                if (fromPosition)
                                {
                                    var toPosition = combatAction.defenderPosition();

                                    if (toPosition)
                                    {
                                        var isPrimary = combatAction.weapon().isPrimary();
                                        var teamColor = attacker.pilot().shipTeam.team.color;

                                        var defender = combatAction.defender();

                                        if (defender && defender.isDestroyed())
                                        {
                                            LOGGER.debug("setting explosion data");

                                            answer.explosion =
                                            {
                                                position: toPosition,
                                                shipBase: defender.pilot().shipTeam.ship.shipBase,
                                                audioClip: document.getElementById("explosionAudio"),
                                            };
                                        }
                                    }
                                }
                            }
                        }
                    }

                    function checkLaserBeam(state, activeToken, answer)
                    {
                        if (Connector.PlayAreaUI.LASER_BEAM_PHASES.vizziniContains(state.phaseKey))
                        {
                            var combatAction = activeToken.combatState().combatAction();
                            LOGGER.debug("combatAction = " + combatAction);

                            if (combatAction)
                            {
                                var attacker = combatAction.attacker();
                                var fromPosition = combatAction.attackerPosition();
                                LOGGER.debug("fromPosition = " + fromPosition);

                                if (fromPosition)
                                {
                                    var defender = combatAction.defender();
                                    var toPosition = combatAction.defenderPosition();
                                    LOGGER.debug("toPosition = " + toPosition);

                                    if (toPosition && !defender.isDestroyed())
                                    {
                                        var isPrimary = combatAction.weapon().isPrimary();
                                        var teamColor = attacker.pilot().shipTeam.team.color;
                                        var audioClip;

                                        if (Connector.PlayAreaUI.LASER_AUDIO_PHASES.vizziniContains(state.phaseKey))
                                        {
                                            audioClip = getLaserAudioClip(attacker);
                                        }
                                        LOGGER.debug("setting laser beam data");

                                        answer.laserBeam =
                                        {
                                            fromPosition: fromPosition,
                                            toPosition: toPosition,
                                            isPrimary: isPrimary,
                                            teamColor: teamColor,
                                            audioClip: audioClip,
                                        };
                                    }
                                }
                            }
                        }
                    }

                    function checkManeuver(state, activeToken, answer)
                    {
                        if (Connector.PlayAreaUI.MANEUVER_PHASES.vizziniContains(state.phaseKey))
                        {
                            var maneuverAction = activeToken.activationState().maneuverAction();

                            if (maneuverAction)
                            {
                                var maneuver = maneuverAction.maneuver();
                                var fromPosition = maneuverAction.fromPosition();
                                var shipBase = maneuverAction.shipBase();
                                LOGGER.debug("setting maneuver data");

                                answer.maneuver =
                                {
                                    maneuver: maneuver,
                                    fromPosition: fromPosition,
                                    shipBase: shipBase,
                                };
                            }
                        }
                    }

                    function getLaserAudioClip(token)
                    {
                        var answer;

                        var shipKey = token.pilot().shipTeam.shipKey;

                        if (shipKey === Ship.YT_1300 || shipKey === Ship.YT_2400)
                        {
                            answer = document.getElementById("millenniumFalconLaserAudio");
                        }
                        else if (shipKey === Ship.FIRESPRAY_31)
                        {
                            answer = document.getElementById("slave1LaserAudio");
                        }
                        else
                        {
                            var teamKey = token.pilot().shipTeam.teamKey;

                            if (teamKey === Team.IMPERIAL)
                            {
                                answer = document.getElementById("tieFighterLaserAudio");
                            }
                            else
                            {
                                answer = document.getElementById("xWingLaserAudio");
                            }
                        }

                        return answer;
                    }
                },
            };

            Connector.StatusBarUI =
            {
                mapStateToProps: function(state, ownProps)
                {
                    InputValidator.validateNotNull("environment", ownProps.environment);

                    var environment = ownProps.environment;
                    var activeToken = environment.getTokenById(state.activeTokenId);
                    var activeShipName = (activeToken ? activeToken.name() : "");

                    return (
                    {
                        round: state.round,
                        phaseKey: state.phaseKey,
                        activeShipName: activeShipName,
                    });
                },
            };

            if (Object.freeze)
            {
                Object.freeze(Connector);
            }

            return Connector;
        });
<|endoftext|>


<commit_before>/* Copyright 2009, 2010 Paperpile

   This file is part of Paperpile

   Paperpile is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Paperpile is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.  You should have received a
   copy of the GNU General Public License along with Paperpile.  If
   not, see http://www.gnu.org/licenses. */

Paperpile.PluginPanelLabel = Ext.extend(Paperpile.PluginPanel, {

  initComponent: function() {
    Ext.apply(this, {
      title: this.title,
      iconCls: 'pp-icon-label'
    });

    Paperpile.PluginPanelLabel.superclass.initComponent.call(this);

    this.on('afterrender', this.myAfterRender, this);
  },

  myAfterRender: function() {
    this.getGrid().updateTagStyles();
  },

  createGrid: function(gridParams) {
    return new Paperpile.PluginGridLabel(gridParams);
  }
});

Paperpile.PluginGridLabel = Ext.extend(Paperpile.PluginGridDB, {

  plugin_iconCls: 'pp-icon-label',
  plugin_name: 'DB',
  limit: 25,
  plugin_base_query: '',

  initComponent: function() {
    Paperpile.PluginGridLabel.superclass.initComponent.call(this);

    this.actions['REMOVE_FROM_LABEL'] = new Ext.Action({
      text: 'Remove label from references',
      cls: 'x-btn-text-icon',
      icon: '/images/icons/label_delete.png',
      handler: this.removeFromLabel,
      scope: this
    });

  },

  getGUID: function() {
    var match = this.plugin_base_query.match('labelid:(.*)$');
    var guid = match[1];
    return guid;
  },

  updateTagStyles: function() {
    Paperpile.PluginGridLabel.superclass.updateTagStyles.call(this);

    var pp = this.getPluginPanel();
    var guid = this.getGUID();
    pp.setIconClass('pp-tag-style-tab pp-tag-style-' + Paperpile.main.getStyleForTag(guid));
  },

  getEmptyBeforeSearchTemplate: function() {
    return new Ext.XTemplate(['

No references are tagged with this label. Close tab

']).compile();
  },

  initContextMenuItemIds: function() {
    Paperpile.PluginGridLabel.superclass.initContextMenuItemIds.call(this);
    var ids = this.contextMenuItemIds;

    var index = ids.indexOf('DELETE');
    ids.insert(index + 1, 'REMOVE_FROM_LABEL');
  },

  initToolbarMenuItemIds: function() {
    Paperpile.PluginGridLabel.superclass.initToolbarMenuItemIds.call(this);
    var ids = this.toolbarMenuItemIds;

    var index = ids.indexOf('TB_FILL');
    ids.insert(index + 1, 'REMOVE_FROM_LABEL');
  },

  updateButtons: function() {
    Paperpile.PluginGridLabel.superclass.updateButtons.call(this);

    var selection = this.getSingleSelectionRecord();
    if (!selection) {
      this.actions['REMOVE_FROM_LABEL'].disable();
    }
  },

  removeFromLabel: function() {
    var sel = this.getSelection();
    var grid = this;
    var match = this.plugin_base_query.match('labelid:(.*)$');
    var guid = match[1];

    var firstRecord = this.getSelectionModel().getLowestSelected();
    var firstIndex = this.getStore().indexOf(firstRecord);
    this.doAfterNextReload.push(function() {
      this.getSelectionModel().selectRow(firstIndex);
    });
    Paperpile.main.removeFromLabel(sel, grid, guid);
  },

  onUpdate: function(data) {
    Paperpile.PluginGridLabel.superclass.onUpdate.call(this, data);

    var pubs = data.pubs;
    if (!pubs) {
      return;
    }

    var refreshMe = false;
    for (var guid in pubs) {
      var update = pubs[guid];
      if (update['tags'] !== undefined) {
        refreshMe = true;
      }
    }
    if (refreshMe) {
      this.getView().holdPosition = true;
      this.getStore().reload();
    }
  }
});<commit_msg>Remove "remove label" button from toolbar.<commit_after>/* Copyright 2009, 2010 Paperpile

   This file is part of Paperpile

   Paperpile is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Paperpile is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.  You should have received a
   copy of the GNU General Public License along with Paperpile.  If
   not, see http://www.gnu.org/licenses. */

Paperpile.PluginPanelLabel = Ext.extend(Paperpile.PluginPanel, {

  initComponent: function() {
    Ext.apply(this, {
      title: this.title,
      iconCls: 'pp-icon-label'
    });

    Paperpile.PluginPanelLabel.superclass.initComponent.call(this);

    this.on('afterrender', this.myAfterRender, this);
  },

  myAfterRender: function() {
    this.getGrid().updateTagStyles();
  },

  createGrid: function(gridParams) {
    return new Paperpile.PluginGridLabel(gridParams);
  }
});

Paperpile.PluginGridLabel = Ext.extend(Paperpile.PluginGridDB, {

  plugin_iconCls: 'pp-icon-label',
  plugin_name: 'DB',
  limit: 25,
  plugin_base_query: '',

  initComponent: function() {
    Paperpile.PluginGridLabel.superclass.initComponent.call(this);

    this.actions['REMOVE_FROM_LABEL'] = new Ext.Action({
      text: 'Remove label from references',
      cls: 'x-btn-text-icon',
      icon: '/images/icons/label_delete.png',
      handler: this.removeFromLabel,
      scope: this
    });

  },

  getGUID: function() {
    var match = this.plugin_base_query.match('labelid:(.*)$');
    var guid = match[1];
    return guid;
  },

  updateTagStyles: function() {
    Paperpile.PluginGridLabel.superclass.updateTagStyles.call(this);

    var pp = this.getPluginPanel();
    var guid = this.getGUID();
    pp.setIconClass('pp-tag-style-tab pp-tag-style-' + Paperpile.main.getStyleForTag(guid));
  },

  getEmptyBeforeSearchTemplate: function() {
    return new Ext.XTemplate(['

No references are tagged with this label. Close tab

']).compile();
  },

  initContextMenuItemIds: function() {
    Paperpile.PluginGridLabel.superclass.initContextMenuItemIds.call(this);
    var ids = this.contextMenuItemIds;

    //var index = ids.indexOf('DELETE');
    //ids.insert(index + 1, 'REMOVE_FROM_LABEL');
  },

  initToolbarMenuItemIds: function() {
    Paperpile.PluginGridLabel.superclass.initToolbarMenuItemIds.call(this);
    var ids = this.toolbarMenuItemIds;

    //var index = ids.indexOf('TB_FILL');
    //ids.insert(index + 1, 'REMOVE_FROM_LABEL');
  },

  updateButtons: function() {
    Paperpile.PluginGridLabel.superclass.updateButtons.call(this);

    var selection = this.getSingleSelectionRecord();
    if (!selection) {
      this.actions['REMOVE_FROM_LABEL'].disable();
    }
  },

  removeFromLabel: function() {
    var sel = this.getSelection();
    var grid = this;
    var match = this.plugin_base_query.match('labelid:(.*)$');
    var guid = match[1];

    var firstRecord = this.getSelectionModel().getLowestSelected();
    var firstIndex = this.getStore().indexOf(firstRecord);
    this.doAfterNextReload.push(function() {
      this.getSelectionModel().selectRow(firstIndex);
    });
    Paperpile.main.removeFromLabel(sel, grid, guid);
  },

  onUpdate: function(data) {
    Paperpile.PluginGridLabel.superclass.onUpdate.call(this, data);

    var pubs = data.pubs;
    if (!pubs) {
      return;
    }

    var refreshMe = false;
    for (var guid in pubs) {
      var update = pubs[guid];
      if (update['tags'] !== undefined) {
        refreshMe = true;
      }
    }
    if (refreshMe) {
      this.getView().holdPosition = true;
      this.getStore().reload();
    }
  }
});<|endoftext|>