<commit_before>function loadschedule() {
	var subst = 1;
	var prevdate;
	var tables = [];
	// EDIT THIS!
	var schoollink = 'gym';
	var link = 'http://www3.pj.nl/' + schoollink + '_info_leerlingen/subst_00';
	while (subst == 1) {
		parselink = link + subst + '.htm';
		var html = $($.parseHTML(parselink, document, false));
		date = html.match(/\d{2}-\d{2}-\d{4}/);
		if (prevdate == date || subst == 1){
			tables = tables.concat(html.match(/(<tr.*<\/tr>)/mg));
			subst = subst + 1;
			prevdate = date;
		} else {
			break;
		}
	}
	var dschedule = Titanium.Filesystem.getFile('schedulechanges.html');
	var template = Titanium.Filesystem.getFile('schedulechangestemplate.html');
	dschedule.write(template.read() + tables + '');
}

var win = Titanium.UI.createWindow({
	backgroundColor: 'white',
	exitOnClose: true
});

var mainview = Titanium.UI.createView({
	height:'72.5%',
	top:'15%'
});

win.add(mainview);

loadschedule();

var webview1 = Titanium.UI.createWebView({
	url:'schedulechanges.html'
});

var webview1EventListener = function() {
	webview1.reload();
};

mainview.add(webview1);

var webview2 = Titanium.UI.createWebView({
	url:'http://www3.pj.nl/infoschermgymnasium/'
});

var webview2EventListener = function() {
	webview2.reload();
};

var actionbar = Titanium.UI.createView({
	backgroundColor:'#dc006d',
	top:0,
	height:'15%'
});

var titlelabel = Titanium.UI.createLabel({
	text:'PJ Info',
	textAlign:'Titanium.UI.TEXT_ALIGNMENT_CENTER',
	color:'#fff',
	font:{fontSize:28}
});

actionbar.add(titlelabel);

var settingsbutton = Titanium.UI.createImageView({
	image:'settings.png',
	height:'60%',
	left:'5%'
});

settingsbutton.addEventListener('click',function(){
	var settingswin = Titanium.UI.createWindow({
		backgroundColor:'#fff'
	});

	var actionbar = Titanium.UI.createView({
		backgroundColor:'#dc006d',
		top:0,
		height:'15%'
	});

	var backbutton = Titanium.UI.createImageView({
		image:'back.png',
		height:'60%',
		left:'5%'
	});

	backbutton.addEventListener('click',function(e){
		settingswin.close();
	});

	actionbar.add(backbutton);

	var titlelabel = Titanium.UI.createLabel({
		text:'Instellingen',
		textAlign:'Titanium.UI.TEXT_ALIGNMENT_CENTER',
		color:'#fff',
		font:{fontSize:28}
	});

	actionbar.add(titlelabel);

	settingswin.add(actionbar);
	settingswin.open();
});

actionbar.add(settingsbutton);

var refreshbutton = Titanium.UI.createImageView({
	image:'refresh.png',
	height:'60%',
	right:'5%'
});

actionbar.add(refreshbutton);
win.add(actionbar);

var tabsview = Titanium.UI.createView({
	bottom:0,
	height:'15%',
	left:0,
	right:0
});

win.add(tabsview);

var label1 = Titanium.UI.createLabel({
	text:'Roosterwijzigingen',
	textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
	top:'15%',
	bottom:0,
	left:0,
	width:'43%',
	color:'#003c6d',
	backgroundColor:'#fff'
});

var label2 = Titanium.UI.createLabel({
	text:'Mededelingen',
	textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
	top:'15%',
	bottom:0,
	left:'44%',
	width:'34%',
	color:'#fff',
	backgroundColor:'#003c6d'
});

var imageview = Titanium.UI.createView({
	top:'15%',
	bottom:0,
	left:'79%',
	height:'85%',
	width:'21%',
	backgroundColor:'#003c6d'
});

var image = Titanium.UI.createImageView({
	image:'stentor.png'
});

imageview.add(image);

var divisionborder1 = Ti.UI.createView({
    backgroundColor:'#dc006d',
    top:'15%',
    bottom:0,
    width:'1%',
    left:'43%',
    right:'55%'
});

var divisionborder2 = Ti.UI.createView({
    backgroundColor:'#dc006d',
    top:'15%',
    bottom:0,
    width:'1%',
    left:'78%',
    right:'21%'
});

tabsview.add(divisionborder1);
tabsview.add(divisionborder2);

tabsview.add(label1);
tabsview.add(label2);
tabsview.add(imageview);

label1.addEventListener('click',function(){
	label1.color = '#003c6d';
	label1.backgroundColor = '#fff';

	label2.color = '#fff';
	label2.backgroundColor = '#003c6d';

	imageview.backgroundColor = '#003c6d';

	refreshbutton.removeEventListener('click',webview2EventListener);

	refreshbutton.addEventListener('click',webview1EventListener);

	mainview.remove(webview2);
	mainview.add(webview1);
});
label2.addEventListener('click',function(){
	label1.color = '#fff';
	label1.backgroundColor = '#003c6d';

	label2.color = '#003c6d';
	label2.backgroundColor = '#fff';

	imageview.backgroundColor = '#003c6d';

	refreshbutton.removeEventListener('click',webview1EventListener);

	refreshbutton.addEventListener('click',webview2EventListener);

	mainview.remove(webview1);
	mainview.add(webview2);
});
imageview.addEventListener('click',function(){
	label1.color = '#fff';
	label1.backgroundColor = '#003c6d';

	label2.color = '#fff';
	label2.backgroundColor = '#003c6d';

	imageview.backgroundColor = '#fff';

	mainview.remove(webview1);
	mainview.remove(webview2);
	actionbar.remove(refreshbutton);

	var stentorview = Titanium.UI.createView({
    	backgroundColor: '#fff',
    	height:'72.5%',
    	top:'15%'
	});

	var gwbutton = Ti.UI.createButton({
		title:'Gevleugelde Woorden insturen',
		height:70,
		width:170,
		backgroundColor: '#dc006d',
		color: '#fff'
	});

	gwbutton.addEventListener('click',function(e)
	{
	   	var emailDialog = Ti.UI.createEmailDialog();
		emailDialog.subject = "Gevleugelde Woorden via PJ Info";
		emailDialog.toRecipients = ['mennohellinga@zoho.com'];	// CHANGE BEFORE RELEASE!
		emailDialog.open();
	});

	label1.addEventListener('click',function(){
		actionbar.add(refreshbutton);
		mainview.remove(stentorview);
		mainview.add(webview1);
	});
	label2.addEventListener('click',function(){
		actionbar.add(refreshbutton);
		mainview.remove(stentorview);
		mainview.add(webview2);
	});

	stentorview.add(gwbutton);
	mainview.add(stentorview);
});

win.open();
<commit_msg>Blijf van mijn code af, JC!<commit_after>function loadschedule() {
	var subst = 1;
	var prevdate;
	var tables = [];
	// EDIT THIS!
	var schoollink = 'gym';
	var link = 'http://www3.pj.nl/' + schoollink + '_info_leerlingen/subst_00';
	while (1) {
		parselink = link + subst + '.htm';
		var html = $($.parseHTML(parselink, document, false));
		date = html.match(/\d{2}-\d{2}-\d{4}/);
		if (prevdate == date || subst == 1){
			tables = tables.concat(html.match(/(<tr.*<\/tr>)/mg));
			subst = subst + 1;
			prevdate = date;
		} else {
			break;
		}
	}
	var dschedule = Titanium.Filesystem.getFile('schedulechanges.html');
	var template = Titanium.Filesystem.getFile('schedulechangestemplate.html');
	dschedule.write(template.read() + tables + '');
}

var win = Titanium.UI.createWindow({
	backgroundColor: 'white',
	exitOnClose: true
});

var mainview = Titanium.UI.createView({
	height:'72.5%',
	top:'15%'
});

win.add(mainview);

loadschedule();

var webview1 = Titanium.UI.createWebView({
	url:'schedulechanges.html'
});

var webview1EventListener = function() {
	webview1.reload();
};

mainview.add(webview1);

var webview2 = Titanium.UI.createWebView({
	url:'http://www3.pj.nl/infoschermgymnasium/'
});

var webview2EventListener = function() {
	webview2.reload();
};

var actionbar = Titanium.UI.createView({
	backgroundColor:'#dc006d',
	top:0,
	height:'15%'
});

var titlelabel = Titanium.UI.createLabel({
	text:'PJ Info',
	textAlign:'Titanium.UI.TEXT_ALIGNMENT_CENTER',
	color:'#fff',
	font:{fontSize:28}
});

actionbar.add(titlelabel);

var settingsbutton = Titanium.UI.createImageView({
	image:'settings.png',
	height:'60%',
	left:'5%'
});

settingsbutton.addEventListener('click',function(){
	var settingswin = Titanium.UI.createWindow({
		backgroundColor:'#fff'
	});

	var actionbar = Titanium.UI.createView({
		backgroundColor:'#dc006d',
		top:0,
		height:'15%'
	});

	var backbutton = Titanium.UI.createImageView({
		image:'back.png',
		height:'60%',
		left:'5%'
	});

	backbutton.addEventListener('click',function(e){
		settingswin.close();
	});

	actionbar.add(backbutton);

	var titlelabel = Titanium.UI.createLabel({
		text:'Instellingen',
		textAlign:'Titanium.UI.TEXT_ALIGNMENT_CENTER',
		color:'#fff',
		font:{fontSize:28}
	});

	actionbar.add(titlelabel);

	settingswin.add(actionbar);
	settingswin.open();
});

actionbar.add(settingsbutton);

var refreshbutton = Titanium.UI.createImageView({
	image:'refresh.png',
	height:'60%',
	right:'5%'
});

actionbar.add(refreshbutton);
win.add(actionbar);

var tabsview = Titanium.UI.createView({
	bottom:0,
	height:'15%',
	left:0,
	right:0
});

win.add(tabsview);

var label1 = Titanium.UI.createLabel({
	text:'Roosterwijzigingen',
	textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
	top:'15%',
	bottom:0,
	left:0,
	width:'43%',
	color:'#003c6d',
	backgroundColor:'#fff'
});

var label2 = Titanium.UI.createLabel({
	text:'Mededelingen',
	textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
	top:'15%',
	bottom:0,
	left:'44%',
	width:'34%',
	color:'#fff',
	backgroundColor:'#003c6d'
});

var imageview = Titanium.UI.createView({
	top:'15%',
	bottom:0,
	left:'79%',
	height:'85%',
	width:'21%',
	backgroundColor:'#003c6d'
});

var image = Titanium.UI.createImageView({
	image:'stentor.png'
});

imageview.add(image);

var divisionborder1 = Ti.UI.createView({
    backgroundColor:'#dc006d',
    top:'15%',
    bottom:0,
    width:'1%',
    left:'43%',
    right:'55%'
});

var divisionborder2 = Ti.UI.createView({
    backgroundColor:'#dc006d',
    top:'15%',
    bottom:0,
    width:'1%',
    left:'78%',
    right:'21%'
});

tabsview.add(divisionborder1);
tabsview.add(divisionborder2);

tabsview.add(label1);
tabsview.add(label2);
tabsview.add(imageview);

