<commit_before>function capitaliseFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

if (!String.prototype.trim) {
		String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
}

FLOW.CascadeResourceView = FLOW.View.extend({
	showNewCascadeField: false,
	cascadeResourceName:null,
	showImportDialog:false,

    didInsertElement : function() {
      FLOW.uploader.registerEvents();
    },

    showMessage : function(header, msg) {
		FLOW.dialogControl.set('activeAction', 'ignore');
		FLOW.dialogControl.set('header', header);
		FLOW.dialogControl.set('message', msg);
		FLOW.dialogControl.set('showCANCEL', false);
		FLOW.dialogControl.set('showDialog', true);
	},

    importFile : function() {
		var file = $('#cascade-resource-file')[0],
		    numLevels = FLOW.selectedControl.get('cascadeImportNumLevels');

		if (!numLevels || +numLevels === 0) {
			this.showMessage(Ember.String.loc('_import_cascade_file'), Ember.String.loc('_import_cascade_number_levels'));
			return;
		}

		if (!file || file.files.length === 0) {
			this.showMessage(Ember.String.loc('_import_cascade_file'), Ember.String.loc('_import_select_cascade_file'));
			return;
		}
		FLOW.uploader.addFile(file.files[0]);
		FLOW.uploader.upload();
	},

	// fired when 'add a cascade resource' is clicked. Displays a text field
	newCascade: function () {
		FLOW.selectedControl.set('cascadeImportNumLevels', null);
		FLOW.selectedControl.set('cascadeImportIncludeCodes', null);
		this.set('importIncludeCodes', null);
	    this.set('showNewCascadeField', true);
	},

	saveNodes: function(){
		FLOW.store.commit();
	},

	showImportCascade: function(){
		this.toggleProperty('showImportDialog');
	},

	hideImportCascade: function(){
		FLOW.selectedControl.set('cascadeImportNumLevels', null);
		FLOW.selectedControl.set('cascadeImportIncludeCodes', null);
		this.toggleProperty('showImportDialog');
	},

	publishResource: function(){
		if (!Ember.empty(FLOW.selectedControl.get('selectedCascadeResource'))){
			FLOW.cascadeResourceControl.publish(FLOW.selectedControl.selectedCascadeResource.get('keyId'));
			this.showMessage(Ember.String.loc('_cascade_resources'), Ember.String.loc('_cascade_resource_published_text'));
		}
	},

	deleteResource: function (e) {
		var resource = FLOW.selectedControl.selectedCascadeResource,
		    keyId = resource.get('keyId'),
            questions = FLOW.store.filter(FLOW.Question, function (item) {
              return item.get('cascadeResourceId') === keyId;
            });

		if (questions.get('length') > 0) {
			this.showMessage(Ember.String.loc('_cascade_resources'), Ember.String.loc('_cannot_delete_cascade'));
			return;
		}
		resource.deleteRecord();
		FLOW.store.commit();
		FLOW.selectedControl.set('selectedCascadeResource', null);
	},

	// adds a level to the hierarchy
	addLevel: function(){
		var selectedCascade = FLOW.selectedControl.selectedCascadeResource,
		    numLevels = (selectedCascade && selectedCascade.get('numLevels') + 1) || 0,
		    nameLevels = (selectedCascade && selectedCascade.get('levelNames')) || [];

		if (!selectedCascade) {
			return;
		}

		nameLevels.push('Level ' + numLevels);

		selectedCascade.set('numLevels', numLevels);
		selectedCascade.set('levelNames', nameLevels);
		FLOW.store.commit();
		FLOW.cascadeResourceControl.setLevelNamesArray();
		FLOW.cascadeResourceControl.setDisplayLevelNames();
	},

	oneSelected: function(){
		return !Ember.empty(FLOW.selectedControl.get('selectedCascadeResource'));
	}.property('FLOW.selectedControl.selectedCascadeResource').cacheable(),

	resourceSelected: function(){
		if (!Ember.empty(FLOW.selectedControl.get('selectedCascadeResource'))){
			var i=1, levelNamesArray=[];
			FLOW.cascadeNodeControl.emptyNodes(1);
			FLOW.cascadeNodeControl.populate(FLOW.selectedControl.selectedCascadeResource.get('keyId'),1,0);
			FLOW.cascadeResourceControl.setLevelNamesArray();
			FLOW.cascadeNodeControl.set('skip',0);
			FLOW.cascadeNodeControl.setDisplayLevels();
			FLOW.cascadeResourceControl.setDisplayLevelNames();
			FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
		}
	}.observes('FLOW.selectedControl.selectedCascadeResource'),

	// fired when 'save' is clicked while showing new cascade text field. Saves new cascade resource to the data store
	saveNewCascadeResource: function () {
		var casc;
		  if (!Ember.empty(this.get('cascadeResourceName').trim())){
			  casc = FLOW.store.createRecord(FLOW.CascadeResource, {
				  "version": 0,
				  "levelNames":["Level 1"],
				  "numLevels": 1,
				  "name": capitaliseFirstLetter(this.get('cascadeResourceName'))
			  });
			  FLOW.store.commit();
			  FLOW.selectedControl.set('selectedCascadeResource',casc);
		  }
	    this.set('showNewCascadeField', false);
	},

	  // fired when 'cancel' is clicked while showing new group text field in left sidebar. Cancels the new survey group creation
	cancelNewCascadeResource: function () {
	  this.set('cascadeResourceName', null);
	  this.set('showNewCascadeField', false);
	},
});

FLOW.CascadeSecondNavView = FLOW.View.extend({
	tagName: 'li',
	content: null,
	classNameBindings: 'display:disable'.w(),

	display: function(){
		if (this.get('dir') == "up"){
			return !this.get('showGoUpLevel');
		} else return !this.get('showGoDownLevel');
	}.property('this.showGoUpLevel','this.showGoUpLevel'),

	showGoUpLevel: function(){
		return FLOW.selectedControl.selectedCascadeResource && (FLOW.cascadeNodeControl.get('skip') + 3 < FLOW.selectedControl.selectedCascadeResource.get('numLevels'));
	}.property('FLOW.cascadeNodeControl.skip', 'FLOW.selectedControl.selectedCascadeResource'),

	showGoDownLevel: function(){
		return FLOW.cascadeNodeControl.get('skip') > 0;
	}.property('FLOW.cascadeNodeControl.skip','FLOW.selectedControl.selectedCascadeResource'),

	goUpLevel: function(){
		FLOW.cascadeNodeControl.set('skip', FLOW.cascadeNodeControl.get('skip') + 1);
		FLOW.cascadeNodeControl.setDisplayLevels();
		FLOW.cascadeResourceControl.setDisplayLevelNames();
		FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
	},

	goDownLevel: function(){
		FLOW.cascadeNodeControl.set('skip', FLOW.cascadeNodeControl.get('skip') - 1);
		FLOW.cascadeNodeControl.setDisplayLevels();
		FLOW.cascadeResourceControl.setDisplayLevelNames();
		FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
	},
});

FLOW.CascadeLevelBreadcrumbView = FLOW.View.extend({
	tagName: 'li',
	content: null,
	classNameBindings: 'offscreen:offScreen'.w(),

	offscreen: function() {
		var skip = FLOW.cascadeNodeControl.get('skip');
		var level = this.content.get('level');
		return ((level < skip + 1) || (level > skip + 3));
	}.property('FLOW.cascadeNodeControl.skip', 'FLOW.selectedControl.selectedCascadeResource'),

	adaptColView: function(){
		var skip = FLOW.cascadeNodeControl.get('skip');
		var level = this.content.get('level');
		// if the level is already visible, do nothing
		if (level > skip && level < skip + 4) {
			return;
		}

		// clicked level lies on the left
		if (level < skip + 1) {
			FLOW.cascadeNodeControl.set('skip', level - 1);
			FLOW.cascadeNodeControl.setDisplayLevels();
			FLOW.cascadeResourceControl.setDisplayLevelNames();
			FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
		}

		// clicked level lies on the right
		if (level > skip + 3) {
			FLOW.cascadeNodeControl.set('skip', level - 3);
			FLOW.cascadeNodeControl.setDisplayLevels();
			FLOW.cascadeResourceControl.setDisplayLevelNames();
			FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
		}
	},
});

FLOW.CascadeLevelNameView = FLOW.View.extend({
	editFieldVisible:false,
	content: null,
	levelName:null,

	showEditField: function(){
		this.set('levelName',this.get('origLevelName'));
		this.set('editFieldVisible',true);
	},

	cancelNewLevelName: function(){
		this.set('levelName',null);
		this.set('editFieldVisible',false);
	},

	saveNewLevelName: function(){
		var currList, index, i=1, levelNamesArray=[];
		index = this.get('col') + FLOW.cascadeNodeControl.get('skip');
		currList = FLOW.selectedControl.selectedCascadeResource.get('levelNames');
		currList[index-1] = capitaliseFirstLetter(this.get('levelName'));
		FLOW.selectedControl.selectedCascadeResource.set('levelNames',currList);

		// this is needed, as in this version of Ember, changes in an array do
		// not make an object dirty, apparently
		FLOW.selectedControl.selectedCascadeResource.send('becomeDirty');
		FLOW.store.commit();

		// put the names in the array again.
		FLOW.cascadeResourceControl.setLevelNamesArray();
		FLOW.cascadeResourceControl.setDisplayLevelNames();

		this.set('levelName',null);
		this.set('editFieldVisible',false);
	}
});