label1.addEventListener('click',function(){
	label1.color = '#003c6d';
	label1.backgroundColor = '#fff';

	label2.color = '#fff';
	label2.backgroundColor = '#003c6d';

	imageview.backgroundColor = '#003c6d';

	refreshbutton.removeEventListener('click',webview2EventListener);

	refreshbutton.addEventListener('click',webview1EventListener);

	mainview.remove(webview2);
	mainview.add(webview1);
});
label2.addEventListener('click',function(){
	label1.color = '#fff';
	label1.backgroundColor = '#003c6d';

	label2.color = '#003c6d';
	label2.backgroundColor = '#fff';

	imageview.backgroundColor = '#003c6d';

	refreshbutton.removeEventListener('click',webview1EventListener);

	refreshbutton.addEventListener('click',webview2EventListener);

	mainview.remove(webview1);
	mainview.add(webview2);
});
imageview.addEventListener('click',function(){
	label1.color = '#fff';
	label1.backgroundColor = '#003c6d';

	label2.color = '#fff';
	label2.backgroundColor = '#003c6d';

	imageview.backgroundColor = '#fff';

	mainview.remove(webview1);
	mainview.remove(webview2);
	actionbar.remove(refreshbutton);

	var stentorview = Titanium.UI.createView({
    	backgroundColor: '#fff',
    	height:'72.5%',
    	top:'15%'
	});

	var gwbutton = Ti.UI.createButton({
		title:'Gevleugelde Woorden insturen',
		height:70,
		width:170,
		backgroundColor: '#dc006d',
		color: '#fff'
	});

	gwbutton.addEventListener('click',function(e)
	{
	   	var emailDialog = Ti.UI.createEmailDialog();
		emailDialog.subject = "Gevleugelde Woorden via PJ Info";
		emailDialog.toRecipients = ['mennohellinga@zoho.com'];	// CHANGE BEFORE RELEASE!
		emailDialog.open();
	});

	label1.addEventListener('click',function(){
		actionbar.add(refreshbutton);
		mainview.remove(stentorview);
		mainview.add(webview1);
	});
	label2.addEventListener('click',function(){
		actionbar.add(refreshbutton);
		mainview.remove(stentorview);
		mainview.add(webview2);
	});

	stentorview.add(gwbutton);
	mainview.add(stentorview);
});

win.open();
<|endoftext|>


<commit_before>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

// create tab group
var tabGroup = Titanium.UI.createTabGroup();

//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
    title:'Menu',
    backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var label1 = Titanium.UI.createLabel({
	color:'#999',
	text:'Dinner Bell',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto',
	bottom: '300'
});

win1.add(label1);

//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
    title:'Tab 2',
    backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
    icon:'KS_nav_ui.png',
    title:'Tab 2',
    window:win2
});

var label2 = Titanium.UI.createLabel({
	color:'#999',
	text:'I am Window 2',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win2.add(label2);

//////
var bvbottom = Titanium.UI.createButton({
	title : 'V-Bottom',
	width : 50,
	height: 40,
	top : 150,
	left : 180
});
bvbottom.addEventListener('click', function() {
	b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_BOTTOM;
});

win1.add(bvbottom);

//
//  add tabs
//
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);

// open tab group
tabGroup.open();
<commit_msg>button centered and labled \"Schedule Meals\"<commit_after>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

// create tab group
var tabGroup = Titanium.UI.createTabGroup();

//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
    title:'Menu',
    backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var label1 = Titanium.UI.createLabel({
	color:'#999',
	text:'Dinner Bell',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto',
	bottom: '300'
});

win1.add(label1);

//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
    title:'Tab 2',
    backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
    icon:'KS_nav_ui.png',
    title:'Tab 2',
    window:win2
});

var label2 = Titanium.UI.createLabel({
	color:'#999',
	text:'unavailable',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win2.add(label2);

//////
var bvbottom = Titanium.UI.createButton({
	title : 'Schedule Meals',
	width : 200,
	height: 40,
	top : 150,
	left : 60
});
bvbottom.addEventListener('click', function() {
	b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_BOTTOM;
});

win1.add(bvbottom);

//
//  add tabs
//
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);

// open tab group
tabGroup.open();
<|endoftext|>


<commit_before>Titanium.UI.setBackgroundImage('images/background.jpg');

var platformWidth = Ti.Platform.displayCaps.platformWidth;
var platformHeight = Ti.Platform.displayCaps.platformHeight;

//A function to make switching windows and adding lables easier

Ti.include("globalModel.js");
Ti.include("pickerModel.js");

Ti.include("introScreenView.js");
Ti.include("mainMenuView.js");
Ti.include("pokemonBattleView.js");
Ti.include("pokemonBattleHistoryView.js");
Ti.include("pokemonPickerView.js");
Ti.include("pokemonViewerView.js");
Ti.include("settingsView.js");

Ti.include("introVideoView.js");
Ti.include("introVideoController.js");

Ti.include("introScreenController.js");
Ti.include("mainMenuController.js");
Ti.include("pokemonBattleController.js");
Ti.include("pokemonPickerController.js");
Ti.include("pokemonViewerController.js");
Ti.include("pokemonBattleHistoryController.js");
Ti.include("settingsController.js");

//This opens the last window that the user was on
if(Ti.App.Properties.getBool('introWatched')){
	if (Ti.App.Properties.getString('lastWindow') == 'mainMenuView'){
		var text = 'Welcome ' + Ti.App.Properties.getString("PlayerName");
		switchWin(mainMenuView, text);
		}
	else if (Ti.App.Properties.getString('lastWindow') == 'battleHistory')
		switchWin(battleHistory, 'Battle History');

	else if (Ti.App.Properties.getString('lastWindow') == 'pokemonBattle')
		switchWin(pokemonBattle, 'Battle');

	else if (Ti.App.Properties.getString('lastWindow') == 'pokemonPicker')
		switchWin(pokemonPicker, 'Pokemon Picker');

	else if (Ti.App.Properties.getString('lastWindow') == 'pokemonViewer')
		switchWin(pokemonViewer, 'Pokemon Viewer');

	else if (Ti.App.Properties.getString('lastWindow') == 'settings')
		switchWin(settings, 'Settings');
}
// This opens the start screen if the app has never been run before or if the app settings have been wiped
if(!Ti.App.Properties.getBool('introWatched')){
	switchWin(introVideo);
}<commit_msg>temp fix to skip vid<commit_after>Titanium.UI.setBackgroundImage('images/background.jpg');

var platformWidth = Ti.Platform.displayCaps.platformWidth;
var platformHeight = Ti.Platform.displayCaps.platformHeight;

//A function to make switching windows and adding lables easier

Ti.include("globalModel.js");
Ti.include("pickerModel.js");

Ti.include("introScreenView.js");
Ti.include("mainMenuView.js");
Ti.include("pokemonBattleView.js");
Ti.include("pokemonBattleHistoryView.js");
Ti.include("pokemonPickerView.js");
Ti.include("pokemonViewerView.js");
Ti.include("settingsView.js");

Ti.include("introVideoView.js");
Ti.include("introVideoController.js");

Ti.include("introScreenController.js");
Ti.include("mainMenuController.js");
Ti.include("pokemonBattleController.js");
Ti.include("pokemonPickerController.js");
Ti.include("pokemonViewerController.js");
Ti.include("pokemonBattleHistoryController.js");
Ti.include("settingsController.js");

//This opens the last window that the user was on
if(Ti.App.Properties.getBool('introWatched')){
	if (Ti.App.Properties.getString('lastWindow') == 'mainMenuView'){
		var text = 'Welcome ' + Ti.App.Properties.getString("PlayerName");
		switchWin(mainMenuView, text);
		}
	else if (Ti.App.Properties.getString('lastWindow') == 'battleHistory')
		switchWin(battleHistory, 'Battle History');

	else if (Ti.App.Properties.getString('lastWindow') == 'pokemonBattle')
		switchWin(pokemonBattle, 'Battle');

	else if (Ti.App.Properties.getString('lastWindow') == 'pokemonPicker')
		switchWin(pokemonPicker, 'Pokemon Picker');

	else if (Ti.App.Properties.getString('lastWindow') == 'pokemonViewer')
		switchWin(pokemonViewer, 'Pokemon Viewer');

	else if (Ti.App.Properties.getString('lastWindow') == 'settings')
		switchWin(settings, 'Settings');
}
// This opens the start screen if the app has never been run before or if the app settings have been wiped
if(!Ti.App.Properties.getBool('introWatched')){
	switchWin(pokemonBattle);
}<|endoftext|>


<commit_before>'use strict'

class ResponseQueue {
  constructor (channel) {
    this.channel = channel
    this.callbacks = []
    this.channel.assertQueue('', {exclusive: true}, this._init.bind(this))
  }

  _init(err, q) {
    this.queue = q.queue
    this.channel.consume(this.queue, this._trigger.bind(this), {noAck: true})
  }

  _trigger (msg){
    msg.content = JSON.parse(msg.content)
    this.callbacks.forEach( (callback) => {
      callback(content, msg)
    })
  }

  onUpdate(callback) {
    this.callbacks.push(callback)
    return () => {
      this.callbacks.slice(this.callbacks.indexOf(callback), 1)
    }
  }
}

module.exports = ResponseQueue<commit_msg>Response returns full message<commit_after>'use strict'

class ResponseQueue {
  constructor (channel) {
    this.channel = channel
    this.callbacks = []
    this.channel.assertQueue('', {exclusive: true}, this._init.bind(this))
  }

  _init(err, q) {
    this.queue = q.queue
    this.channel.consume(this.queue, this._trigger.bind(this), {noAck: true})
  }

  _trigger (msg){
    msg.content = JSON.parse(msg.content)
    this.callbacks.forEach( (callback) => {
      callback(msg)
    })
  }

  onUpdate(callback) {
    this.callbacks.push(callback)
    return () => {
      this.callbacks.slice(this.callbacks.indexOf(callback), 1)
    }
  }
}

module.exports = ResponseQueue<|endoftext|>


<commit_before>var get = Ember.get, set = Ember.set, isArray = Ember.isArray, typeOf = Ember.typeOf;

/**
 * Ember.Selectize is an Ember View that encapsulates a Selectize component.
 * The goal is to use this as a near dropin replacement for Ember.Select.
 */
Ember.Selectize = Ember.View.extend({
  attributeBindings : ['multiple', 'placeholder','autocomplete'],
  classNames : ['ember-selectize'],

  autocomplete:'off',
  // Allows to use prompt (like in Ember.Select) or placeholder property
  placeholder: Ember.computed.alias('prompt'),
  tagName : 'select',

  /**
   * default object paths for value and label paths
   */
  optionValuePath : 'content.value',
  optionLabelPath : 'content.label',

  /**
   * The array of the default plugins to load into selectize
   */
  plugins: ['remove_button'],

  /**
   * Computed properties that hold the processed paths ('content.' replacement),
   * as it is done on Ember.Select
   */
  _valuePath : Ember.computed('optionValuePath',function(){
    return get(this,'optionValuePath').replace(/^content\.?/, '');
  }),
  _labelPath : Ember.computed('optionLabelPath',function(){
    return get(this,'optionLabelPath').replace(/^content\.?/, '');
  }),

  /**
   * This flag should be true when the element is present in the DOM and false when if isn't.
   * This helps to avoid triggering unecessary observers.
   */
  inDOM: false,

  /**
   * Pass true to 'create' property to enable tag creation mode.
   * When active, ember-selectize will send a 'create' action to its controller when a tag is created.
   * Alternatively, you can pass a string to 'createAction' property and
   * ember-selectize will activite tag creation mode send an action with that name to its controller.
   */
  create:false,
  createAction:'create',

  didInsertElement : function() {
    //View is now in DOM
    this.inDOM = true;

    //Normalize create property if createAction was set
    if(this.createAction && (this.createAction !== 'create'))
      this.create = true;

    //Create Selectize's instance
    //We proxy callbacks through jQuery's 'proxy' to have the callbacks context set to 'this'
    this.$().selectize({
      plugins: this.plugins,
      labelField : 'label',
      valueField : 'value',
      searchField : 'label',
      create: this.create ? $.proxy(this._create, this) : false,
      onItemAdd : $.proxy(this._onItemAdd, this),
      onItemRemove : $.proxy(this._onItemRemove, this),
      onType : $.proxy(this._onType, this)
    });

    //Save the created selectize instance
    this.selectize = this.$()[0].selectize;

    //Some changes to content, selection and disabled could have happened before the View was inserted into the DOM.
    //We trigger all the observers manually to account for those changes.
    this._disabledDidChange();
    this._contentDidChange();
    this._selectionDidChange();
  },
  willDestroyElement : function() {

    //Unbind observers
    this._contentWillChange();
    this._selectionWillChange();

    //Invoke Selectize's destroy
    this.selectize.destroy();

    //We are no longer in DOM
    this.inDOM = false;
  },
  /**
   * Event callback that is triggered when user creates a tag
   */
  _create:function(input,callback){
    // Delete user entered text
    this.selectize.setTextboxValue('');
    // Send action to controller
    get(this,'controller').send(get(this,'createAction'),input);
    // We cancel the creation here, so it's up to you to include the created element
    // in the content and selection property
    callback(null);
  },
  /**
   * Event callback that is triggered when user types in the input element
   */
  _onType:function(str){
    set(this,'filter',str);
  },
  /**
   * Event callback triggered when an item is added (when something is selected)
   * Here we need to update our selection property (if single selection) or array (if multiple selection)
   */
  _onItemAdd : function(value) {
    var content = get(this,'content');
    var selection = get(this,'selection');
    var multiple = get(this,'multiple');
    if(content){
      var obj = content.find(function(item){
        if(get(item,get(this,'_valuePath')) == value)
          return true;
      },this);
      if(multiple && isArray(selection) && obj){
        if(!selection.findBy(get(this,'_valuePath'),get(obj,get(this,'_valuePath'))))
          selection.addObject(obj);
      } else if(obj){
        if(!selection || (get(obj,get(this,'_valuePath')) !== get(selection,get(this,'_valuePath'))))
          set(this,'selection',obj);
      }
    }
  },
  /**
   * Event callback triggered when an item is removed (when something is deselected)
   * Here we need to update our selection property (if single selection, here set to null) or remove item from array (if multiple selection)
   */
  _onItemRemove : function(value) {
    if(this.removing) return;
    var content = get(this,'content');
    var selection = get(this,'selection');
    var multiple = get(this,'multiple');
    if(content){
      var obj = content.find(function(item){
        if(get(item,get(this,'_valuePath')) == value)
          return true;
      },this);
      if(multiple && isArray(selection) && obj){
        selection.removeObject(obj);
      } else if(!multiple){
        this.set('selection',null);
      }
    }
  },
    /**
   * Ember observer triggered before the selection property is changed
   * We need to unbind any array observers if we're in multiple selection
   */
  _selectionWillChange: Ember.beforeObserver(function() {

    var multiple = get(this, 'multiple');
    var selection = get(this, 'selection');
    if(selection && isArray(selection) && multiple) {
      selection.removeArrayObserver(this,  {
        willChange : 'selectionArrayWillChange',
        didChange : 'selectionArrayDidChange'
      });
      var len = selection ? get(selection, 'length') : 0;
      this.selectionArrayWillChange(selection, 0, len);
    }
  }, 'selection'),
  /**
   * Ember observer triggered when the selection property is changed
   * We need to bind an array observer when selection is multiple
   */
  _selectionDidChange : Ember.observer(function() {
    if(!this.inDOM) return;

    var multiple = get(this, 'multiple');
    var selection = get(this, 'selection');
    if (multiple) {
      if(selection) {
        if(!isArray(selection)){
          selection = Ember.A([selection]);
          set(this,'selection',selection);
          return;
        }
        selection.addArrayObserver(this, {
          willChange : 'selectionArrayWillChange',
          didChange : 'selectionArrayDidChange'
        });
      } else {
        set(this,'selection',[]);
        return;
      }
      var len = selection ? get(selection, 'length') : 0;
      this.selectionArrayDidChange(selection, 0, null, len);
    } else {
      if(selection) {
        this.selectize.addItem(get(selection,get(this,'_valuePath')));
      } else {
        set(this,'selection',null);
        if(this.selectize){
          this.selectize.clear();
        }
      }
    }
  }, 'selection'),
  /*
   * Triggered before the selection array changes
   * Here we process the removed elements
   */
  selectionArrayWillChange : function(array, idx, removedCount, addedCount) {
    this.removing = true;
    for (var i = idx; i < idx + removedCount; i++) {
      this.selectionObjectWasRemoved(array.objectAt(i));
    }
    this.removing = false;
  },
  /*
   * Triggered after the selection array changes
   * Here we process the inserted elements
   */
  selectionArrayDidChange : function(array, idx, removedCount, addedCount) {
    for (var i = idx; i < idx + addedCount; i++) {
      this.selectionObjectWasAdded(array.objectAt(i), i);
    }
  },
  /*
   * Function that is responsible for Selectize's item inserting logic
   */
  selectionObjectWasAdded : function(obj, index) {
    if(this.selectize) this.selectize.addItem(get(obj,get(this,'_valuePath')));
  },
  /*
   * Function that is responsible for Selectize's item removing logic
   */
  selectionObjectWasRemoved : function(obj) {
    if(this.selectize) this.selectize.removeItem(get(obj,get(this,'_valuePath')));
  },
  /**
   * Ember observer triggered before the content property is changed
   * We need to unbind any array observers
   */
  _contentWillChange: Ember.beforeObserver(function() {
    if(!this.inDOM) return;
    var content = get(this, 'content');
    if(content) {
      content.removeArrayObserver(this, {
        willChange : 'contentArrayWillChange',
        didChange : 'contentArrayDidChange'
      });
    }
    //Trigger remove logic
    var len = content ? get(content, 'length') : 0;
    this.removing = true;
    this.contentArrayWillChange(content, 0, len);
    this.removing = false;
    this._selectionDidChange();
  }, 'content'),
  /**
   * Ember observer triggered when the content property is changed
   * We need to bind an array observer to become notified of its changes
   */
  _contentDidChange : Ember.observer(function() {
    if(!this.inDOM) return;
    var content = get(this, 'content');
    if (content) {
      content.addArrayObserver(this, {
        willChange : 'contentArrayWillChange',
        didChange : 'contentArrayDidChange'
      });
    }
    var len = content ? get(content, 'length') : 0;
    this.contentArrayDidChange(content, 0, null, len);
  }, 'content'),
  /*
   * Triggered before the content array changes
   * Here we process the removed elements
   */
  contentArrayWillChange : function(array, idx, removedCount, addedCount) {
    for (var i = idx; i < idx + removedCount; i++) {
      this.objectWasRemoved(array.objectAt(i));
    }
    this._selectionDidChange();
  },
  /*
   * Triggered after the content array changes
   * Here we process the inserted elements
   */
  contentArrayDidChange : function(array, idx, removedCount, addedCount) {
    for (var i = idx; i < idx + addedCount; i++) {
      this.objectWasAdded(array.objectAt(i), i);
    }
    this._selectionDidChange();
  },
  /*
   * Function that is responsible for Selectize's option inserting logic
   * If the option is an object or Ember instance, we set an observer on the label value of it.
   * This way, we can later update the label of it.
   * Useful for dealing with objects that 'lazy load' some properties/relationships.
   */
  objectWasAdded : function(obj, index) {
    var data = {};
    if(typeOf(obj) === 'object' || typeOf(obj) === 'instance'){
      data = {
        label : get(obj, get(this,'_labelPath')),
        value : get(obj, get(this,'_valuePath')),
        data : obj
      };
      Ember.addObserver(obj,get(this,'_labelPath'),this,'_labelDidChange');
    } else {
      data = {
        label : obj,
        value : obj,
        data : obj
      };
    }

    if(this.selectize){
      this.selectize.addOption(data);
      this.selectize.refreshOptions(this.selectize.isFocused && !this.selectize.isInputHidden);
    }
    //this._selectionDidChange();
  },
  /*
   * Function that is responsible for Selectize's option removing logic
   */
  objectWasRemoved : function(obj) {
    if(typeOf(obj) === 'object' || typeOf(obj) === 'instance')
          Ember.removeObserver(obj,get(this,'_labelPath'),this,'_labelDidChange');
    if(this.selectize){
      this.selectize.removeOption(get(obj, get(this,'_valuePath')));
      this.selectize.refreshOptions(this.selectize.isFocused && !this.selectize.isInputHidden);
    }
    //Trigger a selection change, because the previously selected item might not be available anymore.
    //this._selectionDidChange();
  },
  /*
   * Ember Observer that triggers when an option's label changes.
   * Here we need to update its corresponding option with the new data
   */
  _labelDidChange: function(sender, key, value, rev) {
    if(!this.selectize) return;

    var data = {
      label : get(sender, get(this,'_labelPath')),
      value : get(sender, get(this,'_valuePath')),
      data : sender
    };
    this.selectize.updateOption(data.value,data);
  },
  /*
   * Observer on the disabled property that enables or disables selectize.
   */
  _disabledDidChange: Ember.observer(function(){
    if(!this.selectize) return;
    var disable = get(this,'disabled');
    if(disable) this.selectize.disable();
    else this.selectize.enable();
  },'disabled')
});
<commit_msg>use Ember.get for property lookup<commit_after>var get = Ember.get, set = Ember.set, isArray = Ember.isArray, typeOf = Ember.typeOf;

/**
 * Ember.Selectize is an Ember View that encapsulates a Selectize component.
 * The goal is to use this as a near dropin replacement for Ember.Select.
 */
Ember.Selectize = Ember.View.extend({
  attributeBindings : ['multiple', 'placeholder','autocomplete'],
  classNames : ['ember-selectize'],

  autocomplete:'off',
  // Allows to use prompt (like in Ember.Select) or placeholder property
  placeholder: Ember.computed.alias('prompt'),
  tagName : 'select',

  /**
   * default object paths for value and label paths
   */
  optionValuePath : 'content.value',
  optionLabelPath : 'content.label',

  /**
   * The array of the default plugins to load into selectize
   */
  plugins: ['remove_button'],

  /**
   * Computed properties that hold the processed paths ('content.' replacement),
   * as it is done on Ember.Select
   */
  _valuePath : Ember.computed('optionValuePath',function(){
    return get(this,'optionValuePath').replace(/^content\.?/, '');
  }),
  _labelPath : Ember.computed('optionLabelPath',function(){
    return get(this,'optionLabelPath').replace(/^content\.?/, '');
  }),

  /**
   * This flag should be true when the element is present in the DOM and false when if isn't.
   * This helps to avoid triggering unecessary observers.
   */
  inDOM: false,

  /**
   * Pass true to 'create' property to enable tag creation mode.
   * When active, ember-selectize will send a 'create' action to its controller when a tag is created.
   * Alternatively, you can pass a string to 'createAction' property and
   * ember-selectize will activite tag creation mode send an action with that name to its controller.
   */
  create:false,
  createAction:'create',

  didInsertElement : function() {
    var allowCreate = get(this, 'create');
    //View is now in DOM
    this.inDOM = true;

    //Normalize create property if createAction was set
    if(this.createAction && (this.createAction !== 'create'))
      allowCreate = true;

    //Create Selectize's instance
    //We proxy callbacks through jQuery's 'proxy' to have the callbacks context set to 'this'
    this.$().selectize({
      plugins: this.plugins,
      labelField : 'label',
      valueField : 'value',
      searchField : 'label',
      create: allowCreate ? $.proxy(this._create, this) : false,
      onItemAdd : $.proxy(this._onItemAdd, this),
      onItemRemove : $.proxy(this._onItemRemove, this),
      onType : $.proxy(this._onType, this)
    });

    //Save the created selectize instance
    this.selectize = this.$()[0].selectize;

    //Some changes to content, selection and disabled could have happened before the View was inserted into the DOM.
    //We trigger all the observers manually to account for those changes.
    this._disabledDidChange();
    this._contentDidChange();
    this._selectionDidChange();
  },
  willDestroyElement : function() {

    //Unbind observers
    this._contentWillChange();
    this._selectionWillChange();

    //Invoke Selectize's destroy
    this.selectize.destroy();

    //We are no longer in DOM
    this.inDOM = false;
  },
  /**
   * Event callback that is triggered when user creates a tag
   */
  _create:function(input,callback){
    // Delete user entered text
    this.selectize.setTextboxValue('');
    // Send action to controller
    get(this,'controller').send(get(this,'createAction'),input);
    // We cancel the creation here, so it's up to you to include the created element
    // in the content and selection property
    callback(null);
  },
  /**
   * Event callback that is triggered when user types in the input element
   */
  _onType:function(str){
    set(this,'filter',str);
  },
  /**
   * Event callback triggered when an item is added (when something is selected)
   * Here we need to update our selection property (if single selection) or array (if multiple selection)
   */
  _onItemAdd : function(value) {
    var content = get(this,'content');
    var selection = get(this,'selection');
    var multiple = get(this,'multiple');
    if(content){
      var obj = content.find(function(item){
        if(get(item,get(this,'_valuePath')) == value)
          return true;
      },this);
      if(multiple && isArray(selection) && obj){
        if(!selection.findBy(get(this,'_valuePath'),get(obj,get(this,'_valuePath'))))
          selection.addObject(obj);
      } else if(obj){
        if(!selection || (get(obj,get(this,'_valuePath')) !== get(selection,get(this,'_valuePath'))))
          set(this,'selection',obj);
      }
    }
  },
  /**
   * Event callback triggered when an item is removed (when something is deselected)
   * Here we need to update our selection property (if single selection, here set to null) or remove item from array (if multiple selection)
   */
  _onItemRemove : function(value) {
    if(this.removing) return;
    var content = get(this,'content');
    var selection = get(this,'selection');
    var multiple = get(this,'multiple');
    if(content){
      var obj = content.find(function(item){
        if(get(item,get(this,'_valuePath')) == value)
          return true;
      },this);
      if(multiple && isArray(selection) && obj){
        selection.removeObject(obj);
      } else if(!multiple){
        this.set('selection',null);
      }
    }
  },
    /**
   * Ember observer triggered before the selection property is changed
   * We need to unbind any array observers if we're in multiple selection
   */
  _selectionWillChange: Ember.beforeObserver(function() {

    var multiple = get(this, 'multiple');
    var selection = get(this, 'selection');
    if(selection && isArray(selection) && multiple) {
      selection.removeArrayObserver(this,  {
        willChange : 'selectionArrayWillChange',
        didChange : 'selectionArrayDidChange'
      });
      var len = selection ? get(selection, 'length') : 0;
      this.selectionArrayWillChange(selection, 0, len);
    }
  }, 'selection'),
  /**
   * Ember observer triggered when the selection property is changed
   * We need to bind an array observer when selection is multiple
   */
  _selectionDidChange : Ember.observer(function() {
    if(!this.inDOM) return;

    var multiple = get(this, 'multiple');
    var selection = get(this, 'selection');
    if (multiple) {
      if(selection) {
        if(!isArray(selection)){
          selection = Ember.A([selection]);
          set(this,'selection',selection);
          return;
        }
        selection.addArrayObserver(this, {
          willChange : 'selectionArrayWillChange',
          didChange : 'selectionArrayDidChange'
        });
      } else {
        set(this,'selection',[]);
        return;
      }
      var len = selection ? get(selection, 'length') : 0;
      this.selectionArrayDidChange(selection, 0, null, len);
    } else {
      if(selection) {
        this.selectize.addItem(get(selection,get(this,'_valuePath')));
      } else {
        set(this,'selection',null);
        if(this.selectize){
          this.selectize.clear();
        }
      }
    }
  }, 'selection'),
  /*
   * Triggered before the selection array changes
   * Here we process the removed elements
   */
  selectionArrayWillChange : function(array, idx, removedCount, addedCount) {
    this.removing = true;
    for (var i = idx; i < idx + removedCount; i++) {
      this.selectionObjectWasRemoved(array.objectAt(i));
    }
    this.removing = false;
  },
  /*
   * Triggered after the selection array changes
   * Here we process the inserted elements
   */
  selectionArrayDidChange : function(array, idx, removedCount, addedCount) {
    for (var i = idx; i < idx + addedCount; i++) {
      this.selectionObjectWasAdded(array.objectAt(i), i);
    }
  },
  /*
   * Function that is responsible for Selectize's item inserting logic
   */
  selectionObjectWasAdded : function(obj, index) {
    if(this.selectize) this.selectize.addItem(get(obj,get(this,'_valuePath')));
  },
  /*
   * Function that is responsible for Selectize's item removing logic
   */
  selectionObjectWasRemoved : function(obj) {
    if(this.selectize) this.selectize.removeItem(get(obj,get(this,'_valuePath')));
  },
  /**
   * Ember observer triggered before the content property is changed
   * We need to unbind any array observers
   */
  _contentWillChange: Ember.beforeObserver(function() {
    if(!this.inDOM) return;
    var content = get(this, 'content');
    if(content) {
      content.removeArrayObserver(this, {
        willChange : 'contentArrayWillChange',
        didChange : 'contentArrayDidChange'
      });
    }
    //Trigger remove logic
    var len = content ? get(content, 'length') : 0;
    this.removing = true;
    this.contentArrayWillChange(content, 0, len);
    this.removing = false;
    this._selectionDidChange();
  }, 'content'),
  /**
   * Ember observer triggered when the content property is changed
   * We need to bind an array observer to become notified of its changes
   */
  _contentDidChange : Ember.observer(function() {
    if(!this.inDOM) return;
    var content = get(this, 'content');
    if (content) {
      content.addArrayObserver(this, {
        willChange : 'contentArrayWillChange',
        didChange : 'contentArrayDidChange'
      });
    }
    var len = content ? get(content, 'length') : 0;
    this.contentArrayDidChange(content, 0, null, len);
  }, 'content'),
  /*
   * Triggered before the content array changes
   * Here we process the removed elements
   */
  contentArrayWillChange : function(array, idx, removedCount, addedCount) {
    for (var i = idx; i < idx + removedCount; i++) {
      this.objectWasRemoved(array.objectAt(i));
    }
    this._selectionDidChange();
  },
  /*
   * Triggered after the content array changes
   * Here we process the inserted elements
   */
  contentArrayDidChange : function(array, idx, removedCount, addedCount) {
    for (var i = idx; i < idx + addedCount; i++) {
      this.objectWasAdded(array.objectAt(i), i);
    }
    this._selectionDidChange();
  },
  /*
   * Function that is responsible for Selectize's option inserting logic
   * If the option is an object or Ember instance, we set an observer on the label value of it.
   * This way, we can later update the label of it.
   * Useful for dealing with objects that 'lazy load' some properties/relationships.
   */
  objectWasAdded : function(obj, index) {
    var data = {};
    if(typeOf(obj) === 'object' || typeOf(obj) === 'instance'){
      data = {
        label : get(obj, get(this,'_labelPath')),
        value : get(obj, get(this,'_valuePath')),
        data : obj
      };
      Ember.addObserver(obj,get(this,'_labelPath'),this,'_labelDidChange');
    } else {
      data = {
        label : obj,
        value : obj,
        data : obj
      };
    }

    if(this.selectize){
      this.selectize.addOption(data);
      this.selectize.refreshOptions(this.selectize.isFocused && !this.selectize.isInputHidden);
    }
    //this._selectionDidChange();
  },
  /*
   * Function that is responsible for Selectize's option removing logic
   */
  objectWasRemoved : function(obj) {
    if(typeOf(obj) === 'object' || typeOf(obj) === 'instance')
          Ember.removeObserver(obj,get(this,'_labelPath'),this,'_labelDidChange');
    if(this.selectize){
      this.selectize.removeOption(get(obj, get(this,'_valuePath')));
      this.selectize.refreshOptions(this.selectize.isFocused && !this.selectize.isInputHidden);
    }
    //Trigger a selection change, because the previously selected item might not be available anymore.
    //this._selectionDidChange();
  },
  /*
   * Ember Observer that triggers when an option's label changes.
   * Here we need to update its corresponding option with the new data
   */
  _labelDidChange: function(sender, key, value, rev) {
    if(!this.selectize) return;

    var data = {
      label : get(sender, get(this,'_labelPath')),
      value : get(sender, get(this,'_valuePath')),
      data : sender
    };
    this.selectize.updateOption(data.value,data);
  },
  /*
   * Observer on the disabled property that enables or disables selectize.
   */
  _disabledDidChange: Ember.observer(function(){
    if(!this.selectize) return;
    var disable = get(this,'disabled');
    if(disable) this.selectize.disable();
    else this.selectize.enable();
  },'disabled')
});
<|endoftext|>


<commit_before>const render = require('./render');
const compile = require('./compile');

/**
 * 模板引擎
 * @param   {string}            filename 模板名
 * @param   {Object|string}     content  数据或模板内容
 * @return  {string|function}            如果 content 为 string 则编译并缓存模板，否则渲染模板
 */
const template = (filename, content) => {
    return typeof content === 'object' ?
        render({
            filename
        }, content) :
        compile({
            filename,
            source: content
        });
};

module.exports = template;<commit_msg>remove file<commit_after><|endoftext|>


<commit_before>import Room from './Room.js';
import Wall from './Wall.js';

class Corridor {

    static roomSize = 300;

    constructor(length = 5) {
        this.rooms = [];
        this.distance = 0;

        for (var i = 0; i < length; i++) {
            this.addRoom();
        }
    }

    addRoom() {
        const length = this.rooms.length;
        const start = length ? this.rooms[length - 1].end : 0;
        const size = Math.round(Corridor.roomSize * (1 + (Math.random() - 0.5)));

        this.rooms.push(new Room(length, start, start + size));
        this.distance += size;
    }

    getWalls() {
        const length = this.rooms.length;
        const walls = new Array(length-1);

        for (let i = walls.length - 1; i >= 0; i--) {
            let room = this.rooms[i];
            walls[i] = new Wall(room.end);
        }

        return walls;
    }

    getInverseWalls() {
        const length = this.rooms.length;
        const walls = new Array(length-1);

        for (let i = walls.length - 1; i >= 0; i--) {
            let room = this.rooms[length-1 - i];
            walls[i] = new Wall(this.distance - room.start);
        }

        return walls;
    }
}

export default Corridor;
<commit_msg>Fix corridor<commit_after>import Room from './Room.js';
import Wall from './Wall.js';

class Corridor {

    static roomSize = 300;

    constructor(length = 50) {
        this.rooms = [];
        this.distance = 0;

        for (var i = 0; i < length; i++) {
            this.addRoom();
        }
    }

    addRoom() {
        const length = this.rooms.length;
        const start = length ? this.rooms[length - 1].end : 0;
        const size = Math.round(Corridor.roomSize * (1 + (Math.random() - 0.5)));

        this.rooms.push(new Room(length, start, start + size));
        this.distance += size;
    }

    getWalls() {
        const length = this.rooms.length;
        const walls = new Array(length-1);

        for (let i = walls.length - 1; i >= 0; i--) {
            let room = this.rooms[i];
            walls[i] = new Wall(room.end);
        }

        return walls;
    }

    getInverseWalls() {
        const length = this.rooms.length;
        const walls = new Array(length-1);

        for (let i = walls.length - 1; i >= 0; i--) {
            let room = this.rooms[length-1 - i];
            walls[i] = new Wall(this.distance - room.start);
        }

        return walls;
    }
}

export default Corridor;
<|endoftext|>


<commit_before>Ext.define('App.Constants', {
	singleton: true,
	GRID_COLUMNS: 4
});

Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
	title: 'BPO Portfolio View by Domain',
	requires: ['App.Constants'],
	launch: function() {

		this.add({
			xtype: 'rallyownerfilter',
			itemId: 'ownerComboBox',
			fieldLabel: 'Initiative Owner:',
			stateful: true,
			stateId: this.getContext().getScopedStateId('ownercombobox'),
			model: 'PortfolioItem/Initiative',
			listeners: {
				select: this._onLoad,
				ready: this._onLoad,
				scope: this
			}
		});
	},

	_onLoad: function(){

		// Parent Container
		if (this.down('#container')) {
			this.down('#container').destroy();
		}
		var panel = new Ext.Panel({
			id: 'container',
			// autoScroll: true,
			// title: 'Initiatives',
			layout: {
				type: 'accordion',
				titleCollapse: true,
				animate: true,
				// activeOnTop: true,
				multi: true
			},
			pack: 'start',
			// collapsible: true,
			defaults: {
				bodyStyle: 'padding:15px;'
			}
		});
		this.add(panel);
		panel.doLayout();

		var initiativeStore = Ext.create('Rally.data.WsapiDataStore', {
			model: 'PortfolioItem/Initiative',
			pageSize: 200,
			limit: Infinity,
			autoLoad: true,
			filters: [this._getOwnerFilter()],
			listeners: {
				load: function(store, data) {
					this._onInitiativesLoaded(store, data);
				},
				scope: this
			}
		});
	},

	_onInitiativesLoaded: function(store, data){

		var that = this;
		var containerPanel = that.down('#container');

		// Loop through each Initiative
		Ext.Array.each(data, function(record) {
			// Create Initiative Row Panel
			var id = record.get('FormattedID');
			var title = id + ' - ' + record.get('Name');
			var rowPanel = new Ext.Panel({
				title: title,
				ui: 'initiative',
				layout: {
					type: 'vbox',
					align: 'stretch'
				}
			});

			containerPanel.add(rowPanel);
			containerPanel.doLayout();

			var featureStore = Ext.create('Rally.data.WsapiDataStore', {
				model: 'PortfolioItem/Feature',
				pageSize: 200,
				limit: Infinity,
				autoLoad: true,
				filters: [
					{
						property: 'Parent.Parent.FormattedID',
						operator: '=',
						value: id
					}
				],
				listeners: {
					load: function(store, data) {
						that._onFeaturesLoaded(store, record, rowPanel);
					},
					scope: this
				}
			});
		});
	},

	_onFeaturesLoaded: function(store, initiative, rowPanel){

		// Get Distinct Projects from Feature Store
		var projectNames = _.map(store.getRange(), function(record) {
			return record.get('Project').Name;
		}),
			uniqueProjectNames = _.uniq(projectNames);

		// Set number of columns (grids) per row
		var columns = App.Constants.GRID_COLUMNS;
		var splitDomains = this._splitArray(uniqueProjectNames,columns);

		// Create Grid Panels for Domain
		var id = initiative.get('FormattedID');
		var items = this._getItems(splitDomains,id);
		rowPanel.add(items);
		rowPanel.doLayout();
	},

	_splitArray: function (unsplitArray, size) {
		var splitArray = [];
		while (unsplitArray.length > 0)
		splitArray.push(unsplitArray.splice(0, size));
		return splitArray;
	},

	_getItems: function(splitDomains,id) {
		var gridRows = [];
		var that = this;
		Ext.Array.each(splitDomains, function(record) {
			gridRows.push(
				{
					xtype: 'container',
					layout: {
						type: 'hbox',
						align: 'stretch'
					},
					height: 175,
					items	: that._getItems2(record,id)
				}
			);
		});
		return gridRows;
	},

	_getItems2: function(records,id){
		var that = this;
		var gridPanels = [];

		Ext.Array.each(records, function(record) {
			gridPanels.push(
				{
					title	: record,
					flex	: 2,
					autoScroll: true,
					items	: [
						{
							xtype: 'rallygrid',
							header: false,
							width: '95%',
							columnCfgs: [
								{
									text: 'ID', dataIndex: 'FormattedID', flex: 10
								},
								{
									text: 'State', dataIndex: 'State', flex: 10
								},
								{
									text: '% Done (pts)', dataIndex: 'PercentDoneByStoryPlanEstimate', flex: 10
								}
							],
							enableEditing: false,
							showRowActionsColumn: false,
							// showPagingToolbar: false,
							storeConfig: {
								model: 'portfolioitem/feature',
								pageSize: 200,
								filters: [that._getFilterGrid(record,id)]
							}
						}
					]
				}
			);
		});
		// Create Empty Boxes
		var i = records.length;
		while (i < App.Constants.GRID_COLUMNS){
			gridPanels.push(
				{
					ui: 'empty',
					flex	: 2,
					border	: true
				}
			);
			i++;
		}
		return gridPanels;

	},

	_getFilterGrid: function(record,id) {
		var combo = this.down('rallycombobox');
		var filters = Ext.create('Rally.data.QueryFilter', {
			property: 'Parent.Parent.FormattedID',
			operator: '=',
			value: id
		});

		filters = filters.and(Ext.create('Rally.data.QueryFilter', {
			property: 'Project.Name',
			operator: '=',
			value: record
		}));
		return filters;
	},

	_getOwnerFilter: function() {
		combo = this.down('#ownerComboBox');
		var comboval = combo.getValue();
		if(!comboval){
			comboval = combo.stateValue;
		}
		if(String(comboval).indexOf('-1') > -1){
			comboval = null;
		}
		return {
			property: 'Owner',
			operator: '=',
			value: comboval
		};
	}

});<commit_msg>adding tooltip v1<commit_after>Ext.define('App.Constants', {
	singleton: true,
	GRID_COLUMNS: 4
});

Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
	title: 'BPO Portfolio View by Domain',
	requires: ['App.Constants'],
	launch: function() {

		this.add({
			xtype: 'rallyownerfilter',
			itemId: 'ownerComboBox',
			fieldLabel: 'Initiative Owner:',
			stateful: true,
			stateId: this.getContext().getScopedStateId('ownercombobox'),
			model: 'PortfolioItem/Initiative',
			listeners: {
				select: this._onLoad,
				ready: this._onLoad,
				scope: this
			}
		});
	},

	_onLoad: function(){

		// Parent Container
		if (this.down('#container')) {
			this.down('#container').destroy();
		}
		var panel = new Ext.Panel({
			id: 'container',
			// autoScroll: true,
			// title: 'Initiatives',
			layout: {
				type: 'accordion',
				titleCollapse: true,
				animate: true,
				// activeOnTop: true,
				multi: true
			},
			pack: 'start',
			// collapsible: true,
			defaults: {
				bodyStyle: 'padding:15px;'
			}
		});
		this.add(panel);
		panel.doLayout();

		var initiativeStore = Ext.create('Rally.data.WsapiDataStore', {
			model: 'PortfolioItem/Initiative',
			pageSize: 200,
			limit: Infinity,
			autoLoad: true,
			filters: [this._getOwnerFilter()],
			listeners: {
				load: function(store, data) {
					this._onInitiativesLoaded(store, data);
				},
				scope: this
			}
		});
	},

	_onInitiativesLoaded: function(store, data){

		var that = this;
		var containerPanel = that.down('#container');

		// Loop through each Initiative
		Ext.Array.each(data, function(record) {
			// Create Initiative Row Panel
			var id = record.get('FormattedID');
			var title = id + ' - ' + record.get('Name');
			var rowPanel = new Ext.Panel({
				title: title,
				ui: 'initiative',
				layout: {
					type: 'vbox',
					align: 'stretch'
				}
			});

			containerPanel.add(rowPanel);
			containerPanel.doLayout();

			var featureStore = Ext.create('Rally.data.WsapiDataStore', {
				model: 'PortfolioItem/Feature',
				pageSize: 200,
				limit: Infinity,
				autoLoad: true,
				filters: [
					{
						property: 'Parent.Parent.FormattedID',
						operator: '=',
						value: id
					}
				],
				listeners: {
					load: function(store, data) {
						that._onFeaturesLoaded(store, record, rowPanel);
					},
					scope: this
				}
			});
		});
	},

	_onFeaturesLoaded: function(store, initiative, rowPanel){

		// Get Distinct Projects from Feature Store
		var projectNames = _.map(store.getRange(), function(record) {
			return record.get('Project').Name;
		}),
			uniqueProjectNames = _.uniq(projectNames);

		// Set number of columns (grids) per row
		var columns = App.Constants.GRID_COLUMNS;
		var splitDomains = this._splitArray(uniqueProjectNames,columns);

		// Create Grid Panels for Domain
		var id = initiative.get('FormattedID');
		var items = this._getItems(splitDomains,id);
		rowPanel.add(items);
		rowPanel.doLayout();
	},

	_splitArray: function (unsplitArray, size) {
		var splitArray = [];
		while (unsplitArray.length > 0)
		splitArray.push(unsplitArray.splice(0, size));
		return splitArray;
	},

	_getItems: function(splitDomains,id) {
		var gridRows = [];
		var that = this;
		Ext.Array.each(splitDomains, function(record) {
			gridRows.push(
				{
					xtype: 'container',
					layout: {
						type: 'hbox',
						align: 'stretch'
					},
					height: 175,
					items	: that._getItems2(record,id)
				}
			);
		});
		return gridRows;
	},

	_getItems2: function(records,id){
		var that = this;
		var gridPanels = [];

		Ext.Array.each(records, function(record) {
			gridPanels.push(
				{
					title	: record,
					flex	: 2,
					autoScroll: true,
					items	: [
						{
							xtype: 'rallygrid',
							header: false,
							width: '95%',
							columnCfgs: [
								{
									text: 'ID', dataIndex: 'FormattedID', flex: 10
								},
								{
									text: 'State', dataIndex: 'State', flex: 10
								},
								{
									text: '% Done (pts)', dataIndex: 'PercentDoneByStoryPlanEstimate', flex: 10
								}
							],
							enableEditing: false,
							showRowActionsColumn: false,
							// showPagingToolbar: false,
							storeConfig: {
								model: 'portfolioitem/feature',
								pageSize: 200,
								filters: [that._getFilterGrid(record,id)]
							},
							// For Tooltip (12/1/2015)
							listeners: {
								itemmouseenter: function(g, record, item) {
									tooltipvalue = record.get('FormattedID') + ' - ' + record.get('Name');
									Ext.create('Rally.ui.tooltip.ToolTip', {
										target : item,
										html: '
' + tooltipvalue + '
'
									});
								},
								// select: this._getRecordOnSelectedRow,
								// load : function(g, record, index, options){
									// this._getRecordOnSelectedRow(g, record, 0, options);
								// },
								scope: this
							}
						}
					]
				}
			);
		});
		// Create Empty Boxes
		var i = records.length;
		while (i < App.Constants.GRID_COLUMNS){
			gridPanels.push(
				{
					ui: 'empty',
					flex	: 2,
					border	: true
				}
			);
			i++;
		}
		return gridPanels;

	},

	_getFilterGrid: function(record,id) {
		var combo = this.down('rallycombobox');
		var filters = Ext.create('Rally.data.QueryFilter', {
			property: 'Parent.Parent.FormattedID',
			operator: '=',
			value: id
		});

		filters = filters.and(Ext.create('Rally.data.QueryFilter', {
			property: 'Project.Name',
			operator: '=',
			value: record
		}));
		return filters;
	},

	_getOwnerFilter: function() {
		combo = this.down('#ownerComboBox');
		var comboval = combo.getValue();
		if(!comboval){
			comboval = combo.stateValue;
		}
		if(String(comboval).indexOf('-1') > -1){
			comboval = null;
		}
		return {
			property: 'Owner',
			operator: '=',
			value: comboval
		};
	},

	// SPH Test This (12/1/2015)
	_getRecordOnSelectedRow:function(g, record, rowIndex, options){
        console.log(record);
    }

});<|endoftext|>