FLOW.CascadeNodeView = FLOW.View.extend({
	cascadeNodeName: null,
	cascadeNodeCode:null,

	showInputField:function(){
		var skip = FLOW.cascadeNodeControl.get('skip');

		// determines if we should show an input field in this column
		// we do this in column one by default, or if in the previous column a node has been selected
		if (this.get('col') === 1 && skip === 0) {
			return true;
		}
		return (!Ember.empty(FLOW.cascadeNodeControl.selectedNode[skip + this.get('col') - 1]) &&
				!Ember.empty(FLOW.cascadeNodeControl.selectedNode[skip + this.get('col') - 1].get('keyId')));
	}.property('FLOW.cascadeNodeControl.selectedNodeTrigger').cacheable(),

	addNewNode: function() {
		var newNodeStringArray, level, nodes, exists, item, itemTrim, levelNames;
		level = this.get('col') + FLOW.cascadeNodeControl.get('skip');
		nodes = FLOW.cascadeNodeControl.get('level' + level);
		item = this.get('cascadeNodeName');
		if (item !== null && item.trim().length > 0) {
			exists = false;
			itemTrim = item.trim().toLowerCase();
			nodes.forEach(function(node){
				if (node.get('name').toLowerCase() == itemTrim) {
					exists = true;
				}
			});
			if (!exists) {
				FLOW.cascadeNodeControl.addNode(FLOW.selectedControl.selectedCascadeResource.get('keyId'),
						level, item.trim(), this.get('cascadeNodeCode'));
			}
		}
		this.set('cascadeNodeName',"");
		this.set('cascadeNodeCode',"");

		// check if we need to increase the level of items that we use
		// TODO somehow decrease it when a level becomes empty. However, this is hard to check.
		if (level > FLOW.selectedControl.selectedCascadeResource.get('numLevels')){
			levelNames = FLOW.selectedControl.selectedCascadeResource.get('levelNames');
			levelNames.push('Level ' + level);
			FLOW.selectedControl.selectedCascadeResource.set('numLevels', level);
			FLOW.selectedControl.selectedCascadeResource.set('levelNames', levelNames);
			FLOW.store.commit();
			FLOW.cascadeResourceControl.setLevelNamesArray();
		}
	},
});