<commit_before>// @flow
import React, {Component} from 'react';
import Expo from 'expo';
import {Dimensions, StyleSheet} from 'react-native';
import {
  Button,
  Container,
  Content,
  Text,
  Thumbnail,
  View
} from 'native-base';

const {height: screenHeight} = Dimensions.get('window')

const styles = StyleSheet.create({
  bgLight: {
    backgroundColor: 'cornflowerblue'
  },
  bg: {
    backgroundColor: 'steelblue'
  },
  bgDark: {
    backgroundColor: 'darkslateblue'
  },
  fullScreen: {
    flex: 1,
    height: screenHeight
  },
  header: {
    flex: 1,
    alignItems: "center",
    justifyContent: 'flex-end',
    zIndex: 1
  },
  content: {
    flex: 3
  },
  subtitle: {
    fontSize: 16,
    marginTop: 60,
    marginBottom: 10,
    textAlign: 'center',
  },
  title: {
    // fontFamily: 'Roboto',
    fontSize: 32,
    justifyContent: 'center',
    marginBottom: 15,
    textAlign: 'center',
  },
  leadBlock: {
    flex: 2,
    textAlign: 'center'
  },
  lead:{
    fontSize: 20,
  },
  textCenter: {
    textAlign: 'center'
  },
  small: {
    fontSize: 14,
  },
  valign: {
    flex: 1,
    justifyContent: 'center'
  }
})

let css = (styles) => {
  return StyleSheet.flatten(styles)
}

export default class HelloWorld extends Component {

  // async componentWillMount() {
  //   await Expo.Font.loadAsync({'Roboto': require('native-base/Fonts/Roboto.ttf'), 'Roboto_medium': require('native-base/Fonts/Roboto_medium.ttf')});
  // }

  render() {
    return (
      <Container>
        <Content>
          <View style={css(styles.fullScreen)}>
            <View style={css(styles.header)}>
              <Thumbnail style={{
                marginBottom: -40
              }} large source={{
                uri: 'http://gravatar.com/avatar/41b64c5cb658355a506deba471262427'
              }}/>
            </View>
            <View style={css([styles.content])} padder>
              <Text style={css(styles.subtitle)}>The Hello World App</Text>
              <Text style={css(styles.title)}>nahuelhds</Text>
              <View style={css([{flex: 1}])}>
                <View style={css(styles.leadBlock)}>
                  <Text style={css([styles.lead, styles.textCenter])}>
                    Agile developer & Craftperson
                  </Text>
                  <Text style={css([styles.lead, styles.textCenter])}>
                    @ CristalMedia
                  </Text>
                </View>
                <View style={css([styles.valign])}>
                  <Text style={css([styles.textCenter, styles.small])}>Esta aplicación fue creada para conocer y aprender sobre React Native.</Text>
                </View>
              </View>
              <View>
                <Button full primary>
                  <Text>Ingresar</Text>
                </Button>
              </View>
            </View>
          </View>
        </Content>
      </Container>
    )
  }
}
<commit_msg>Estilos al final del archivo segun las buenas costumbres<commit_after>// @flow
import React, {Component} from 'react';
import Expo from 'expo';
import {Dimensions, StyleSheet} from 'react-native';
import {
  Button,
  Container,
  Content,
  Text,
  Thumbnail,
  View
} from 'native-base';