FLOW.CascadeNodeItemView = FLOW.View.extend({
	content: null,
	tagName: 'li',
	classNameBindings: 'amSelected:selected'.w(),
	showEditNodeFlag: false,
	newCode:null,
	newName:null,

	// true if the node group is selected. Used to set proper display class
	amSelected: function () {
	    var selected = FLOW.cascadeNodeControl.get('selectedNode')[this.get('col') + FLOW.cascadeNodeControl.get('skip')];
	    if (selected) {
	      var amSelected = (this.content.get('name') === FLOW.cascadeNodeControl.get('selectedNode')[this.get('col') + FLOW.cascadeNodeControl.get('skip')].get('name'));
	      return amSelected;
	    } else {
	      return false;
	    }
	}.property('FLOW.cascadeNodeControl.selectedNodeTrigger').cacheable(),

	deleteNode:function() {
		FLOW.cascadeNodeControl.emptyNodes(this.get('col') + FLOW.cascadeNodeControl.get('skip') + 1);
		this.get('content').deleteRecord();
		FLOW.store.commit();
	},

	showEditNodeField: function(){
		this.set('showEditNode', true);
		this.set('newCode',this.content.get('code'));
		this.set('newName',this.content.get('name'));
	},

	cancelEditNode: function(){
		this.set('showEditNode', false);
		this.set('newCode',null);
		this.set('newName',null);
	},

	saveEditNode: function(){
		if (Ember.empty(this.get('newName')) ||this.get('newName').trim().length === 0) {
			this.cancelEditNode();
			return;
		}
		this.content.set('name',capitaliseFirstLetter(this.get('newName')));
		this.content.set('code',this.get('newCode'));
		FLOW.store.commit();
		this.cancelEditNode();
	},

	makeSelected: function(){
		var i, level;
		level = this.get('col') + FLOW.cascadeNodeControl.get('skip');
		FLOW.cascadeNodeControl.get('selectedNode')[level] = this.get('content');
		FLOW.cascadeNodeControl.emptyNodes(level + 1);

		if (!Ember.empty(this.content.get('keyId'))){
			FLOW.cascadeNodeControl.populate(FLOW.selectedControl.selectedCascadeResource.get('keyId'),
					level + 1, this.content.get('keyId'));
		}
		FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
	}
});<commit_msg>[#1024] Clear cascade new name field after save<commit_after>function capitaliseFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

if (!String.prototype.trim) {
		String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
}

FLOW.CascadeResourceView = FLOW.View.extend({
	showNewCascadeField: false,
	cascadeResourceName:null,
	showImportDialog:false,

    didInsertElement : function() {
      FLOW.uploader.registerEvents();
    },

    showMessage : function(header, msg) {
		FLOW.dialogControl.set('activeAction', 'ignore');
		FLOW.dialogControl.set('header', header);
		FLOW.dialogControl.set('message', msg);
		FLOW.dialogControl.set('showCANCEL', false);
		FLOW.dialogControl.set('showDialog', true);
	},

    importFile : function() {
		var file = $('#cascade-resource-file')[0],
		    numLevels = FLOW.selectedControl.get('cascadeImportNumLevels');

		if (!numLevels || +numLevels === 0) {
			this.showMessage(Ember.String.loc('_import_cascade_file'), Ember.String.loc('_import_cascade_number_levels'));
			return;
		}

		if (!file || file.files.length === 0) {
			this.showMessage(Ember.String.loc('_import_cascade_file'), Ember.String.loc('_import_select_cascade_file'));
			return;
		}
		FLOW.uploader.addFile(file.files[0]);
		FLOW.uploader.upload();
	},

	// fired when 'add a cascade resource' is clicked. Displays a text field
	newCascade: function () {
		FLOW.selectedControl.set('cascadeImportNumLevels', null);
		FLOW.selectedControl.set('cascadeImportIncludeCodes', null);
		this.set('importIncludeCodes', null);
	    this.set('showNewCascadeField', true);
	},

	saveNodes: function(){
		FLOW.store.commit();
	},

	showImportCascade: function(){
		this.toggleProperty('showImportDialog');
	},

	hideImportCascade: function(){
		FLOW.selectedControl.set('cascadeImportNumLevels', null);
		FLOW.selectedControl.set('cascadeImportIncludeCodes', null);
		this.toggleProperty('showImportDialog');
	},

	publishResource: function(){
		if (!Ember.empty(FLOW.selectedControl.get('selectedCascadeResource'))){
			FLOW.cascadeResourceControl.publish(FLOW.selectedControl.selectedCascadeResource.get('keyId'));
			this.showMessage(Ember.String.loc('_cascade_resources'), Ember.String.loc('_cascade_resource_published_text'));
		}
	},

	deleteResource: function (e) {
		var resource = FLOW.selectedControl.selectedCascadeResource,
		    keyId = resource.get('keyId'),
            questions = FLOW.store.filter(FLOW.Question, function (item) {
              return item.get('cascadeResourceId') === keyId;
            });

		if (questions.get('length') > 0) {
			this.showMessage(Ember.String.loc('_cascade_resources'), Ember.String.loc('_cannot_delete_cascade'));
			return;
		}
		resource.deleteRecord();
		FLOW.store.commit();
		FLOW.selectedControl.set('selectedCascadeResource', null);
	},

	// adds a level to the hierarchy
	addLevel: function(){
		var selectedCascade = FLOW.selectedControl.selectedCascadeResource,
		    numLevels = (selectedCascade && selectedCascade.get('numLevels') + 1) || 0,
		    nameLevels = (selectedCascade && selectedCascade.get('levelNames')) || [];

		if (!selectedCascade) {
			return;
		}

		nameLevels.push('Level ' + numLevels);

		selectedCascade.set('numLevels', numLevels);
		selectedCascade.set('levelNames', nameLevels);
		FLOW.store.commit();
		FLOW.cascadeResourceControl.setLevelNamesArray();
		FLOW.cascadeResourceControl.setDisplayLevelNames();
	},

	oneSelected: function(){
		return !Ember.empty(FLOW.selectedControl.get('selectedCascadeResource'));
	}.property('FLOW.selectedControl.selectedCascadeResource').cacheable(),

	resourceSelected: function(){
		if (!Ember.empty(FLOW.selectedControl.get('selectedCascadeResource'))){
			var i=1, levelNamesArray=[];
			FLOW.cascadeNodeControl.emptyNodes(1);
			FLOW.cascadeNodeControl.populate(FLOW.selectedControl.selectedCascadeResource.get('keyId'),1,0);
			FLOW.cascadeResourceControl.setLevelNamesArray();
			FLOW.cascadeNodeControl.set('skip',0);
			FLOW.cascadeNodeControl.setDisplayLevels();
			FLOW.cascadeResourceControl.setDisplayLevelNames();
			FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
		}
	}.observes('FLOW.selectedControl.selectedCascadeResource'),

	// fired when 'save' is clicked while showing new cascade text field. Saves new cascade resource to the data store
	saveNewCascadeResource: function () {
		var casc;
		  if (!Ember.empty(this.get('cascadeResourceName').trim())){
			  casc = FLOW.store.createRecord(FLOW.CascadeResource, {
				  "version": 0,
				  "levelNames":["Level 1"],
				  "numLevels": 1,
				  "name": capitaliseFirstLetter(this.get('cascadeResourceName'))
			  });
			  FLOW.store.commit();
			  FLOW.selectedControl.set('selectedCascadeResource',casc);
		  }
	    this.set('showNewCascadeField', false);
	    this.set('cascadeResourceName',null);
	},

	  // fired when 'cancel' is clicked while showing new group text field in left sidebar. Cancels the new survey group creation
	cancelNewCascadeResource: function () {
	  this.set('cascadeResourceName', null);
	  this.set('showNewCascadeField', false);
	},
});

FLOW.CascadeSecondNavView = FLOW.View.extend({
	tagName: 'li',
	content: null,
	classNameBindings: 'display:disable'.w(),

	display: function(){
		if (this.get('dir') == "up"){
			return !this.get('showGoUpLevel');
		} else return !this.get('showGoDownLevel');
	}.property('this.showGoUpLevel','this.showGoUpLevel'),

	showGoUpLevel: function(){
		return FLOW.selectedControl.selectedCascadeResource && (FLOW.cascadeNodeControl.get('skip') + 3 < FLOW.selectedControl.selectedCascadeResource.get('numLevels'));
	}.property('FLOW.cascadeNodeControl.skip', 'FLOW.selectedControl.selectedCascadeResource'),

	showGoDownLevel: function(){
		return FLOW.cascadeNodeControl.get('skip') > 0;
	}.property('FLOW.cascadeNodeControl.skip','FLOW.selectedControl.selectedCascadeResource'),

	goUpLevel: function(){
		FLOW.cascadeNodeControl.set('skip', FLOW.cascadeNodeControl.get('skip') + 1);
		FLOW.cascadeNodeControl.setDisplayLevels();
		FLOW.cascadeResourceControl.setDisplayLevelNames();
		FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
	},

	goDownLevel: function(){
		FLOW.cascadeNodeControl.set('skip', FLOW.cascadeNodeControl.get('skip') - 1);
		FLOW.cascadeNodeControl.setDisplayLevels();
		FLOW.cascadeResourceControl.setDisplayLevelNames();
		FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
	},
});

FLOW.CascadeLevelBreadcrumbView = FLOW.View.extend({
	tagName: 'li',
	content: null,
	classNameBindings: 'offscreen:offScreen'.w(),

	offscreen: function() {
		var skip = FLOW.cascadeNodeControl.get('skip');
		var level = this.content.get('level');
		return ((level < skip + 1) || (level > skip + 3));
	}.property('FLOW.cascadeNodeControl.skip', 'FLOW.selectedControl.selectedCascadeResource'),

	adaptColView: function(){
		var skip = FLOW.cascadeNodeControl.get('skip');
		var level = this.content.get('level');
		// if the level is already visible, do nothing
		if (level > skip && level < skip + 4) {
			return;
		}

		// clicked level lies on the left
		if (level < skip + 1) {
			FLOW.cascadeNodeControl.set('skip', level - 1);
			FLOW.cascadeNodeControl.setDisplayLevels();
			FLOW.cascadeResourceControl.setDisplayLevelNames();
			FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
		}

		// clicked level lies on the right
		if (level > skip + 3) {
			FLOW.cascadeNodeControl.set('skip', level - 3);
			FLOW.cascadeNodeControl.setDisplayLevels();
			FLOW.cascadeResourceControl.setDisplayLevelNames();
			FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
		}
	},
});

FLOW.CascadeLevelNameView = FLOW.View.extend({
	editFieldVisible:false,
	content: null,
	levelName:null,

	showEditField: function(){
		this.set('levelName',this.get('origLevelName'));
		this.set('editFieldVisible',true);
	},

	cancelNewLevelName: function(){
		this.set('levelName',null);
		this.set('editFieldVisible',false);
	},

	saveNewLevelName: function(){
		var currList, index, i=1, levelNamesArray=[];
		index = this.get('col') + FLOW.cascadeNodeControl.get('skip');
		currList = FLOW.selectedControl.selectedCascadeResource.get('levelNames');
		currList[index-1] = capitaliseFirstLetter(this.get('levelName'));
		FLOW.selectedControl.selectedCascadeResource.set('levelNames',currList);

		// this is needed, as in this version of Ember, changes in an array do
		// not make an object dirty, apparently
		FLOW.selectedControl.selectedCascadeResource.send('becomeDirty');
		FLOW.store.commit();

		// put the names in the array again.
		FLOW.cascadeResourceControl.setLevelNamesArray();
		FLOW.cascadeResourceControl.setDisplayLevelNames();

		this.set('levelName',null);
		this.set('editFieldVisible',false);
	}
});

FLOW.CascadeNodeView = FLOW.View.extend({
	cascadeNodeName: null,
	cascadeNodeCode:null,

	showInputField:function(){
		var skip = FLOW.cascadeNodeControl.get('skip');

		// determines if we should show an input field in this column
		// we do this in column one by default, or if in the previous column a node has been selected
		if (this.get('col') === 1 && skip === 0) {
			return true;
		}
		return (!Ember.empty(FLOW.cascadeNodeControl.selectedNode[skip + this.get('col') - 1]) &&
				!Ember.empty(FLOW.cascadeNodeControl.selectedNode[skip + this.get('col') - 1].get('keyId')));
	}.property('FLOW.cascadeNodeControl.selectedNodeTrigger').cacheable(),

	addNewNode: function() {
		var newNodeStringArray, level, nodes, exists, item, itemTrim, levelNames;
		level = this.get('col') + FLOW.cascadeNodeControl.get('skip');
		nodes = FLOW.cascadeNodeControl.get('level' + level);
		item = this.get('cascadeNodeName');
		if (item !== null && item.trim().length > 0) {
			exists = false;
			itemTrim = item.trim().toLowerCase();
			nodes.forEach(function(node){
				if (node.get('name').toLowerCase() == itemTrim) {
					exists = true;
				}
			});
			if (!exists) {
				FLOW.cascadeNodeControl.addNode(FLOW.selectedControl.selectedCascadeResource.get('keyId'),
						level, item.trim(), this.get('cascadeNodeCode'));
			}
		}
		this.set('cascadeNodeName',"");
		this.set('cascadeNodeCode',"");

		// check if we need to increase the level of items that we use
		// TODO somehow decrease it when a level becomes empty. However, this is hard to check.
		if (level > FLOW.selectedControl.selectedCascadeResource.get('numLevels')){
			levelNames = FLOW.selectedControl.selectedCascadeResource.get('levelNames');
			levelNames.push('Level ' + level);
			FLOW.selectedControl.selectedCascadeResource.set('numLevels', level);
			FLOW.selectedControl.selectedCascadeResource.set('levelNames', levelNames);
			FLOW.store.commit();
			FLOW.cascadeResourceControl.setLevelNamesArray();
		}
	},
});

FLOW.CascadeNodeItemView = FLOW.View.extend({
	content: null,
	tagName: 'li',
	classNameBindings: 'amSelected:selected'.w(),
	showEditNodeFlag: false,
	newCode:null,
	newName:null,

	// true if the node group is selected. Used to set proper display class
	amSelected: function () {
	    var selected = FLOW.cascadeNodeControl.get('selectedNode')[this.get('col') + FLOW.cascadeNodeControl.get('skip')];
	    if (selected) {
	      var amSelected = (this.content.get('name') === FLOW.cascadeNodeControl.get('selectedNode')[this.get('col') + FLOW.cascadeNodeControl.get('skip')].get('name'));
	      return amSelected;
	    } else {
	      return false;
	    }
	}.property('FLOW.cascadeNodeControl.selectedNodeTrigger').cacheable(),

	deleteNode:function() {
		FLOW.cascadeNodeControl.emptyNodes(this.get('col') + FLOW.cascadeNodeControl.get('skip') + 1);
		this.get('content').deleteRecord();
		FLOW.store.commit();
	},

	showEditNodeField: function(){
		this.set('showEditNode', true);
		this.set('newCode',this.content.get('code'));
		this.set('newName',this.content.get('name'));
	},

	cancelEditNode: function(){
		this.set('showEditNode', false);
		this.set('newCode',null);
		this.set('newName',null);
	},

	saveEditNode: function(){
		if (Ember.empty(this.get('newName')) ||this.get('newName').trim().length === 0) {
			this.cancelEditNode();
			return;
		}
		this.content.set('name',capitaliseFirstLetter(this.get('newName')));
		this.content.set('code',this.get('newCode'));
		FLOW.store.commit();
		this.cancelEditNode();
	},

	makeSelected: function(){
		var i, level;
		level = this.get('col') + FLOW.cascadeNodeControl.get('skip');
		FLOW.cascadeNodeControl.get('selectedNode')[level] = this.get('content');
		FLOW.cascadeNodeControl.emptyNodes(level + 1);

		if (!Ember.empty(this.content.get('keyId'))){
			FLOW.cascadeNodeControl.populate(FLOW.selectedControl.selectedCascadeResource.get('keyId'),
					level + 1, this.content.get('keyId'));
		}
		FLOW.cascadeNodeControl.toggleSelectedNodeTrigger();
	}
});<|endoftext|>


<commit_before>/**
 * Holds shared logic for subgames.
 *
 * How to use:
 * Number amount:        this.amount
 * Representation:       this.representation
 * The method:           this.method
 * The number to answer: this.currentNumber (updates automatically)
 *
 * Add game objects to:     this.gameGroup
 * Add buttons and HUD to:  this.hudGroup
 * Use agent with:          this.agent (default visibility = false)
 *
 * Start game:              this.startGame()
 * Disable/Enable input:    this.disable(true/false) - default = true = disabled
 * Run next round:          this.nextRound() - will change mode automatically when needed
 * Try a number:            this.tryNumber(number) - when testing a guess against this.currentNumber
 * Add water to the can:    this.addWater(fromX, fromY) - Adds a water drop to the can
 *
 *
 * These function _should_ be overshadowed by the subgame:
 * They are called with two parameters (ifFirstTime, triesSoFar).
 * modeIntro      // Introduce the game, call nextRound to start next mode.
 * modePlayerDo   // Player only
 * modePlayerShow // Player is showing the TA
 * modeAgentTry   // TA is guessing and the player is helping out
 * modeAgentDo    // TA only
 * modeOutro      // The game is finished, celebrate!
 *
 *
 * Typical game flow:
 * this.startGame();    // the first mode, this.modeIntro, will be called
 * this.nextRound();    // start next round (will automatically start next mode)
 * this.disable(false); // make it possible to interact with anything
 * this.tryNumber(x);   // try a number against the current one
 * this.nextRound();    // do this regardless if right or wrong,
 *                      // it takes care of mode switching and function calls for you
 * // Repeat last two functions until game is over.
 */
function Subgame () {}

/* Phaser state function. (publishes subgameStarted event) */
Subgame.prototype.init = function (options) {
	/* "Private" variables */
	var _this = this; // Event subscriptions does not have access to this
	this._modes = options.mode || [
		GLOBAL.MODE.intro,
		GLOBAL.MODE.playerDo,
		GLOBAL.MODE.playerShow,
		GLOBAL.MODE.agentTry,
		// GLOBAL.MODE.agentDo,
		GLOBAL.MODE.outro
	];
	this._mode = null;
	this._pendingMode = null;
	this._first = true;
	/* Keep track of how many rounds that have been played */
	this._counter = new Counter(options.roundsPerMode || 3, true);
	/* When enough rounds have been played, trigger a mode change */
	this._counter.onMax = function () {
		_this._nextMode();
	};
	this._currentTries = 0;
	this._totalTries = 0;

	/* Public variables */
	this.method = options.method || GLOBAL.METHOD.count;
	this.representation = options.representation;
	this.amount = GLOBAL.NUMBER_RANGE[options.range];
	/* The current number to answer */
	this.currentNumber = null;
	/* The current mode running */
	this.currentMode = null;
	/* Stores the offset of the last try, can be used to judge last try */
	/* Ex: -1 means that last try was one less than currentNumber */
	this.lastTry = 0;

	/* Setup game objects */
	this.gameGroup = game.add.group();
	this.agent = player.createAgent();
	this.agent.visible = false;
	this.gameGroup.add(this.agent);

	this.hudGroup = game.add.group();

	//  TODO: Is there an easier way to disable all input, except the menu?
	var disabler = new Cover('#ffffff', 0);
	game.world.add(disabler);
	this.disable = function (value) {
		if (disabler.visible !== value) {
			EventSystem.publish(GLOBAL.EVENT.disabled, [value]);
		}
		disabler.visible = value;
	};

	/* Setup menu objects */
	this._menuGroup = game.add.group();
	this._menuGroup.visible = false;

	this.waterCan = new WaterCan(this.game.width - 100, 10);
	this._menuGroup.add(this.waterCan);

	this._menuGroup.add(new Menu());

	EventSystem.publish(GLOBAL.EVENT.subgameStarted, [options.type || 0]);
};

/* Phaser state function */
Subgame.prototype.shutdown = onShutDown;

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                            Private functions                              */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/

/** Change to the next mode in the queue. */
Subgame.prototype._nextMode = function () {
	var newMode = this._modes.shift();
	this._decideMode(newMode);
	this._pendingMode = newMode;
	this._first = true;
};

/**
 * Translate from integer to mode function
 * @param {number}
 */
Subgame.prototype._decideMode = function (mode) {
	if (mode === GLOBAL.MODE.intro) {
		this._mode = this.modeIntro;
	} else if (mode === GLOBAL.MODE.playerDo) {
		this._mode = this.modePlayerDo;
	} else if (mode === GLOBAL.MODE.playerShow) {
		this._mode = this.modePlayerShow;
	} else if (mode === GLOBAL.MODE.agentTry) {
		this._mode = this.modeAgentTry;
	} else if (mode === GLOBAL.MODE.agentDo) {
		this._mode = this.modeAgentDo;
	} else if (mode === GLOBAL.MODE.outro) {
		this._mode = this.modeOutro;
	} else {
		this._mode = this.endGame;
	}
};

/** Change this.currentNumber to a new one (resets the tries). */
Subgame.prototype._nextNumber = function () {
	// Should we allow the same number again?
	this._totalTries += this._currentTries;
	this._currentTries = 0;
	this.currentNumber = this.rnd.integerInRange(1, this.amount);
};

/** Skip the current mode. */
Subgame.prototype._skipMode = function () {
	this._nextMode();
	this.nextRound();
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                            Public functions                               */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/

/**
 * Calls the current mode function (publishes modeChange event first time mode runs).
 * It will be called with two parameters:
 * 1) If it is the first time on this mode.
 * 2) How many tries that have been made on the current number.
 */
Subgame.prototype.nextRound = function () {
	// Special case: intro and outro only have one round
	if ((this.currentMode === GLOBAL.MODE.intro ||
		this.currentMode === GLOBAL.MODE.outro) &&
		this.currentMode === this._pendingMode) {
		this._nextMode();
	}

	// Publish event when it it is the first time it runs
	if (this._first) {
		EventSystem.publish(GLOBAL.EVENT.modeChange, [this._pendingMode]);
	}

	// Run mode and update properties
	this.currentMode = this._pendingMode;
	this._mode(this._first, this._currentTries);
	this._first = false;
};

/**
 * Try a number against this.currentNumber (publishes tryNumber event).
 * The offset of the last try is stored in this.lastTry.
 * @param {number} The number to try.
 * @returns {boolean} The offset of the last try (0 is correct, -x is too low, +x is too high).
 */
Subgame.prototype.tryNumber = function (number) {
	EventSystem.publish(GLOBAL.EVENT.tryNumber, [number, this.currentNumber]);
	this._currentTries++;
	this.lastTry = number - this.currentNumber;

	if (!this.lastTry) {
		this._counter.value++; // This will trigger next mode if we loop.
		this._nextNumber();
	}
	return this.lastTry;
};

/**
 * Adds water to the water can.
 * Water will only be added in modes playerShow, agentTry and agentDo.
 * @param {number} The x position where the drop will begin.
 * @param {number} The y position where the drop will begin.
 * @param {boolean} Override mode restrictions and force drop to be added.
 * @returns {Object} The drop animation from x, y to water can.
 */
Subgame.prototype.addWater = function (x, y, force) {
	var t = new TimelineMax();
	if (this.currentMode === GLOBAL.MODE.playerShow ||
		this.currentMode === GLOBAL.MODE.agentTry ||
		this.currentMode === GLOBAL.MODE.agentDo ||
		force) {
		var drop = this.add.sprite(x, y, 'drop', 0, this._menuGroup);
		drop.anchor.set(0.5);
		drop.scale.y = 0;

		// Show drop
		t.to(drop.scale, 1.5, { y: 1, ease:Elastic.easeOut })
			// Move drop
			.to(drop, 1.5, { x: this.waterCan.x + 30, y: this.waterCan.y, ease:Power2.easeOut })
			// Hide drop and add water
			.to(drop, 0.5, { height: 0,
				onStart: function () { player.water++; },
				onComplete: function () { drop.destroy(); }
			});
	}
	return t;
};

/** Start the game! */
Subgame.prototype.startGame = function () {
	var _this = this;
	this.sound.whenSoundsDecoded(function () {
		_this._menuGroup.visible = true;
		_this._nextMode();
		_this._nextNumber();
		_this.nextRound();
	});
};

/* End the game. */
Subgame.prototype.endGame = function () {
	this.state.start(GLOBAL.STATE.garden);
};

/* Overshadowing mode functions */
/* The following functions should be overshadowed in the game object */
Subgame.prototype.modeIntro      = Subgame.prototype._skipMode;
Subgame.prototype.modePlayerDo   = Subgame.prototype._skipMode;
Subgame.prototype.modePlayerShow = Subgame.prototype._skipMode;
Subgame.prototype.modeAgentTry   = Subgame.prototype._skipMode;
Subgame.prototype.modeAgentDo    = Subgame.prototype._skipMode;
Subgame.prototype.modeOutro      = Subgame.prototype._skipMode;<commit_msg>Subgame: this.method always integer<commit_after>/**
 * Holds shared logic for subgames.
 *
 * How to use:
 * Number amount:        this.amount
 * Representation:       this.representation
 * The method:           this.method
 * The number to answer: this.currentNumber (updates automatically)
 *
 * Add game objects to:     this.gameGroup
 * Add buttons and HUD to:  this.hudGroup
 * Use agent with:          this.agent (default visibility = false)
 *
 * Start game:              this.startGame()
 * Disable/Enable input:    this.disable(true/false) - default = true = disabled
 * Run next round:          this.nextRound() - will change mode automatically when needed
 * Try a number:            this.tryNumber(number) - when testing a guess against this.currentNumber
 * Add water to the can:    this.addWater(fromX, fromY) - Adds a water drop to the can
 *
 *
 * These function _should_ be overshadowed by the subgame:
 * They are called with two parameters (ifFirstTime, triesSoFar).
 * modeIntro      // Introduce the game, call nextRound to start next mode.
 * modePlayerDo   // Player only
 * modePlayerShow // Player is showing the TA
 * modeAgentTry   // TA is guessing and the player is helping out
 * modeAgentDo    // TA only
 * modeOutro      // The game is finished, celebrate!
 *
 *
 * Typical game flow:
 * this.startGame();    // the first mode, this.modeIntro, will be called
 * this.nextRound();    // start next round (will automatically start next mode)
 * this.disable(false); // make it possible to interact with anything
 * this.tryNumber(x);   // try a number against the current one
 * this.nextRound();    // do this regardless if right or wrong,
 *                      // it takes care of mode switching and function calls for you
 * // Repeat last two functions until game is over.
 */
function Subgame () {}

/* Phaser state function. (publishes subgameStarted event) */
Subgame.prototype.init = function (options) {
	/* "Private" variables */
	var _this = this; // Event subscriptions does not have access to this
	this._modes = options.mode || [
		GLOBAL.MODE.intro,
		GLOBAL.MODE.playerDo,
		GLOBAL.MODE.playerShow,
		GLOBAL.MODE.agentTry,
		// GLOBAL.MODE.agentDo,
		GLOBAL.MODE.outro
	];
	this._mode = null;
	this._pendingMode = null;
	this._first = true;
	/* Keep track of how many rounds that have been played */
	this._counter = new Counter(options.roundsPerMode || 3, true);
	/* When enough rounds have been played, trigger a mode change */
	this._counter.onMax = function () {
		_this._nextMode();
	};
	this._currentTries = 0;
	this._totalTries = 0;

	/* Public variables */
	this.method = parseInt(options.method || GLOBAL.METHOD.count);
	this.representation = options.representation;
	this.amount = GLOBAL.NUMBER_RANGE[options.range];
	/* The current number to answer */
	this.currentNumber = null;
	/* The current mode running */
	this.currentMode = null;
	/* Stores the offset of the last try, can be used to judge last try */
	/* Ex: -1 means that last try was one less than currentNumber */
	this.lastTry = 0;

	/* Setup game objects */
	this.gameGroup = game.add.group();
	this.agent = player.createAgent();
	this.agent.visible = false;
	this.gameGroup.add(this.agent);

	this.hudGroup = game.add.group();

	//  TODO: Is there an easier way to disable all input, except the menu?
	var disabler = new Cover('#ffffff', 0);
	game.world.add(disabler);
	this.disable = function (value) {
		if (disabler.visible !== value) {
			EventSystem.publish(GLOBAL.EVENT.disabled, [value]);
		}
		disabler.visible = value;
	};

	/* Setup menu objects */
	this._menuGroup = game.add.group();
	this._menuGroup.visible = false;

	this.waterCan = new WaterCan(this.game.width - 100, 10);
	this._menuGroup.add(this.waterCan);

	this._menuGroup.add(new Menu());

	EventSystem.publish(GLOBAL.EVENT.subgameStarted, [options.type || 0]);
};

/* Phaser state function */
Subgame.prototype.shutdown = onShutDown;

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                            Private functions                              */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/

/** Change to the next mode in the queue. */
Subgame.prototype._nextMode = function () {
	var newMode = this._modes.shift();
	this._decideMode(newMode);
	this._pendingMode = newMode;
	this._first = true;
};

/**
 * Translate from integer to mode function
 * @param {number}
 */
Subgame.prototype._decideMode = function (mode) {
	if (mode === GLOBAL.MODE.intro) {
		this._mode = this.modeIntro;
	} else if (mode === GLOBAL.MODE.playerDo) {
		this._mode = this.modePlayerDo;
	} else if (mode === GLOBAL.MODE.playerShow) {
		this._mode = this.modePlayerShow;
	} else if (mode === GLOBAL.MODE.agentTry) {
		this._mode = this.modeAgentTry;
	} else if (mode === GLOBAL.MODE.agentDo) {
		this._mode = this.modeAgentDo;
	} else if (mode === GLOBAL.MODE.outro) {
		this._mode = this.modeOutro;
	} else {
		this._mode = this.endGame;
	}
};

/** Change this.currentNumber to a new one (resets the tries). */
Subgame.prototype._nextNumber = function () {
	// Should we allow the same number again?
	this._totalTries += this._currentTries;
	this._currentTries = 0;
	this.currentNumber = this.rnd.integerInRange(1, this.amount);
};

/** Skip the current mode. */
Subgame.prototype._skipMode = function () {
	this._nextMode();
	this.nextRound();
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                            Public functions                               */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/

/**
 * Calls the current mode function (publishes modeChange event first time mode runs).
 * It will be called with two parameters:
 * 1) If it is the first time on this mode.
 * 2) How many tries that have been made on the current number.
 */
Subgame.prototype.nextRound = function () {
	// Special case: intro and outro only have one round
	if ((this.currentMode === GLOBAL.MODE.intro ||
		this.currentMode === GLOBAL.MODE.outro) &&
		this.currentMode === this._pendingMode) {
		this._nextMode();
	}

	// Publish event when it it is the first time it runs
	if (this._first) {
		EventSystem.publish(GLOBAL.EVENT.modeChange, [this._pendingMode]);
	}

	// Run mode and update properties
	this.currentMode = this._pendingMode;
	this._mode(this._first, this._currentTries);
	this._first = false;
};

/**
 * Try a number against this.currentNumber (publishes tryNumber event).
 * The offset of the last try is stored in this.lastTry.
 * @param {number} The number to try.
 * @returns {boolean} The offset of the last try (0 is correct, -x is too low, +x is too high).
 */
Subgame.prototype.tryNumber = function (number) {
	EventSystem.publish(GLOBAL.EVENT.tryNumber, [number, this.currentNumber]);
	this._currentTries++;
	this.lastTry = number - this.currentNumber;

	if (!this.lastTry) {
		this._counter.value++; // This will trigger next mode if we loop.
		this._nextNumber();
	}
	return this.lastTry;
};

/**
 * Adds water to the water can.
 * Water will only be added in modes playerShow, agentTry and agentDo.
 * @param {number} The x position where the drop will begin.
 * @param {number} The y position where the drop will begin.
 * @param {boolean} Override mode restrictions and force drop to be added.
 * @returns {Object} The drop animation from x, y to water can.
 */
Subgame.prototype.addWater = function (x, y, force) {
	var t = new TimelineMax();
	if (this.currentMode === GLOBAL.MODE.playerShow ||
		this.currentMode === GLOBAL.MODE.agentTry ||
		this.currentMode === GLOBAL.MODE.agentDo ||
		force) {
		var drop = this.add.sprite(x, y, 'drop', 0, this._menuGroup);
		drop.anchor.set(0.5);
		drop.scale.y = 0;

		// Show drop
		t.to(drop.scale, 1.5, { y: 1, ease:Elastic.easeOut })
			// Move drop
			.to(drop, 1.5, { x: this.waterCan.x + 30, y: this.waterCan.y, ease:Power2.easeOut })
			// Hide drop and add water
			.to(drop, 0.5, { height: 0,
				onStart: function () { player.water++; },
				onComplete: function () { drop.destroy(); }
			});
	}
	return t;
};

/** Start the game! */
Subgame.prototype.startGame = function () {
	var _this = this;
	this.sound.whenSoundsDecoded(function () {
		_this._menuGroup.visible = true;
		_this._nextMode();
		_this._nextNumber();
		_this.nextRound();
	});
};

/* End the game. */
Subgame.prototype.endGame = function () {
	this.state.start(GLOBAL.STATE.garden);
};

/* Overshadowing mode functions */
/* The following functions should be overshadowed in the game object */
Subgame.prototype.modeIntro      = Subgame.prototype._skipMode;
Subgame.prototype.modePlayerDo   = Subgame.prototype._skipMode;
Subgame.prototype.modePlayerShow = Subgame.prototype._skipMode;
Subgame.prototype.modeAgentTry   = Subgame.prototype._skipMode;
Subgame.prototype.modeAgentDo    = Subgame.prototype._skipMode;
Subgame.prototype.modeOutro      = Subgame.prototype._skipMode;<|endoftext|>


<commit_before>(function ($) {
    $.fn.tzCheckbox = function (options) {

        // Default On / Off labels:

        options = $.extend({
            labels: ['ON', 'OFF']
        }, options);

        return this.each(function () {
            var originalCheckBox = $(this),
				labels = [];

            // Checking for the data-on / data-off HTML5 data attributes:
            if (originalCheckBox.data('on')) {
                labels[0] = originalCheckBox.data('on');
                labels[1] = originalCheckBox.data('off');
            }
            else labels = options.labels;

            // Creating the new checkbox markup:
            var checkBox = $('', {
                class: 'tzCheckBox ' + (this.checked ? 'checked' : ''),
                html: '' + labels[this.checked ? 0 : 1] +
						''
            });

            // -- Original Code, just hides the checkbox -- //
            // Inserting the new checkbox, and hiding the original:
            //checkBox.insertAfter(originalCheckBox.hide());

            // -- Replacement code to try to get keyboard changes working -- //
            var hidden = originalCheckBox.siblings("input[type='hidden'][name='" + originalCheckBox.attr("id") + "']");

            // put the checkbox and everything into a container
            var container = $("", { class: 'tzCheckBox-Container' });
            container.append(checkBox);
            container.insertAfter(originalCheckBox);

            // move the original checkbox controls
            container.append(originalCheckBox);
            container.append(hidden);

            checkBox.click(function () {
                checkBox.toggleClass('checked');

                var isChecked = checkBox.hasClass('checked');

                // Synchronizing the original checkbox:
                originalCheckBox.attr('checked', isChecked);
                checkBox.find('.tzCBContent').html(labels[isChecked ? 0 : 1]);

                originalCheckBox.trigger('click');

                originalCheckBox.attr('checked', isChecked);
                checkBox.find('.tzCBContent').html(labels[isChecked ? 0 : 1]);
            });

            // Trigger 'checked' if the original changes & the new one will be updated
            originalCheckBox.bind('checked', function () {
                checkBox.click();
            });

            originalCheckBox.change(function () { checkBox.click(); });

            originalCheckBox.focusin(function () { checkBox.addClass("focus"); container.find(".tzCBPart").addClass("focus"); }).focusout(function () { checkBox.removeClass("focus"); container.find(".tzCBPart").removeClass("focus"); });

        });
    };
})(jQuery);<commit_msg>fixed js validation issues with the checkbox plugin<commit_after>(function ($) {
    $.fn.tzCheckbox = function (options) {

        // Default On / Off labels:

        options = $.extend({
            labels: ['ON', 'OFF']
        }, options);

        return this.each(function () {
            var originalCheckBox = $(this),
				labels = [];

            // Checking for the data-on / data-off HTML5 data attributes:
            if (originalCheckBox.data('on')) {
                labels[0] = originalCheckBox.data('on');
                labels[1] = originalCheckBox.data('off');
            }
            else labels = options.labels;

            // Creating the new checkbox markup:
            var checkBox = $('', {
                "class": 'tzCheckBox ' + (this.checked ? 'checked' : ''),
                html: '' + labels[this.checked ? 0 : 1] +
						''
            });

            // -- Original Code, just hides the checkbox -- //
            // Inserting the new checkbox, and hiding the original:
            //checkBox.insertAfter(originalCheckBox.hide());

            // -- Replacement code to try to get keyboard changes working -- //
            var hidden = originalCheckBox.siblings("input[type='hidden'][name='" + originalCheckBox.attr("id") + "']");

            // put the checkbox and everything into a container
            var container = $("", { "class": 'tzCheckBox-Container' });
            container.append(checkBox);
            container.insertAfter(originalCheckBox);

            // move the original checkbox controls
            container.append(originalCheckBox);
            container.append(hidden);

            checkBox.click(function () {
                checkBox.toggleClass('checked');

                var isChecked = checkBox.hasClass('checked');

                // Synchronizing the original checkbox:
                originalCheckBox.attr('checked', isChecked);
                checkBox.find('.tzCBContent').html(labels[isChecked ? 0 : 1]);

                originalCheckBox.trigger('click');

                originalCheckBox.attr('checked', isChecked);
                checkBox.find('.tzCBContent').html(labels[isChecked ? 0 : 1]);
            });

            // Trigger 'checked' if the original changes & the new one will be updated
            originalCheckBox.bind('checked', function () {
                checkBox.click();
            });

            originalCheckBox.change(function () { checkBox.click(); });

            originalCheckBox.focusin(function () { checkBox.addClass("focus"); container.find(".tzCBPart").addClass("focus"); }).focusout(function () { checkBox.removeClass("focus"); container.find(".tzCBPart").removeClass("focus"); });

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


<commit_before>/* =========================================================
 * bootstrap-timepicker.js
 * http://www.github.com/jdewit/bootstrap-timepicker
 * =========================================================
 * Copyright 2012
 *
 * Created By:
 * Joris de Wit @joris_dewit
 * Gilbert @mindeavor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

!function($) {

    "use strict"; // jshint ;_;

    /* TIMEPICKER PUBLIC CLASS DEFINITION
     * ================================== */
    var Timepicker = function(element, options) {
        this.$element = $(element);
        this.options = $.extend({}, $.fn.timepicker.defaults, options, this.$element.data());
        this.minuteStep = this.options.minuteStep || this.minuteStep;
        this.showMeridian = this.options.showMeridian || this.showMeridian;
        this.disableFocus = this.options.disableFocus || this.disableFocus;
        this.template = this.options.template || this.template;
        this.defaultTime = this.options.defaultTime || this.defaultTime;
        this.open = false;
        this.init();
    };

    Timepicker.prototype = {

        constructor: Timepicker

        , init: function () {

            this.$element
                .on('click', $.proxy(this.show, this))
                .on('keyup', $.proxy(this.updateFromElementVal, this))
            ;

            this.$widget = $(this.getTemplate()).appendTo('body');

            this.$widget.on('click', $.proxy(this.click, this));

            this.setDefaultTime(this.defaultTime);
        }

        , show: function(e) {
            e.stopPropagation();
            e.preventDefault();

            this.$element.trigger('show');

            $('html').on('click.timepicker.data-api', $.proxy(this.hide, this));

            if (true === this.disableFocus) {
                this.$element.blur();
            }

            var pos = $.extend({}, this.$element.offset(), {
                height: this.$element[0].offsetHeight
            });

            if (this.options.template === 'modal') {
//                this.$widget.css({
//                    top: pos.top + pos.height
//                })

                this.$widget.modal('show');
            } else {
                this.$widget.css({
                    top: pos.top + pos.height
                    , left: pos.left
                })

                if (!this.open) {
                    this.$widget.addClass('open');
                }
            }

            this.open = true;
            this.$element.trigger('shown');

            return this;
        }

        , hide: function(){
            this.$element.trigger('hide');

            $('html').off('click.timepicker.data-api', $.proxy(this.hide, this));

            if (this.options.template === 'modal') {
                this.$widget.modal('hide');
            } else {
                this.$widget.removeClass('open');
            }
            this.open = false;
            this.$element.trigger('hidden');

            return this;
        }

        , setValues: function(time) {
            var meridian, match = time.match(/(AM|PM)/i);
            if (match) {
                meridian = match[1];
            }
            time = $.trim(time.replace(/(PM|AM)/i, ''));
            var timeArray = time.split(':');

            this.meridian = meridian;
            this.hour = parseInt(timeArray[0], 10);
            this.minute = parseInt(timeArray[1], 10);
        }

        , setDefaultTime: function(defaultTime){
            if (defaultTime) {
                if (defaultTime === 'current') {
                    var dTime = new Date();
                    var hours = dTime.getHours();
                    var minutes = Math.floor(dTime.getMinutes() / this.minuteStep) * this.minuteStep;
                    var meridian = "AM";
                    if ( this.showMeridian ){
                        if (hours === 0) {
                            hours = 12;
                        } else if (hours > 12) {
                            hours = hours - 12;
                            meridian = "PM";
                        } else {
                           meridian = "AM";
                        }
                    }
                    this.hour = hours;
                    this.minute = minutes;
                    this.meridian = meridian;
                } else {
                    this.setValues(defaultTime);
                }
                this.update();
            }
        }

        , formatTime: function(hour, minute, meridian) {
            hour = hour < 10 ? '0' + hour : hour;
            minute = minute < 10 ? '0' + minute : minute;

            return hour + ':' + minute + ( this.showMeridian ? ' ' + meridian : '' );
        }

        , getTime: function() {
            return this.formatTime(this.hour, this.minute, this.meridian);
        }

        , setTime: function(time) {
            this.setValues(time);
            this.update();
        }

        , updateElement: function() {
            var time = this.getTime();

            this.$element.val(time).change();
        }

        , updateWidget: function() {
            this.$widget
                .find('td.bootstrap-timepicker-hour').text(this.hour).end()
                .find('td.bootstrap-timepicker-minute').text(this.minute < 10 ? '0' + this.minute : this.minute).end()
                .find('td.bootstrap-timepicker-meridian').text(this.meridian);
        }

        , update: function() {
            this.updateElement();
            this.updateWidget();
        }

        , updateFromElementVal: function () {
            var time = this.$element.val();
            if (time) {
                this.setValues(time);
                this.updateWidget();
            }
        }

        , click: function(e) {
            e.stopPropagation();
            e.preventDefault();

            if (true !== this.disableFocus) {
                this.$element.focus();
            }

            var action = $(e.target).closest('a').data('action');
            if (action) {
                this[action]();
                this.update();
            }

        }

        , incrementHour: function() {
            if ( this.showMeridian ) {
                if ( this.hour === 12 ) {
                    this.hour = 1;
                    return this.toggleMeridian();
                }
            }
            if ( this.hour === 23 ) {
                return this.hour = 0;
            }
            this.hour = this.hour + 1;
        }

        , decrementHour: function() {
            if ( this.showMeridian ) {
                if (this.hour === 1) {
                    this.hour = 12;
                    return this.toggleMeridian();
                }
            }
            if (this.hour === 0) {
                return this.hour = 23;
            }
            this.hour = this.hour - 1;
        }

        , incrementMinute: function() {
            var newVal = this.minute + this.minuteStep - (this.minute % this.minuteStep);
            if (newVal > 59) {
                this.incrementHour();
                this.minute = newVal - 60;
            } else {
                this.minute = newVal;
            }
        }

        , decrementMinute: function() {
            var newVal = this.minute - this.minuteStep;
            if (newVal < 0) {
                this.decrementHour();
                this.minute = newVal + 60;
            } else {
                this.minute = newVal;
            }
        }

        , toggleMeridian: function() {
            this.meridian = this.meridian === 'AM' ? 'PM' : 'AM';

            this.update();
        }

        , getTemplate: function() {
            if (this.options.templates[this.options.template]) {
                return this.options.templates[this.options.template];
            }
            var template;
            switch(this.options.template) {
                case 'modal':
                    template = '
'+
                                   '
'+
                                       '×'+
                                       '
Pick a Time
'+
                                   '
'+
                                   '
'+
                                       '
'+
                                           '
'+
                                               '	'+
                                               '	'+
                                               '	'+
                                               ( this.showMeridian ? '	' : '' ) +
                                           '
'+
                                           '
'+
                                               '	 '+
                                               ':	'+
                                               '	 '+
                                               ( this.showMeridian ? '	' : '' ) +
                                           '
'+
                                           '
'+
                                               '	'+
                                               '	'+
                                               '	'+
                                               ( this.showMeridian ? '	' : '' ) +
                                           '
'+
                                       '
'+
                                   '
'+
                                   '
'+
                                       'Ok'+
                                   '
'+
                               '
';

                break;
                case 'dropdown':
                    template = '
'+
                                   '
'+
                                       '
'+
                                           '	'+
                                           '	'+
                                           '	'+
                                           ( this.showMeridian ? '	' : '' ) +
                                       '
'+
                                       '
'+
                                           '	 '+
                                           ':	'+
                                           '	 '+
                                           ( this.showMeridian ? '	' : '' ) +
                                       '
'+
                                       '
'+
                                           '	'+
                                           '	'+
                                           '	'+
                                           ( this.showMeridian ? '	' : '' ) +
                                       '
'+
                                   '
'+
                               '
';
                break;

            }
            return template;
        }
    };

    /* TIMEPICKER PLUGIN DEFINITION
     * =========================== */

    $.fn.timepicker = function (option) {
        return this.each(function () {
            var $this = $(this)
            , data = $this.data('timepicker')
            , options = typeof option == 'object' && option;
            if (!data) {
                $this.data('timepicker', (data = new Timepicker(this, options)));
            }
            if (typeof option == 'string') {
                data[option]();
            }
        })
    }

    $.fn.timepicker.defaults = {
      minuteStep: 15
    , disableFocus: false
    , defaultTime: 'current'
    , showMeridian: true
    , template: 'dropdown'
    , templates: {} // set custom templates
    }

    $.fn.timepicker.Constructor = Timepicker

    /* TIMEPICKER DATA-API
     * ================== */

    $(function () {
        $('body').on('focus.timepicker.data-api', '[data-provide="timepicker"]', function (e) {
            var $this = $(this);
            if ($this.data('timepicker')) {
                return;
            }
            e.preventDefault();
            $this.timepicker($this.data());
        })
    })
}(window.jQuery);
<commit_msg>added 'value' option for setting value of timepicker to value of element<commit_after>/* =========================================================
 * bootstrap-timepicker.js
 * http://www.github.com/jdewit/bootstrap-timepicker
 * =========================================================
 * Copyright 2012
 *
 * Created By:
 * Joris de Wit @joris_dewit
 * Gilbert @mindeavor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

!function($) {

    "use strict"; // jshint ;_;

    /* TIMEPICKER PUBLIC CLASS DEFINITION
     * ================================== */
    var Timepicker = function(element, options) {
        this.$element = $(element);
        this.options = $.extend({}, $.fn.timepicker.defaults, options, this.$element.data());
        this.minuteStep = this.options.minuteStep || this.minuteStep;
        this.showMeridian = this.options.showMeridian || this.showMeridian;
        this.disableFocus = this.options.disableFocus || this.disableFocus;
        this.template = this.options.template || this.template;
        this.defaultTime = this.options.defaultTime || this.defaultTime;
        this.open = false;
        this.init();
    };

    Timepicker.prototype = {

        constructor: Timepicker

        , init: function () {

            this.$element
                .on('click', $.proxy(this.show, this))
                .on('keyup', $.proxy(this.updateFromElementVal, this))
            ;

            this.$widget = $(this.getTemplate()).appendTo('body');

            this.$widget.on('click', $.proxy(this.click, this));

            this.setDefaultTime(this.defaultTime);
        }

        , show: function(e) {
            e.stopPropagation();
            e.preventDefault();

            this.$element.trigger('show');

            $('html').on('click.timepicker.data-api', $.proxy(this.hide, this));

            if (true === this.disableFocus) {
                this.$element.blur();
            }

            var pos = $.extend({}, this.$element.offset(), {
                height: this.$element[0].offsetHeight
            });

            if (this.options.template === 'modal') {
//                this.$widget.css({
//                    top: pos.top + pos.height
//                })

                this.$widget.modal('show');
            } else {
                this.$widget.css({
                    top: pos.top + pos.height
                    , left: pos.left
                })

                if (!this.open) {
                    this.$widget.addClass('open');
                }
            }

            this.open = true;
            this.$element.trigger('shown');

            return this;
        }

        , hide: function(){
            this.$element.trigger('hide');

            $('html').off('click.timepicker.data-api', $.proxy(this.hide, this));

            if (this.options.template === 'modal') {
                this.$widget.modal('hide');
            } else {
                this.$widget.removeClass('open');
            }
            this.open = false;
            this.$element.trigger('hidden');

            return this;
        }

        , setValues: function(time) {
            var meridian, match = time.match(/(AM|PM)/i);
            if (match) {
                meridian = match[1];
            }
            // .split(/^([0-9]+):([0-9]+) (AM|PM)$/)
            time = $.trim(time.replace(/(PM|AM)/i, ''));
            var timeArray = time.split(':');

            this.meridian = meridian;
            this.hour = parseInt(timeArray[0], 10);
            this.minute = parseInt(timeArray[1], 10);
        }

        , setDefaultTime: function(defaultTime){
            if (defaultTime) {
                if (defaultTime === 'current') {
                    var dTime = new Date();
                    var hours = dTime.getHours();
                    var minutes = Math.floor(dTime.getMinutes() / this.minuteStep) * this.minuteStep;
                    var meridian = "AM";
                    if ( this.showMeridian ) {
                        if (hours === 0) {
                            hours = 12;
                        } else if (hours > 12) {
                            hours = hours - 12;
                            meridian = "PM";
                        } else {
                           meridian = "AM";
                        }
                    }
                    this.hour = hours;
                    this.minute = minutes;
                    this.meridian = meridian;
                } else if (defaultTime === 'value') {
                    this.setValues( this.$element.val() );
                } else {
                    this.setValues(defaultTime);
                }
                this.update();
            }
        }

        , formatTime: function(hour, minute, meridian) {
            hour = hour < 10 ? '0' + hour : hour;
            minute = minute < 10 ? '0' + minute : minute;

            return hour + ':' + minute + ( this.showMeridian ? ' ' + meridian : '' );
        }

        , getTime: function() {
            return this.formatTime(this.hour, this.minute, this.meridian);
        }

        , setTime: function(time) {
            this.setValues(time);
            this.update();
        }

        , updateElement: function() {
            var time = this.getTime();

            this.$element.val(time).change();
        }

        , updateWidget: function() {
            this.$widget
                .find('td.bootstrap-timepicker-hour').text(this.hour).end()
                .find('td.bootstrap-timepicker-minute').text(this.minute < 10 ? '0' + this.minute : this.minute).end()
                .find('td.bootstrap-timepicker-meridian').text(this.meridian);
        }

        , update: function() {
            this.updateElement();
            this.updateWidget();
        }

        , updateFromElementVal: function () {
            var time = this.$element.val();
            if (time) {
                this.setValues(time);
                this.updateWidget();
            }
        }

        , click: function(e) {
            e.stopPropagation();
            e.preventDefault();

            if (true !== this.disableFocus) {
                this.$element.focus();
            }

            var action = $(e.target).closest('a').data('action');
            if (action) {
                this[action]();
                this.update();
            }

        }

        , incrementHour: function() {
            if ( this.showMeridian ) {
                if ( this.hour === 12 ) {
                    this.hour = 1;
                    return this.toggleMeridian();
                }
            }
            if ( this.hour === 23 ) {
                return this.hour = 0;
            }
            this.hour = this.hour + 1;
        }

        , decrementHour: function() {
            if ( this.showMeridian ) {
                if (this.hour === 1) {
                    this.hour = 12;
                    return this.toggleMeridian();
                }
            }
            if (this.hour === 0) {
                return this.hour = 23;
            }
            this.hour = this.hour - 1;
        }

        , incrementMinute: function() {
            var newVal = this.minute + this.minuteStep - (this.minute % this.minuteStep);
            if (newVal > 59) {
                this.incrementHour();
                this.minute = newVal - 60;
            } else {
                this.minute = newVal;
            }
        }

        , decrementMinute: function() {
            var newVal = this.minute - this.minuteStep;
            if (newVal < 0) {
                this.decrementHour();
                this.minute = newVal + 60;
            } else {
                this.minute = newVal;
            }
        }

        , toggleMeridian: function() {
            this.meridian = this.meridian === 'AM' ? 'PM' : 'AM';

            this.update();
        }

        , getTemplate: function() {
            if (this.options.templates[this.options.template]) {
                return this.options.templates[this.options.template];
            }
            var template;
            switch(this.options.template) {
                case 'modal':
                    template = '
'+
                                   '
'+
                                       '×'+
                                       '
Pick a Time
'+
                                   '
'+
                                   '
'+
                                       '
'+
                                           '
'+
                                               '	'+
                                               '	'+
                                               '	'+
                                               ( this.showMeridian ? '	' : '' ) +
                                           '
'+
                                           '
'+
                                               '	 '+
                                               ':	'+
                                               '	 '+
                                               ( this.showMeridian ? '	' : '' ) +
                                           '
'+
                                           '
'+
                                               '	'+
                                               '	'+
                                               '	'+
                                               ( this.showMeridian ? '	' : '' ) +
                                           '
'+
                                       '
'+
                                   '
'+
                                   '
'+
                                       'Ok'+
                                   '
'+
                               '
';

                break;
                case 'dropdown':
                    template = '
'+
                                   '
'+
                                       '
'+
                                           '	'+
                                           '	'+
                                           '	'+
                                           ( this.showMeridian ? '	' : '' ) +
                                       '
'+
                                       '
'+
                                           '	 '+
                                           ':	'+
                                           '	 '+
                                           ( this.showMeridian ? '	' : '' ) +
                                       '
'+
                                       '
'+
                                           '	'+
                                           '	'+
                                           '	'+
                                           ( this.showMeridian ? '	' : '' ) +
                                       '
'+
                                   '
'+
                               '
';
                break;

            }
            return template;
        }
    };

    /* TIMEPICKER PLUGIN DEFINITION
     * =========================== */

    $.fn.timepicker = function (option) {
        return this.each(function () {
            var $this = $(this)
            , data = $this.data('timepicker')
            , options = typeof option == 'object' && option;
            if (!data) {
                $this.data('timepicker', (data = new Timepicker(this, options)));
            }
            if (typeof option == 'string') {
                data[option]();
            }
        })
    }

    $.fn.timepicker.defaults = {
      minuteStep: 15
    , disableFocus: false
    , defaultTime: 'current'
    , showMeridian: true
    , template: 'dropdown'
    , templates: {} // set custom templates
    }

    $.fn.timepicker.Constructor = Timepicker

    /* TIMEPICKER DATA-API
     * ================== */

    $(function () {
        $('body').on('focus.timepicker.data-api', '[data-provide="timepicker"]', function (e) {
            var $this = $(this);
            if ($this.data('timepicker')) {
                return;
            }
            e.preventDefault();
            $this.timepicker($this.data());
        })
    })
}(window.jQuery);
<|endoftext|>


<commit_before>angular.module('team-task')
    .controller('WorkforceController', ['$scope', '$rootScope', '$state', 'Atividade', 'Time',
        'Pessoa', '$stateParams', 'Projeto', '$filter', '$uibModal',
        function ($scope, $rootScope, $state, Atividade, Time, Pessoa, $stateParams, Projeto, $filter, $uibModal) {
            $scope.showLoading = false;

            function loadTable() {
                $scope.showLoading = true;

                Pessoa.getById($stateParams.id).then(function (pessoa) {
                    if (pessoa) {

                        var qTime = {
                            "recursos": $stateParams.id
                        };
                        Time.query(qTime).then(function (times) {
                            if (times[0]) {
                                var listaTimes = [];
                                for (var i = 0; i < times.length; i++) {
                                    listaTimes.push(times[i]._id.$oid);
                                }

                                $scope.cargaPessoa = pessoa;
                                $scope.ganttData = [];

                                var aQtdQuery = {
                                    "time": {
                                        "$in": listaTimes
                                    },
                                    "designado": pessoa._id.$oid
                                };

                                Atividade.query(aQtdQuery).then(function (atividades) {

                                    for (var indexTimeAtividade = 0; indexTimeAtividade < atividades.length; indexTimeAtividade++) {
                                        var time = $filter('filter')(times, {"_id" : {"$oid" : atividades[indexTimeAtividade].time}});
                                        var nomeTime = "";
                                        if(time && time.length > 0) {
                                            nomeTime = time[0].nome + " / ";
                                        }
                                        var rowAt = {
                                            "name": nomeTime + atividades[indexTimeAtividade].nome,
                                            "time": time,
                                            "atividade": atividades[indexTimeAtividade]
                                        };
                                        rowAt.tasks = [];
                                        rowAt.tasks.push({
                                            "name": atividades[indexTimeAtividade].nome,
                                            "from": moment(atividades[indexTimeAtividade].inicio.$date),
                                            "to": moment(atividades[indexTimeAtividade].fim.$date),
                                            "color": "#F1C232",
                                            "status": atividades[indexTimeAtividade].status
                                        });
                                        $scope.ganttData.push(rowAt);
                                    }

                                    var pQtdQuery = {
                                        "status": "Ativo",
                                        "atividades.designado": pessoa._id.$oid
                                    };
                                    Projeto.query(pQtdQuery).then(function (projetos) {
                                        for (var p = 0; p < projetos.length; p++) {
                                            for (var at = 0; at < projetos[p].atividades.length; at++) {
                                                if (projetos[p].atividades[at].designado === pessoa._id.$oid) {
                                                    var rowPr = {
                                                        "name": projetos[p].nome + " / " + projetos[p].atividades[at].nome,
                                                        "atividade": projetos[p].atividades[at],
                                                        "projeto": projetos[p],
                                                        "indiceAt": at
                                                    };
                                                    rowPr.tasks = [];
                                                    rowPr.tasks.push({
                                                        "name": projetos[p].atividades[at].nome,
                                                        "from": moment(projetos[p].atividades[at].inicio.$date),
                                                        "to": moment(projetos[p].atividades[at].fim.$date),
                                                        "color": "#9FC5F8",
                                                        "status": projetos[p].atividades[at].status
                                                    });
                                                    $scope.ganttData.push(rowPr);
                                                }
                                            }
                                        }
                                    });
                                });
                            }
                        });
                    }
                });

                $scope.showLoading = false;
            }

            $scope.getColumnWidth = function(widthEnabled, scale, zoom) {
                if (!widthEnabled) {
                    return undefined;
                }

                if (scale.match(/.*?week.*?/)) {
                    return 150 * zoom;
                }

                if (scale.match(/.*?month.*?/)) {
                    return 300 * zoom;
                }

                if (scale.match(/.*?quarter.*?/)) {
                    return 500 * zoom;
                }

                if (scale.match(/.*?year.*?/)) {
                    return 800 * zoom;
                }
                return 40 * zoom;
            };

            $scope.editarAtividade = function (model) {
                if(model.projeto) {
                    $uibModal
                        .open({
                            templateUrl: 'views/modal/edit-activity.html',
                            controller: 'ModalEditActivityController',
                            resolve: {
                                projetoSelecionado: function () {
                                    return model.projeto;
                                },
                                indice: function () {
                                    return model.indiceAt;
                                }
                            }
                        }).result.then(function () {
                            loadTable();
                            $rootScope.$emit("CallLoadMenus", {});
                        }, function () {
                        });
                } else {
                    $uibModal
                        .open({
                            templateUrl: 'views/modal/edit-team-activity.html',
                            controller: 'ModalEditTeamActivityController',
                            resolve: {
                                timeSelecionado: function () {
                                    return model.time[0];
                                },
                                atividadeSelecionada: function () {
                                    return model.atividade;
                                }
                            }
                        }).result.then(function () {
                            loadTable();
                            $rootScope.$emit("CallLoadMenus", {});
                        }, function () {
                        });
                }
            };

            $scope.mostrarDetalheAtividade = function (model) {

                if(model.projeto) {
                    $uibModal
                        .open({
                            templateUrl: 'views/modal/view-activity.html',
                            controller: 'ModalViewActivityController',
                            resolve: {
                                projetoSelecionado: function () {
                                    return model.projeto;
                                },
                                indice: function () {
                                    return model.indiceAt;
                                }
                            }
                        }).result.then(function () {}, function () {});
                } else {
                    $uibModal
                        .open({
                            templateUrl: 'views/modal/view-team-activity.html',
                            controller: 'ModalViewTeamActivityController',
                            resolve: {
                                atividadeSelecionada: function () {
                                    return model.atividade;
                                }
                            }
                        }).result.then(function () {}, function () {});
                }
            };

            $scope.filtro = [];
            $scope.filterChange = function () {
                if($scope.filtro) {
                    var listaFiltro = [];
                    if ($scope.filtro[0]) {
                        listaFiltro.push("aguardando");
                    }
                    if ($scope.filtro[1]) {
                        listaFiltro.push("iniciada");
                    }
                    if ($scope.filtro[2]) {
                        listaFiltro.push("concluída");
                    }
                    if(listaFiltro.length > 0) {
                        $scope.ganttOptions.filtertask = listaFiltro;
                    } else {
                        $scope.ganttOptions.filtertask = "";
                    }
                } else {
                    $scope.ganttOptions.filtertask = "";
                }
                $scope.api.rows.refresh();
            };

            $scope.filterFunction = function (item) {
                if(item && item.model) {
                    if($scope.ganttOptions.filtertask) {
                        return $scope.ganttOptions.filtertask.indexOf(item.model.status.toLowerCase()) > -1;
                    } else {
                        return false;
                    }
                }
            };

            $scope.initWorkforce = function () {
                $scope.filtro = [true, true, true];
                $scope.dateFormat = "dddd, DD/MM/YYYY";
                $scope.ganttOptions = {
                    "zoom": 1,
                    "scale": "week",
                    "width": true,
                    "currentDate": 'line',
                    "tableHeaders": {'model.name': 'Atividade'},
                    "daily": true,
                    "sortMode": "from",
                    "contents": {
                        'model.name': '{{getValue()}}' +
                        ' '+
                        ''
                    },
                    "filtertask": ["aguardando", "iniciada", "concluída"],
                    api: function(api) {
                        $scope.api = api;
                    }
                };
                loadTable();
            };
        }]);<commit_msg>ajuste na ordenacao<commit_after>angular.module('team-task')
    .controller('WorkforceController', ['$scope', '$rootScope', '$state', 'Atividade', 'Time',
        'Pessoa', '$stateParams', 'Projeto', '$filter', '$uibModal',
        function ($scope, $rootScope, $state, Atividade, Time, Pessoa, $stateParams, Projeto, $filter, $uibModal) {
            $scope.showLoading = false;

            function loadTable() {
                $scope.showLoading = true;

                Pessoa.getById($stateParams.id).then(function (pessoa) {
                    if (pessoa) {

                        var qTime = {
                            "recursos": $stateParams.id
                        };
                        Time.query(qTime).then(function (times) {
                            if (times[0]) {
                                var listaTimes = [];
                                for (var i = 0; i < times.length; i++) {
                                    listaTimes.push(times[i]._id.$oid);
                                }

                                $scope.cargaPessoa = pessoa;
                                $scope.ganttData = [];

                                var aQtdQuery = {
                                    "time": {
                                        "$in": listaTimes
                                    },
                                    "designado": pessoa._id.$oid
                                };

                                Atividade.query(aQtdQuery).then(function (atividades) {

                                    for (var indexTimeAtividade = 0; indexTimeAtividade < atividades.length; indexTimeAtividade++) {
                                        var time = $filter('filter')(times, {"_id" : {"$oid" : atividades[indexTimeAtividade].time}});
                                        var nomeTime = "";
                                        if(time && time.length > 0) {
                                            nomeTime = time[0].nome + " / ";
                                        }
                                        var rowAt = {
                                            "name": nomeTime + atividades[indexTimeAtividade].nome,
                                            "time": time,
                                            "atividade": atividades[indexTimeAtividade]
                                        };
                                        rowAt.tasks = [];
                                        rowAt.tasks.push({
                                            "name": atividades[indexTimeAtividade].nome,
                                            "from": moment(atividades[indexTimeAtividade].inicio.$date),
                                            "to": moment(atividades[indexTimeAtividade].fim.$date),
                                            "color": "#F1C232",
                                            "status": atividades[indexTimeAtividade].status
                                        });
                                        $scope.ganttData.push(rowAt);
                                    }

                                    var pQtdQuery = {
                                        "status": "Ativo",
                                        "atividades.designado": pessoa._id.$oid
                                    };
                                    Projeto.query(pQtdQuery).then(function (projetos) {
                                        for (var p = 0; p < projetos.length; p++) {
                                            for (var at = 0; at < projetos[p].atividades.length; at++) {
                                                if (projetos[p].atividades[at].designado === pessoa._id.$oid) {
                                                    var rowPr = {
                                                        "name": projetos[p].nome + " / " + projetos[p].atividades[at].nome,
                                                        "atividade": projetos[p].atividades[at],
                                                        "projeto": projetos[p],
                                                        "indiceAt": at
                                                    };
                                                    rowPr.tasks = [];
                                                    rowPr.tasks.push({
                                                        "name": projetos[p].atividades[at].nome,
                                                        "from": moment(projetos[p].atividades[at].inicio.$date),
                                                        "to": moment(projetos[p].atividades[at].fim.$date),
                                                        "color": "#9FC5F8",
                                                        "status": projetos[p].atividades[at].status
                                                    });
                                                    $scope.ganttData.push(rowPr);
                                                }
                                            }
                                        }
                                    });
                                });
                            }
                        });
                    }
                });

                $scope.showLoading = false;
            }

            $scope.getColumnWidth = function(widthEnabled, scale, zoom) {
                if (!widthEnabled) {
                    return undefined;
                }

                if (scale.match(/.*?week.*?/)) {
                    return 150 * zoom;
                }

                if (scale.match(/.*?month.*?/)) {
                    return 300 * zoom;
                }

                if (scale.match(/.*?quarter.*?/)) {
                    return 500 * zoom;
                }

                if (scale.match(/.*?year.*?/)) {
                    return 800 * zoom;
                }
                return 40 * zoom;
            };

            $scope.editarAtividade = function (model) {
                if(model.projeto) {
                    $uibModal
                        .open({
                            templateUrl: 'views/modal/edit-activity.html',
                            controller: 'ModalEditActivityController',
                            resolve: {
                                projetoSelecionado: function () {
                                    return model.projeto;
                                },
                                indice: function () {
                                    return model.indiceAt;
                                }
                            }
                        }).result.then(function () {
                            loadTable();
                            $rootScope.$emit("CallLoadMenus", {});
                        }, function () {
                        });
                } else {
                    $uibModal
                        .open({
                            templateUrl: 'views/modal/edit-team-activity.html',
                            controller: 'ModalEditTeamActivityController',
                            resolve: {
                                timeSelecionado: function () {
                                    return model.time[0];
                                },
                                atividadeSelecionada: function () {
                                    return model.atividade;
                                }
                            }
                        }).result.then(function () {
                            loadTable();
                            $rootScope.$emit("CallLoadMenus", {});
                        }, function () {
                        });
                }
            };

            $scope.mostrarDetalheAtividade = function (model) {

                if(model.projeto) {
                    $uibModal
                        .open({
                            templateUrl: 'views/modal/view-activity.html',
                            controller: 'ModalViewActivityController',
                            resolve: {
                                projetoSelecionado: function () {
                                    return model.projeto;
                                },
                                indice: function () {
                                    return model.indiceAt;
                                }
                            }
                        }).result.then(function () {}, function () {});
                } else {
                    $uibModal
                        .open({
                            templateUrl: 'views/modal/view-team-activity.html',
                            controller: 'ModalViewTeamActivityController',
                            resolve: {
                                atividadeSelecionada: function () {
                                    return model.atividade;
                                }
                            }
                        }).result.then(function () {}, function () {});
                }
            };

            $scope.filtro = [];
            $scope.filterChange = function () {
                if($scope.filtro) {
                    var listaFiltro = [];
                    if ($scope.filtro[0]) {
                        listaFiltro.push("aguardando");
                    }
                    if ($scope.filtro[1]) {
                        listaFiltro.push("iniciada");
                    }
                    if ($scope.filtro[2]) {
                        listaFiltro.push("concluída");
                    }
                    if(listaFiltro.length > 0) {
                        $scope.ganttOptions.filtertask = listaFiltro;
                    } else {
                        $scope.ganttOptions.filtertask = "";
                    }
                } else {
                    $scope.ganttOptions.filtertask = "";
                }
                $scope.api.rows.refresh();
            };

            $scope.filterFunction = function (item) {
                if(item && item.model) {
                    if($scope.ganttOptions.filtertask) {
                        return $scope.ganttOptions.filtertask.indexOf(item.model.status.toLowerCase()) > -1;
                    } else {
                        return false;
                    }
                }
            };

            $scope.initWorkforce = function () {
                $scope.filtro = [true, true, true];
                $scope.dateFormat = "dddd, DD/MM/YYYY";
                $scope.ganttOptions = {
                    "zoom": 1,
                    "scale": "week",
                    "width": true,
                    "currentDate": 'line',
                    "tableHeaders": {'model.name': 'Atividade'},
                    "daily": true,
                    "sortMode": ["model.time.nome", "model.projeto.nome", "from"],
                    "contents": {
                        'model.name': '{{getValue()}}' +
                        ' '+
                        ''
                    },
                    "filtertask": ["aguardando", "iniciada", "concluída"],
                    api: function(api) {
                        $scope.api = api;
                    }
                };
                loadTable();
            };
        }]);<|endoftext|>