export default class HelloWorld extends Component {

  // async componentWillMount() {
  //   await Expo.Font.loadAsync({'Roboto': require('native-base/Fonts/Roboto.ttf'), 'Roboto_medium': require('native-base/Fonts/Roboto_medium.ttf')});
  // }

  render() {
    return (
      <Container>
        <Content>
          <View style={css(styles.fullScreen)}>
            <View style={css(styles.header)}>
              <Thumbnail style={{
                marginBottom: -40
              }} large source={{
                uri: 'http://gravatar.com/avatar/41b64c5cb658355a506deba471262427'
              }}/>
            </View>
            <View style={css([styles.content])} padder>
              <Text style={css(styles.subtitle)}>The Hello World App</Text>
              <Text style={css(styles.title)}>nahuelhds</Text>
              <View style={css([{flex: 1}])}>
                <View style={css(styles.leadBlock)}>
                  <Text style={css([styles.lead, styles.textCenter])}>
                    Agile developer & Craftperson
                  </Text>
                  <Text style={css([styles.lead, styles.textCenter])}>
                    @ CristalMedia
                  </Text>
                </View>
                <View style={css([styles.valign])}>
                  <Text style={css([styles.textCenter, styles.small])}>Esta aplicación fue creada para conocer y aprender sobre React Native.</Text>
                </View>
              </View>
              <View>
                <Button full primary>
                  <Text>Ingresar</Text>
                </Button>
              </View>
            </View>
          </View>
        </Content>
      </Container>
    )
  }
}

const {height: screenHeight} = Dimensions.get('window')

const styles = StyleSheet.create({
  bgLight: {
    backgroundColor: 'cornflowerblue'
  },
  bg: {
    backgroundColor: 'steelblue'
  },
  bgDark: {
    backgroundColor: 'darkslateblue'
  },
  fullScreen: {
    flex: 1,
    height: screenHeight
  },
  header: {
    flex: 1,
    alignItems: "center",
    justifyContent: 'flex-end',
    zIndex: 1
  },
  content: {
    flex: 3
  },
  subtitle: {
    fontSize: 16,
    marginTop: 60,
    marginBottom: 10,
    textAlign: 'center',
  },
  title: {
    // fontFamily: 'Roboto',
    fontSize: 32,
    justifyContent: 'center',
    marginBottom: 15,
    textAlign: 'center',
  },
  leadBlock: {
    flex: 2,
    textAlign: 'center'
  },
  lead:{
    fontSize: 20,
  },
  textCenter: {
    textAlign: 'center'
  },
  small: {
    fontSize: 14,
  },
  valign: {
    flex: 1,
    justifyContent: 'center'
  }
})

let css = (styles) => {
  return StyleSheet.flatten(styles)
}
<|endoftext|>


<commit_before>Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
    launch: function() {
        //Write app code here
        console.log('My first Rally App for Features Sudhir WOOT!!!');
        var myUserStoryStore=Ext.create('Rally.data.wsapi.Store', {
            model: 'PortfolioItem/Feature',
            autoLoad: true,
            listeners: {
                load: function(myUStoryStore, myStorydata, success) {
                    //process data
                    console.log('!!Got User Feature Data',myUStoryStore,myStorydata,success);
                    // Add grid
                    var myUserStoryGrid=Ext.create('Ext.Container', {
                        items: [{
                            xtype: 'rallygrid',
                            columnCfgs: [
                                'FormattedID',
                                'Name'
                            ],
                            storeConfig: {
                                model: 'PortfolioItem/Feature'
                            }
                        }],
                        renderTo: Ext.getBody()
                    });
                    //Add Grid ends
                    console.log('My Feature grid',myUserStoryGrid);
                    this.add(myUserStoryGrid);
                },
                scope:this
            },
            fetch: ['FormattedID','Name', 'LastUpdateDate']
        });
        //API Docs: https://help.rallydev.com/apps/2.0/doc/
    }
});
<commit_msg>refactored code into functions<commit_after>Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
    launch : function(){
        console.log('My first Rally App for Features Sudhir WOOT!!!');
        this._loadData();
    },
    //Get Data from Rally
    _loadData:function(){
       ///
        var myFeatureStore=Ext.create('Rally.data.wsapi.Store', {
            model: 'PortfolioItem/Feature',
            autoLoad: true,
            listeners: {
                load: function(myUStoryStore, myStorydata, success) {
                    //process data
                    console.log('!!Got User Feature Data',myUStoryStore,myStorydata,success);
                    // Add grid
                    this._loadGrid(myFeatureStore);
                    //Add Grid ends
                 //   console.log('My Feature grid',myUserStoryGrid);
                   // this.add(myUserStoryGrid);
                },
                scope:this
            },
            fetch: ['FormattedID','Name', 'LastUpdateDate']
        });

        ///
    },

    //Create and Show Grid of User Features
    _loadGrid :function(myFeatureStore){
        var myFeatureGrid=Ext.create('Rally.ui.grid.Grid', {
                store: myFeatureStore,
                columnCfgs: [
                    'FormattedID',
                    'Name', 'LastUpdateDate'
                ]
        });
        console.log('@@@@@@@@What is this?',this);
        this.add(myFeatureGrid);

    }

    /*
    launch: function() {
        //Write app code here
        console.log('My first Rally App for Features Sudhir WOOT!!!');
        var myUserStoryStore=Ext.create('Rally.data.wsapi.Store', {
            model: 'PortfolioItem/Feature',
            autoLoad: true,
            listeners: {
                load: function(myUStoryStore, myStorydata, success) {
                    //process data
                    console.log('!!Got User Feature Data',myUStoryStore,myStorydata,success);
                    // Add grid
                    var myUserStoryGrid=Ext.create('Ext.Container', {
                        items: [{
                            xtype: 'rallygrid',
                            columnCfgs: [
                                'FormattedID',
                                'Name','LastUpdateDate'
                            ],
                            storeConfig: {
                                model: 'PortfolioItem/Feature'
                            }
                        }],
                        renderTo: Ext.getBody()
                    });
                    //Add Grid ends
                    console.log('My Feature grid',myUserStoryGrid);
                    this.add(myUserStoryGrid);
                },
                scope:this
            },
            fetch: ['FormattedID','Name', 'LastUpdateDate']
        });
        //API Docs: https://help.rallydev.com/apps/2.0/doc/
    }
    */

});
<|endoftext|>


<commit_before>Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
    items: [{
        xtype: 'container',
        itemId: 'pulldown-container',
        layout: {
            type: 'hbox',
            align: 'stretch'
        }
    },{
        xtype: 'container',
        itemId: 'text-container',
        layout: {
            type: 'anchor',
            align: 'stretch'
        }
    }],
    launch: function() {
        console.log('Basic Rally Grid');
        this._loadIterations();
    },
    _loadIterations: function() {
        var iterPicker = {
            xtype: 'rallyiterationcombobox',
            itemId: 'iter-picker',
            fieldLabel: 'Iteration',
            labelAlign: 'right',
            width: '300',
            listeners: {
                ready: this._loadData,
                select: this._loadData,
                scope: this
            }
        };
        this.down('#pulldown-container').add(iterPicker);
    },
    _getFilters: function(iterVal) {
        var iterationFilter = Ext.create('Rally.data.wsapi.Filter', {
            property: 'Iteration',
            operation: '=',
            value: iterVal
        });
        return iterationFilter;
    },
    _loadData: function() {
        var iterRef = this.down('#iter-picker').getRecord().get('_ref');
        console.log('iter ref: ', iterRef);

        var comboFilter = this._getFilters(iterRef);

        if (this.myStore) {
            this.myStore.setFilter(comboFilter);
            this.myStore.load();
        } else {
            this.myStore = Ext.create('Rally.data.wsapi.artifact.Store', {
                models: ['User Story', 'Defect'],
                autoLoad: true,
                filters: comboFilter,
                listeners: {
                    load: function(store, data, success) {
                        console.log(store)
                        var htmlStr = this._getArtifactHtml(store.getRecords());
                        if (!this.mytext) {
                            this._createText(htmlStr);
                        }
                        this._setText(htmlStr);
                    },
                    scope: this
                },
                fetch: ['FormattedID', 'Name', 'Owner', 'ScheduleState', 'PlanEstimate', 'RevisionHistory']
            });
        }
    },
    _createText: function(string) {
        this.mytext = {
            itemId: 'texted',
            xtype: 'rallyrichtexteditor',
            value: string,
            style: {
                width: '100%',
                height: '100%'
            }
        };
        this.down('#text-container').add(this.mytext);
    },
    _setText: function(string) {
        this.down('#texted').setValue(string);
    },
    _getArtifactHtml: function(records) {
        var htmlStr = '';
        Ext.Array.each(records, function(rec) {
            pEst = rec.get('PlanEstimate');
            state = rec.get('ScheduleState');

            recStr = rec.get('FormattedID') + ': ' + rec.get('Name');

            if (pEst && pEst > 0) {
                recStr = recStr + ' (' + pEst + 'pts)';
            } else {
                if (schState && schState == 'Incomplete') {
                    // Use revision history to get old status
                    revHis = rec.getProxy('RevisionHistory');
                    console.log(revHis);
                    recStr = recStr + ' (' + pEst + 'pts)';
                }
            }

            if (state == 'Accepted' || state == 'Completed') {
                htmlStr = htmlStr + '' + recStr + '
';
            } else if (state == 'Incomplete') {
                htmlStr = htmlStr + '' + recStr + '
';
            } else {
                htmlStr = htmlStr + recStr + '
';
            }
        });
        return htmlStr;
    }
});
<commit_msg>Close to revision solution<commit_after>Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
    items: [{
        xtype: 'container',
        itemId: 'pulldown-container',
        layout: {
            type: 'hbox',
            align: 'stretch'
        }
    },{
        xtype: 'container',
        itemId: 'text-container',
        layout: {
            type: 'anchor',
            align: 'stretch'
        }
    }],
    launch: function() {
        console.log('Basic Rally Grid');
        this._loadIterations();
    },
    _loadIterations: function() {
        var iterPicker = {
            xtype: 'rallyiterationcombobox',
            itemId: 'iter-picker',
            fieldLabel: 'Iteration',
            labelAlign: 'right',
            width: '300',
            listeners: {
                ready: this._loadData,
                select: this._loadData,
                scope: this
            }
        };
        this.down('#pulldown-container').add(iterPicker);
    },
    _getFilters: function(iterVal) {
        var iterationFilter = Ext.create('Rally.data.wsapi.Filter', {
            property: 'Iteration',
            operation: '=',
            value: iterVal
        });
        return iterationFilter;
    },
    _loadData: function() {
        var iterRef = this.down('#iter-picker').getRecord().get('_ref');
        console.log('iter ref: ', iterRef);

        var comboFilter = this._getFilters(iterRef);

        if (this.myStore) {
            this.myStore.setFilter(comboFilter);
            this.myStore.load();
        } else {
            this.myStore = Ext.create('Rally.data.wsapi.artifact.Store', {
                models: ['User Story', 'Defect'],
                autoLoad: true,
                filters: comboFilter,
                listeners: {
                    load: function(store, data, success) {
                        console.log(store)
                        var htmlStr = this._getArtifactHtml(data);
                        if (!this.mytext) {
                            this._createText(htmlStr);
                        }
                        this._setText(htmlStr);
                    },
                    scope: this
                },
                fetch: ['FormattedID', 'Name', 'Owner', 'ScheduleState', 'PlanEstimate', 'RevisionHistory', 'Revisions', 'Description', 'RevisionNumber']
            });
        }
    },
    _createText: function(string) {
        this.mytext = {
            itemId: 'texted',
            xtype: 'rallyrichtexteditor',
            value: string,
            style: {
                width: '100%',
                height: '100%'
            }
        };
        this.down('#text-container').add(this.mytext);
    },
    _setText: function(string) {
        this.down('#texted').setValue(string);
    },
    _getArtifactHtml: function(data) {
        var htmlStr = '';
        console.log(data)
        Ext.Array.each(data, function(rec) {
            pEst = rec.get('PlanEstimate');
            state = rec.get('ScheduleState');

            recStr = rec.get('FormattedID') + ': ' + rec.get('Name');

            if (pEst && pEst > 0) {
                recStr = recStr + ' (' + pEst + 'pts)';
            } else {
                if (state && state == 'Incomplete') {
                    // Use revision history to get old status
                    // http://stackoverflow.com/questions/12694644/querying-for-user-story-revisions-in-rally
                    Ext.Array.each(rec.get('RevisionHistory').Revisions, function(rev) {
                    //     console.log(rev.RevisionNumber)
                         console.log(rev)
                    })
                    recStr = recStr + ' (' + pEst + 'pts)';
                }
            }

            if (state == 'Accepted' || state == 'Completed') {
                htmlStr = htmlStr + '' + recStr + '
';
            } else if (state == 'Incomplete') {
                htmlStr = htmlStr + '' + recStr + '
';
            } else {
                htmlStr = htmlStr + recStr + '
';
            }
        });
        return htmlStr;
    }
});
<|endoftext|>


<commit_before>Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',

    launch: function() {
        MyApp = this;

        MyApp.epicList = [];
        MyApp.scopeDetails = [];
        MyApp.scopeDescription = [];
        MyApp.featureDetails = [];
        MyApp.featureDescription = [];

        MyApp.globalContext = this.getContext().getDataContext();

        // Load the program list and create the program combobox
        MyApp._loadProgramList();
    },

    _wrapComponent: function(component, cls) {
        var wrapper = Ext.create('Ext.container.Container', {
            componentCls: cls
        });

        wrapper.add(component);

        return wrapper;
    },

    _loadProgramList: function() {
        var thisIsMyStore = Ext.create('Rally.data.WsapiDataStore', {
            autoLoad: true,

            model: 'PortfolioItem/Epic',

            context: MyApp.globalContext,

            //fetch: ['Name' ],

            sorters: {
                property: 'Name',
                direction: 'ASC'
            },

            listeners: {
                load: function( store, records ) {
                    console.log( store );
                    var index=0;
                    for (index=0; index<records.length; index++) {
                        MyApp.epicList.push( records[index].data.Name );
                    }
                    MyApp._drawComboBox();
                }
            }
        });
    },

    _drawComboBox: function() {
        MyApp.combo = Ext.create('Ext.form.ComboBox', {
            fieldLabel: 'Program',

            store: MyApp.epicList,

            listeners: {
                'change': function(combo, newVal) {
                    MyApp.selectedEpicName = newVal;

                    MyApp._loadProgramDetails();
                }
            }
        });

        MyApp.programPane = Ext.create('Ext.container.Container', {
            componentCls: 'inner'
        });

        MyApp.add(MyApp._wrapComponent(MyApp.programPane, 'program'));

        MyApp.programPane.add(MyApp.combo);
    },

    _loadProgramDetails: function() {
        Ext.create('Rally.data.WsapiDataStore', {
            autoLoad: true,

            model: 'PortfolioItem/Epic',

            context: MyApp.globalContext,

            fetch: ['Name',
                    'c_SAPProjectNumber',
                    'InvestmentCategory',
                    'PlannedStartDate',
                    'PlannedEndDate',
                    'LastUpdateDate',
                    'Description'
                    ],

            filters: [
                    {
                        property: 'Name',
                        operator: 'Contains',
                        value: MyApp.selectedEpicName
                    }
                    ],

            sorters: {
                property: 'Rank',
                direction: 'ASC'
            },

            listeners: {
                load: MyApp._writeProgramDetails
            }
        });
    },

    _writeProgramDetails: function(myStore, records) {
        // Remove the combo box
        MyApp.programPane.remove(MyApp.combo);

        title = records[0].data.Name;

        MyApp.programName = Ext.create('Ext.panel.Panel', {
            width: '100%',
            html: '

' + title + '

',
            renderTo: Ext.getBody()
        });

        MyApp.programPane.add( MyApp.programName );

        MyApp.programDetails = Ext.create('Rally.ui.grid.Grid', {
            store: myStore,
            border: 1,
            columnCfgs: [
                {dataIndex: 'c_SAPProjectNumber', text:'SAP #'},
                'InvestmentCategory',
                'PlannedStartDate',
                'PlannedEndDate',
                'LastUpdateDate'
            ],
            showPagingToolbar: false
        });

        MyApp.programPane.add(MyApp.programDetails);

        MyApp.programDescription = Ext.create('Ext.panel.Panel', {
            width: '100%',
            html: '
' + records[0].data.Description + '
',
            renderTo: Ext.getBody()
        });

        MyApp.programPane.add( MyApp.programDescription );

        MyApp.scopePane = Ext.create('Ext.container.Container', {
            componentCls: 'inner'
        });
        MyApp.add(MyApp._wrapComponent(MyApp.scopePane, 'scope'));

        MyApp.scopeTotal = Ext.create('Ext.panel.Panel', {
            width: '100%',
            html: '

Scope Summary

',
            renderTo: Ext.getBody()
        });

        MyApp.scopePane.add( MyApp.scopeTotal );

        MyApp._loadScopeDetails();
    },

    _loadScopeDetails: function() {
        Ext.create('Rally.data.WsapiDataStore', {
            autoLoad: true,
            pageSize: 1,    // Load 1 page at a time
            limit: 1,       // Limit to 1

            model: 'PortfolioItem/MMF',
            context: MyApp.globalContext,

            fetch: ['Parent',
                    'Project',
                    'Name',
                    'c_SAPProjectNumber',
                    'InvestmentCategory',
                    'PlannedStartDate',
                    'PlannedEndDate',
                    'LastUpdateDate',
                    'Description'
                    ],

            filters: [
                    {
                        property: 'Parent.Name',
                        operator: 'Contains',
                        value: MyApp.selectedEpicName
                    }
                ],

            sorters: {
                property: 'Rank',
                direction: 'ASC'
            },

            listeners: {
                load: function( store, records ) {
                    MyApp._buildScopeDetails( store, records, store.currentPage-1 );

                    // Load the next until all pages are loaded
                    if ( store.currentPage < store.totalCount )
                    {
                       store.loadPage( store.currentPage+1 );
                    }
                    else
                    {
                        var index = 0;
                        for (index=0; index< store.totalCount; index++ ){
                            MyApp.scopePane.add(MyApp.scopeDetails[index]);
                            MyApp.scopePane.add(MyApp.scopeDescription[index] );
                        }

                        MyApp.featurePane = Ext.create('Ext.container.Container', {
                            componentCls: 'inner'
                        });
                        MyApp.add(MyApp._wrapComponent(MyApp.featurePane, 'feature'));

                        MyApp.featureTotal = Ext.create('Ext.panel.Panel', {
                            width: '100%',
                            html: '

Feature Summary by PSI

',
                            renderTo: Ext.getBody()
                        });

                        MyApp.featurePane.add( MyApp.featureTotal );

                        // Move to features
                        MyApp._loadFeatureDetails();
                    }
                }
            }
        });
    },

    _buildScopeDetails: function(myStore, records) {
        // Filter off the epic from the scope title
        var epicTitle = MyApp.selectedEpicName + ': ';
        var title = records[0].data.Name;
        if ( 0 === title.indexOf( epicTitle ) ) {
            title = title.substr( epicTitle.length );
        }

        MyApp.scopeDetails.push( Ext.create('Rally.ui.grid.Grid', {
            store: myStore,
            title: '' + title + '',
            border: 1,
            columnCfgs: [
                'Name',
                {dataIndex: 'c_SAPProjectNumber', text:'SAP #'},
                'InvestmentCategory',
                'PlannedStartDate',
                'PlannedEndDate',
                'LastUpdateDate',
                'Project'
            ],
            showPagingToolbar: false
        }) );

        MyApp.scopeDescription.push( Ext.create('Ext.panel.Panel', {
            width: '100%',
            html: '
' + records[0].data.Description + '
',
            renderTo: Ext.getBody()
        }) );
    },

    _loadFeatureDetails: function() {
        Ext.create('Rally.data.WsapiDataStore', {
            autoLoad: true,
            pageSize: 1,    // Load 1 page at a time
            limit: 1,       // Limit to 1

            model: 'PortfolioItem/Feature',
            context: MyApp.globalContext,

            fetch: ['Parent',
                    'Project',
                    'Name',
                    'PreliminaryEstimate',
                    'ValueScore',
                    'RiskScore',
                    'LastUpdateDate',
                    'Description',
                    'Release'
                ],

            filters: [
                    {
                        property: 'Parent.Parent.Name',
                        operator: 'Contains',
                        value: MyApp.selectedEpicName
                    }
                ],

            sorters: {
                property: 'Release',
                direction: 'ASC'
            },

            listeners: {
                load: function( store, records ) {
                    MyApp._writeFeatureDetails( store, records );

                    // Load the next until all pages are loaded
                    if ( store.currentPage < store.totalCount )
                    {
                        store.loadPage( store.currentPage+1 );
                    }
                    else
                    {
                        var index = 0;
                        for (index=0; index< store.totalCount; index++ ){
                            MyApp.featurePane.add(MyApp.featureDetails[index]);
                            MyApp.featurePane.add(MyApp.featureDescription[index] );
                        }
                    }
                }
            }
        });
    },

    _writeFeatureDetails: function(myStore, records) {
        var title = records[0].data.Name;

        MyApp.featureDetails.push( Ext.create('Rally.ui.grid.Grid', {
            store: myStore,
            border: 1,
            title: '' + title + '',
            columnCfgs: [
                'Name',
                'PreliminaryEstimate',
                'ValueScore',
                'RiskScore',
                'Project',
                'LastUpdateDate',
                'Release'
            ],
            showPagingToolbar: false
        }));

        MyApp.featureDescription.push( Ext.create('Ext.panel.Panel', {
            width: '100%',
            html: '
' + records[0].data.Description + '
',
            renderTo: Ext.getBody()
        }));
    }
});
<commit_msg>Changed to create a new data store through recursive calls and a page counter<commit_after>Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',

    launch: function() {
        MyApp = this;

        MyApp.storeCopies = [];
        MyApp.epicList = [];
        MyApp.currentScopePage = 1;
        MyApp.scopeDetails = [];
        MyApp.scopeDescription = [];
        MyApp.currentFeaturePage = 1;
        MyApp.featureDetails = [];
        MyApp.featureDescription = [];

        MyApp.globalContext = this.getContext().getDataContext();

        // Load the program list and create the program combobox
        MyApp._loadProgramList();
    },

    _wrapComponent: function(component, cls) {
        var wrapper = Ext.create('Ext.container.Container', {
            componentCls: cls
        });

        wrapper.add(component);

        return wrapper;
    },

    _loadProgramList: function() {
        var thisIsMyStore = Ext.create('Rally.data.WsapiDataStore', {
            autoLoad: true,

            model: 'PortfolioItem/Epic',

            context: MyApp.globalContext,

            fetch: ['Name' ],

            sorters: {
                property: 'Name',
                direction: 'ASC'
            },

            listeners: {
                load: function( myStore, records ) {
                    console.log( myStore );
                    var index=0;
                    for (index=0; index<records.length; index++) {
                        MyApp.epicList.push( records[index].data.Name );
                    }
                    MyApp._drawComboBox();
                }
            }
        });
    },

    _drawComboBox: function() {
        MyApp.combo = Ext.create('Ext.form.ComboBox', {
            fieldLabel: 'Program',

            store: MyApp.epicList,

            listeners: {
                'change': function(combo, newVal) {
                    MyApp.selectedEpicName = newVal;

                    MyApp._loadProgramDetails();
                }
            }
        });

        MyApp.programPane = Ext.create('Ext.container.Container', {
            componentCls: 'inner'
        });

        MyApp.add(MyApp._wrapComponent(MyApp.programPane, 'program'));

        MyApp.programPane.add(MyApp.combo);
    },

    _loadProgramDetails: function() {
        Ext.create('Rally.data.WsapiDataStore', {
            autoLoad: true,

            model: 'PortfolioItem/Epic',

            context: MyApp.globalContext,

            fetch: ['Name',
                    'c_SAPProjectNumber',
                    'InvestmentCategory',
                    'PlannedStartDate',
                    'PlannedEndDate',
                    'LastUpdateDate',
                    'Description'
                    ],

            filters: [
                    {
                        property: 'Name',
                        operator: 'Contains',
                        value: MyApp.selectedEpicName
                    }
                    ],

            sorters: {
                property: 'Rank',
                direction: 'ASC'
            },

            listeners: {
                load: MyApp._writeProgramDetails
            }
        });
    },

    _writeProgramDetails: function(myStore, records) {
        MyApp.storeCopies.push( myStore );

        // Remove the combo box
        MyApp.programPane.remove(MyApp.combo);

        title = records[0].data.Name;

        MyApp.programName = Ext.create('Ext.panel.Panel', {
            width: '100%',
            html: '

' + title + '

',
            renderTo: Ext.getBody()
        });

        MyApp.programPane.add( MyApp.programName );

        MyApp.programDetails = Ext.create('Rally.ui.grid.Grid', {
            store: myStore,
            border: 1,
            columnCfgs: [
                {dataIndex: 'c_SAPProjectNumber', text:'SAP #'},
                'InvestmentCategory',
                'PlannedStartDate',
                'PlannedEndDate',
                'LastUpdateDate'
            ],
            showPagingToolbar: false
        });

        MyApp.programPane.add(MyApp.programDetails);

        MyApp.programDescription = Ext.create('Ext.panel.Panel', {
            width: '100%',
            html: '
' + records[0].data.Description + '
',
            renderTo: Ext.getBody()
        });

        MyApp.programPane.add( MyApp.programDescription );

        MyApp.scopePane = Ext.create('Ext.container.Container', {
            componentCls: 'inner'
        });
        MyApp.add(MyApp._wrapComponent(MyApp.scopePane, 'scope'));

        MyApp.scopeTotal = Ext.create('Ext.panel.Panel', {
            width: '100%',
            html: '

Scope Summary

',
            renderTo: Ext.getBody()
        });

        MyApp.scopePane.add( MyApp.scopeTotal );

        MyApp._loadScopeDetails();
    },

    _loadScopeDetails: function() {
        thisStore = Ext.create('Rally.data.WsapiDataStore', {
            pageSize: 1,    // Load 1 page at a time
            limit: 1,       // Limit to 1

            model: 'PortfolioItem/MMF',
            context: MyApp.globalContext,

            fetch: ['Parent',
                    'Project',
                    'Name',
                    'c_SAPProjectNumber',
                    'InvestmentCategory',
                    'PlannedStartDate',
                    'PlannedEndDate',
                    'LastUpdateDate',
                    'Description'
                    ],

            filters: [
                    {
                        property: 'Parent.Name',
                        operator: 'Contains',
                        value: MyApp.selectedEpicName
                    }
                ],

            sorters: {
                property: 'Rank',
                direction: 'ASC'
            },

            listeners: {
                load: function( myStore, records ) {
                    MyApp.storeCopies.push( myStore );

                    MyApp._buildScopeDetails( myStore, records );

                    // Load the next until all pages are loaded
                    if ( myStore.currentPage < myStore.totalCount )
                    {
                        ++MyApp.currentScopePage;
                        MyApp._loadScopeDetails();
                    }
                    else
                    {
                        var index = 0;
                        for (index=0; index< myStore.totalCount; index++ ){
                            MyApp.scopePane.add(MyApp.scopeDetails[index]);
                            MyApp.scopePane.add(MyApp.scopeDescription[index] );
                        }

                        MyApp.featurePane = Ext.create('Ext.container.Container', {
                            componentCls: 'inner'
                        });
                        MyApp.add(MyApp._wrapComponent(MyApp.featurePane, 'feature'));

                        MyApp.featureTotal = Ext.create('Ext.panel.Panel', {
                            width: '100%',
                            html: '

Feature Summary by PSI

',
                            renderTo: Ext.getBody()
                        });

                        MyApp.featurePane.add( MyApp.featureTotal );

                        // Move to features
                        MyApp._loadFeatureDetails();
                    }
                }
            }
        });

        thisStore.loadPage( MyApp.currentScopePage );
    },

    _buildScopeDetails: function(myStore, records) {
        // Filter off the epic from the scope title
        var epicTitle = MyApp.selectedEpicName + ': ';
        var title = records[0].data.Name;
        if ( 0 === title.indexOf( epicTitle ) ) {
            title = title.substr( epicTitle.length );
        }

        MyApp.scopeDetails.push( Ext.create('Rally.ui.grid.Grid', {
            store: myStore,
            title: '' + title + '',
            border: 1,
            columnCfgs: [
                'Name',
                {dataIndex: 'c_SAPProjectNumber', text:'SAP #'},
                'InvestmentCategory',
                'PlannedStartDate',
                'PlannedEndDate',
                'LastUpdateDate',
                'Project'
            ],
            showPagingToolbar: false
        }) );

        MyApp.scopeDescription.push( Ext.create('Ext.panel.Panel', {
            width: '100%',
            html: '
' + records[0].data.Description + '
',
            renderTo: Ext.getBody()
        }) );
    },

    _loadFeatureDetails: function() {
        thisStore = Ext.create('Rally.data.WsapiDataStore', {
            pageSize: 1,    // Load 1 page at a time
            limit: 1,       // Limit to 1

            model: 'PortfolioItem/Feature',
            context: MyApp.globalContext,

            fetch: ['Parent',
                    'Project',
                    'Name',
                    'PreliminaryEstimate',
                    'ValueScore',
                    'RiskScore',
                    'LastUpdateDate',
                    'Description',
                    'Release'
                ],

            filters: [
                    {
                        property: 'Parent.Parent.Name',
                        operator: 'Contains',
                        value: MyApp.selectedEpicName
                    }
                ],

            sorters: {
                property: 'Release',
                direction: 'ASC'
            },

            listeners: {
                load: function( myStore, records ) {
                    MyApp.storeCopies.push( myStore );

                    MyApp._writeFeatureDetails( myStore, records );

                    // Load the next until all pages are loaded
                    if ( myStore.currentPage < myStore.totalCount )
                    {
                        ++MyApp.currentFeaturePage;
                        MyApp._loadFeatureDetails();
                    }
                    else
                    {
                        var index = 0;
                        for (index=0; index< myStore.totalCount; index++ ){
                            MyApp.featurePane.add(MyApp.featureDetails[index]);
                            MyApp.featurePane.add(MyApp.featureDescription[index] );
                        }

                        for (index=0; index< MyApp.storeCopies.length; index++){
                            console.log( MyApp.storeCopies[index] );
                        }
                    }
                }
            }
        });

        thisStore.loadPage( MyApp.currentFeaturePage );
    },

    _writeFeatureDetails: function(myStore, records) {
        var title = records[0].data.Name;

        MyApp.featureDetails.push( Ext.create('Rally.ui.grid.Grid', {
            store: myStore,
            border: 1,
            title: '' + title + '',
            columnCfgs: [
                'Name',
                'PreliminaryEstimate',
                'ValueScore',
                'RiskScore',
                'Project',
                'LastUpdateDate',
                'Release'
            ],
            showPagingToolbar: false
        }));

        MyApp.featureDescription.push( Ext.create('Ext.panel.Panel', {
            width: '100%',
            html: '
' + records[0].data.Description + '
',
            renderTo: Ext.getBody()
        }));
    }
});
<|endoftext|>