<commit_before>Package.describe({
  summary: "Adds famous dead people to the Meteor.users collection.",

  // update this value before you run 'meteor publish'
  version: "1.0.0",

  // if this value isn't set, meteor will default to the directory name
  name: "clinical:accounts-famous-dead-people",

  // and add this value if you want people to access your code from Atmosphere
  git: "http://github.com/awatson1978/accounts-famous-dead-people.git"
});

Package.on_use(function (api) {

  api.use('accounts-base@1.1.3');
  api.use('accounts-password@1.0.5');

  api.addFiles('initialize.users.js', 'server');

  api.addFiles('avatars/ada.lovelace.jpg', "client", {isAsset: true});
  api.addFiles('avatars/alan.turing.jpg', "client", {isAsset: true});
  api.addFiles('avatars/alexis.carrel.jpg', "client", {isAsset: true});
  api.addFiles('avatars/edward.doisy.jpg', "client", {isAsset: true});
  api.addFiles('avatars/edward.tatum.jpg', "client", {isAsset: true});
  api.addFiles('avatars/florence.nightingale.jpg', "client", {isAsset: true});
  api.addFiles('avatars/galen.jpg', "client", {isAsset: true});
  api.addFiles('avatars/george.beadle.jpg', "client", {isAsset: true});
  api.addFiles('avatars/george.wald.jpg', "client", {isAsset: true});
  api.addFiles('avatars/george.washington.carver.jpg', "client", {isAsset: true});
  api.addFiles('avatars/hermann.muller.jpg', "client", {isAsset: true});
  api.addFiles('avatars/hygea.jpg', "client", {isAsset: true});
  api.addFiles('avatars/james.watson.jpg', "client", {isAsset: true});
  api.addFiles('avatars/john.eccles.jpg', "client", {isAsset: true});
  api.addFiles('avatars/kurt.vonnegut.jpg', "client", {isAsset: true});
  api.addFiles('avatars/madam.curie.jpg', "client", {isAsset: true});
  api.addFiles('avatars/mary.shelley.jpg', "client", {isAsset: true});
  api.addFiles('avatars/mother.teresa.jpg', "client", {isAsset: true});
  api.addFiles('avatars/octavia.butler.jpg', "client", {isAsset: true});
  api.addFiles('avatars/roger.sperry.jpg', "client", {isAsset: true});
  api.addFiles('avatars/samuel.clemens.jpg', "client", {isAsset: true});

  api.addFiles('avatars/rosalind.franklin.jpg', "client", {isAsset: true});
  api.addFiles('avatars/nicola.tesla.jpg', "client", {isAsset: true});
  api.addFiles('avatars/grace.hopper.jpg', "client", {isAsset: true});
  api.addFiles('avatars/carl.gauss.jpg', "client", {isAsset: true});
  api.addFiles('avatars/claude.shannon.jpg', "client", {isAsset: true});
  api.addFiles('avatars/barbara.mcclintock.jpg', "client", {isAsset: true});
  api.addFiles('avatars/gertrude.elion.jpg', "client", {isAsset: true});
  api.addFiles('avatars/rachel.carson.jpg', "client", {isAsset: true});
  api.addFiles('avatars/maria.mayer.jpg', "client", {isAsset: true});
  api.addFiles('avatars/rita.levi.montalcini.jpg', "client", {isAsset: true});
  api.addFiles('avatars/elizabeth.blackwell.jpg', "client", {isAsset: true});
});
<commit_msg>added api.versionFrom() and bumped<commit_after>Package.describe({
  summary: "Adds famous dead people to the Meteor.users collection.",

  // update this value before you run 'meteor publish'
  version: "1.0.0",

  // if this value isn't set, meteor will default to the directory name
  name: "clinical:accounts-famous-dead-people",

  // and add this value if you want people to access your code from Atmosphere
  git: "http://github.com/awatson1978/accounts-famous-dead-people.git"
});

Package.on_use(function (api) {
  api.versionsFrom('1.0.3.1');

  api.use('accounts-base@1.1.3');
  api.use('accounts-password@1.0.5');

  api.addFiles('initialize.users.js', 'server');

  api.addFiles('avatars/ada.lovelace.jpg', "client", {isAsset: true});
  api.addFiles('avatars/alan.turing.jpg', "client", {isAsset: true});
  api.addFiles('avatars/alexis.carrel.jpg', "client", {isAsset: true});
  api.addFiles('avatars/edward.doisy.jpg', "client", {isAsset: true});
  api.addFiles('avatars/edward.tatum.jpg', "client", {isAsset: true});
  api.addFiles('avatars/florence.nightingale.jpg', "client", {isAsset: true});
  api.addFiles('avatars/galen.jpg', "client", {isAsset: true});
  api.addFiles('avatars/george.beadle.jpg', "client", {isAsset: true});
  api.addFiles('avatars/george.wald.jpg', "client", {isAsset: true});
  api.addFiles('avatars/george.washington.carver.jpg', "client", {isAsset: true});
  api.addFiles('avatars/hermann.muller.jpg', "client", {isAsset: true});
  api.addFiles('avatars/hygea.jpg', "client", {isAsset: true});
  api.addFiles('avatars/james.watson.jpg', "client", {isAsset: true});
  api.addFiles('avatars/john.eccles.jpg', "client", {isAsset: true});
  api.addFiles('avatars/kurt.vonnegut.jpg', "client", {isAsset: true});
  api.addFiles('avatars/madam.curie.jpg', "client", {isAsset: true});
  api.addFiles('avatars/mary.shelley.jpg', "client", {isAsset: true});
  api.addFiles('avatars/mother.teresa.jpg', "client", {isAsset: true});
  api.addFiles('avatars/octavia.butler.jpg', "client", {isAsset: true});
  api.addFiles('avatars/roger.sperry.jpg', "client", {isAsset: true});
  api.addFiles('avatars/samuel.clemens.jpg', "client", {isAsset: true});

  api.addFiles('avatars/rosalind.franklin.jpg', "client", {isAsset: true});
  api.addFiles('avatars/nicola.tesla.jpg', "client", {isAsset: true});
  api.addFiles('avatars/grace.hopper.jpg', "client", {isAsset: true});
  api.addFiles('avatars/carl.gauss.jpg', "client", {isAsset: true});
  api.addFiles('avatars/claude.shannon.jpg', "client", {isAsset: true});
  api.addFiles('avatars/barbara.mcclintock.jpg', "client", {isAsset: true});
  api.addFiles('avatars/gertrude.elion.jpg', "client", {isAsset: true});
  api.addFiles('avatars/rachel.carson.jpg', "client", {isAsset: true});
  api.addFiles('avatars/maria.mayer.jpg', "client", {isAsset: true});
  api.addFiles('avatars/rita.levi.montalcini.jpg', "client", {isAsset: true});
  api.addFiles('avatars/elizabeth.blackwell.jpg', "client", {isAsset: true});
});
<|endoftext|>


<commit_before>
module("About Asserts (topics/about_asserts.js)");

test("ok", function() {
    ok(__ === true, 'what will satisfy the ok assertion?');
});

test("not ok", function() {
    ok(__ === false, 'what is a false value?');
});

test("equal", function() {
    equal(__, 1 + 1, 'what will satisfy the equal assertion?');
});
<commit_msg>Complete asserts tests to pass<commit_after>
module("About Asserts (topics/about_asserts.js)");

test("ok", function() {
    ok(true === true, 'what will satisfy the ok assertion?');
});

test("not ok", function() {
    ok(false === false, 'what is a false value?');
});

test("equal", function() {
    equal(2, 1 + 1, 'what will satisfy the equal assertion?');
});
<|endoftext|>


<commit_before>$(document).ready(function(){
  var user1, user2, currentSession, startTime, endTime, currentInterval, totalTimeWorking, pairingDurationMs, timer;
  var sessions = [];

  $('button.duration-button').on('click', function(event){
    event.preventDefault();
    if($('input.duration').val() !== "" ){
      currentInterval = parseInt($('input.duration').val());
      pairingDurationMs = currentInterval * 60000;
    } else {
      alert("Please Enter A Real Number");
    }
  });

  $('button.start-pairing').on('click', function(){
    startPairing();
  });

  $('.pause_button').on('click', function(){
    if(timer){
      window.clearInterval(timer);
      timer = null;
    } else {
      startTimerCount();
    }
  });

  $('.exit_session').on('click', function(){
    if(currentSession.timeWorked === 0){
      endSession();
    }
    var activeTime = 0;
    var inActiveTime = 0;
    sessions.forEach(function(pairSession){
      activeTime += pairSession.timeWorked;
      inActiveTime += pairSession.timePaused;
    })
    sessions.push(TotalSessionInfo(activeTime, inActiveTime));
  })

  function PairingSession(user1, user2){
    this.drive = user1;
    this.navigate = user2;
    this.timeWorked = 0;
    this.timePaused = 0;
  }

  function TotalSessionInfo(activeTime, pauseTime){
    this.totalTime = pauseTime + activeTime;
    this.activeTime = activeTime;
    this.pauseTime = pauseTime;
  }

  function startPairing(){
    var date = new Date();
    startTime = date.getTime();
    currentSession = sessions.push(PairingSession(user1, user2));
    startTimerCount();
  }

  function startTimerCount(){
    timer = setInterval(function(){
      totalTimeWorking ++;
      currentInterval --;
      updateTimerCountdown();
      checkDuration();
    }, 60000);
  }

  function stopTimer(){
    window.clearInterval(timer);
  }

  function checkDuration(){
    if(currentInterval === 0){
      endSession();
      alert('Switch it ^');
      startPairing();
    }
  }

  function endSession(){
    var date = new Date();
    endTime = date.getTime();
    currentInterval = pairingDurationMs / 60000;
    currentSession.timeWorked = 20;
    currentSession.timePaused = startTime - endTime - currentInterval;
  }

  function updateTimerCountdown(){
    $('.countdown').val(currentInterval);
  }
});

<commit_msg>Fix Logic to set current Session Info<commit_after>$(document).ready(function(){
  var user1, user2, currentSession, startTime, endTime, currentInterval, totalTimeWorking, pairingDurationMs, timer;
  var sessions = [];

  $('button.duration-button').on('click', function(event){
    event.preventDefault();
    if($('input.duration').val() !== "" ){
      currentInterval = parseInt($('input.duration').val());
      pairingDurationMs = currentInterval * 60000;
    } else {
      alert("Please Enter A Real Number");
    }
  });

  $('button.start-pairing').on('click', function(){
    startPairing();
  });

  $('.pause_button').on('click', function(){
    if(timer){
      window.clearInterval(timer);
      timer = null;
    } else {
      startTimerCount();
    }
  });

  $('.exit_session').on('click', function(){
    if(currentSession.timeWorked === 0){
      endSession();
    }
    var activeTime = 0;
    var inActiveTime = 0;
    sessions.forEach(function(pairSession){
      activeTime += pairSession.timeWorked;
      inActiveTime += pairSession.timePaused;
    })
    sessions.push(TotalSessionInfo(activeTime, inActiveTime));
  })

  function PairingSession(user1, user2){
    this.drive = user1;
    this.navigate = user2;
    this.timeWorked = 0;
    this.timePaused = 0;
  }

  function TotalSessionInfo(activeTime, pauseTime){
    this.totalTime = pauseTime + activeTime;
    this.activeTime = activeTime;
    this.pauseTime = pauseTime;
  }

  function startPairing(){
    var date = new Date();
    startTime = date.getTime();
    currentSession = PairingSession(user1, user2);
    sessions.push(currentSession);
    startTimerCount();
  }

  function startTimerCount(){
    timer = setInterval(function(){
      totalTimeWorking ++;
      currentInterval --;
      updateTimerCountdown();
      checkDuration();
    }, 60000);
  }

  function stopTimer(){
    window.clearInterval(timer);
  }

  function checkDuration(){
    if(currentInterval === 0){
      endSession();
      alert('Switch it ^');
      startPairing();
    }
  }

  function endSession(){
    var date = new Date();
    endTime = date.getTime();
    currentInterval = pairingDurationMs / 60000;
    currentSession.timeWorked = currentInterval;
    currentSession.timePaused = startTime - endTime - totalTimeWorking;
    totalTimeWorking = 0;
  }

  function updateTimerCountdown(){
    $('.countdown').val(currentInterval);
  }
});

<|endoftext|>


<commit_before>/**
 Protein Engineering Analysis Tool Structure Analysis (PEATSA)
 Copyright (C) 2010 Michael Johnston & Jens Erik Nielsen

 Author: Michael Johnston

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

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

 Contact information:
 Email: Jens.Nielsen_at_gmail.com
 Normal mail:
 Jens Nielsen
 SBBS, Conway Institute
 University College Dublin
 Dublin 4, Ireland
 **/

//Global variable referencing the javascript object that
//slides in and out the graphs
var collapsible;
var graph;
var data;

// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['piechart','columnchart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(CreateGraph);

function HideContent(d)
{
	document.getElementById(d).style.display = "none";
}

function ShowContent(d)
{
	document.getElementById(d).style.display = "block";
}

function ReverseDisplay(d)
{
	if(document.getElementById(d).style.display == "none")
	{
		document.getElementById(d).style.display = "block";
	}
	else
	{
		document.getElementById(d).style.display = "none";
	}
}

//Sets up the variables necessary for showing and hiding the results graphs.
//Initialises the global variable 'collapsible' which is the javascript object
//that animates the opening and closing of the graph image.
//Also hides the image initially
function InitialiseGraph()
{
	collapsible = new Fx.Slide($('resultsGraph'), {
				   duration: 500,
				   transition: Fx.Transitions.linear
				   });
	HideGraphBox();
}

function CreateGraph()
{
	graph = new google.visualization.ColumnChart(document.getElementById('resultsGraph'));
}

//This function is called when one graph is displayed and another is requested
function HandleGraphChange()
{
	graph.draw(data, {height: 400, legend: 'none', fontSize: 12, title: document.getElementById('resultsGraph').name});
	//Slide the image out and remove this handler from the collapsible object
	collapsible.slideIn();
	collapsible.removeEvent('complete', HandleGraphChange);
}

function SetGraphData(resultType)
{
	// Create our data table.
	var calculationData = dataForCalculation(resultType);
	data = new google.visualization.DataTable();

	//Stability and Binding calcs just report Mutation and Total
	//For pKa calls each mutation will posisble have results for a number of ionisable residues
	if(resultType == "Stability" || resultType == "Binding")
	{
		data.addColumn('string', 'Mutation');
		data.addColumn('number', 'Free-Energy Difference');

		for(var i=0; i < calculationData.length; i++)
		{
			calculationData[i][1] = parseFloat(calculationData[i][1]);
			data.addRow(calculationData[i]);
		}
	}
	else if(resultType == "Scan")
	{
		data.addColumn('string', 'Mutation');
		for(i=1; i<calculationData[0].length; i++)
		{
			data.addColumn('number', calculationData[0][i]);
		}

		for(var i=1; i < calculationData.length; i++)
		{
			for(j=1; j<calculationData[i].length; j++)
			{
				calculationData[i][j] = parseFloat(calculationData[i][j]);
			}
			data.addRow(calculationData[i]);
		}
	}
}

//This function shows and hides the results graphs on the result page
//There are three possibilities
//1 - Open a graph when none is displayed
//2 - Close the displayed graph
//3 - Open a new graph when one is already displayed
//resultType is one of Stability, Binding or deltapKa
function ShowResultsGraph(resultType)
{
	//Check is a new graph requested i.e. it the name different to the resultsGraph name attribute
	if(document.getElementById('resultsGraph').name != resultType)
	{
		SetGraphData(resultType);
		document.getElementById('resultsGraph').name = resultType;
		//If an graph is already displayed we close it, replace it, and open it.
		//Otherwise we just replace the current chart and display it
		if(collapsible.open == 1)
		{
			//Set the HandleGraphChange function to be called after
			//we slide the graph out
			collapsible.addEvent('complete', HandleGraphChange);
			//Set the new link for the graph - This will also be used
			//by HandleGraphChange to obtain the new url
			//document.getElementById('resultsGraphLink').href = url;
			//Slide the graph out - when this is done HandleGraphChange will execute.
			collapsible.slideOut();
		}
		else
		{
			graph.draw(data, {height: 400, legend: 'none', fontSize: 12, title: resultType, titleY: 'kj/mol'});
			//document.getElementById('resultsGraphLink').href = url;
		        collapsible.toggle();
		}
	}
	else
	{
		//Its the same graph as was last selected - just toggle
		collapsible.toggle();
	}
}

function HideGraphBox()
{
	collapsible.hide();
	ShowContent('resultsGraph');
}

function HideElement(id)
{
	element = new Fx.Slide($(id), {
				   duration: 500,
				   transition: Fx.Transitions.linear
				   });
	element.hide()
}

function ToggleElement(id)
{
	element = new Fx.Slide($(id), {
				   duration: 250,
				   transition: Fx.Transitions.linear
				   });
	element.toggle();
}

//--></script>

<commit_msg>Add code to create bump score graph<commit_after>/**
 Protein Engineering Analysis Tool Structure Analysis (PEATSA)
 Copyright (C) 2010 Michael Johnston & Jens Erik Nielsen

 Author: Michael Johnston

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

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

 Contact information:
 Email: Jens.Nielsen_at_gmail.com
 Normal mail:
 Jens Nielsen
 SBBS, Conway Institute
 University College Dublin
 Dublin 4, Ireland
 **/

//Global variable referencing the javascript object that
//slides in and out the graphs
var collapsible;
var graph;
var data;

// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['piechart','columnchart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(CreateGraph);

function HideContent(d)
{
	document.getElementById(d).style.display = "none";
}

function ShowContent(d)
{
	document.getElementById(d).style.display = "block";
}

function ReverseDisplay(d)
{
	if(document.getElementById(d).style.display == "none")
	{
		document.getElementById(d).style.display = "block";
	}
	else
	{
		document.getElementById(d).style.display = "none";
	}
}

//Sets up the variables necessary for showing and hiding the results graphs.
//Initialises the global variable 'collapsible' which is the javascript object
//that animates the opening and closing of the graph image.
//Also hides the image initially
function InitialiseGraph()
{
	collapsible = new Fx.Slide($('resultsGraph'), {
				   duration: 500,
				   transition: Fx.Transitions.linear
				   });
	HideGraphBox();
}

function CreateGraph()
{
	graph = new google.visualization.ColumnChart(document.getElementById('resultsGraph'));
}

//This function is called when one graph is displayed and another is requested
function HandleGraphChange()
{
	graph.draw(data, {height: 400, legend: 'none', fontSize: 12, title: document.getElementById('resultsGraph').name});
	//Slide the image out and remove this handler from the collapsible object
	collapsible.slideIn();
	collapsible.removeEvent('complete', HandleGraphChange);
}

function SetGraphData(resultType)
{
	// Create our data table.
	var calculationData = dataForCalculation(resultType);
	data = new google.visualization.DataTable();

	//Stability and Binding calcs just report Mutation and Total
	//For pKa calls each mutation will posisble have results for a number of ionisable residues
	if(resultType == "Stability" || resultType == "Binding")
	{
		data.addColumn('string', 'Mutation');
		data.addColumn('number', 'Free-Energy Difference');

		for(var i=0; i < calculationData.length; i++)
		{
			calculationData[i][1] = parseFloat(calculationData[i][1]);
			data.addRow(calculationData[i]);
		}
	}
	else if(resultType == "Scan")
	{
		data.addColumn('string', 'Mutation');
		for(i=1; i<calculationData[0].length; i++)
		{
			data.addColumn('number', calculationData[0][i]);
		}

		for(var i=1; i < calculationData.length; i++)
		{
			for(j=1; j<calculationData[i].length; j++)
			{
				calculationData[i][j] = parseFloat(calculationData[i][j]);
			}
			data.addRow(calculationData[i]);
		}
	}
	else if(resultType == "Modelling")
	{
		data.addColumn('string', 'Mutation');
		data.addColumn('number', 'Bump Score');

		for(var i=0; i < calculationData.length; i++)
		{
			calculationData[i][1] = parseFloat(calculationData[i][1]);
			data.addRow(calculationData[i]);
		}
	}
}

//This function shows and hides the results graphs on the result page
//There are three possibilities
//1 - Open a graph when none is displayed
//2 - Close the displayed graph
//3 - Open a new graph when one is already displayed
//resultType is one of Stability, Binding or deltapKa
function ShowResultsGraph(resultType)
{
	//Check is a new graph requested i.e. it the name different to the resultsGraph name attribute
	if(document.getElementById('resultsGraph').name != resultType)
	{
		SetGraphData(resultType);
		document.getElementById('resultsGraph').name = resultType;
		//If an graph is already displayed we close it, replace it, and open it.
		//Otherwise we just replace the current chart and display it
		if(collapsible.open == 1)
		{
			//Set the HandleGraphChange function to be called after
			//we slide the graph out
			collapsible.addEvent('complete', HandleGraphChange);
			//Set the new link for the graph - This will also be used
			//by HandleGraphChange to obtain the new url
			//document.getElementById('resultsGraphLink').href = url;
			//Slide the graph out - when this is done HandleGraphChange will execute.
			collapsible.slideOut();
		}
		else
		{
			graph.draw(data, {height: 400, legend: 'none', fontSize: 12, title: resultType, titleY: 'kj/mol'});
			//document.getElementById('resultsGraphLink').href = url;
		        collapsible.toggle();
		}
	}
	else
	{
		//Its the same graph as was last selected - just toggle
		collapsible.toggle();
	}
}

function HideGraphBox()
{
	collapsible.hide();
	ShowContent('resultsGraph');
}

function HideElement(id)
{
	element = new Fx.Slide($(id), {
				   duration: 500,
				   transition: Fx.Transitions.linear
				   });
	element.hide()
}

function ToggleElement(id)
{
	element = new Fx.Slide($(id), {
				   duration: 250,
				   transition: Fx.Transitions.linear
				   });
	element.toggle();
}

//--></script>

<|endoftext|>


<commit_before>import { findElementWithAssert, every } from '../helpers';

/**
 * Creates a predicate to validate if an element contains a subtext
 *
 * @example
 *
 Page Title

 *
 *   var page = PageObject.create({
 *     titleIncludes: contains('h1')
 *   });
 *
 *   assert.ok(page.titleIncludes('Page'));
 *
 * @param {string} selector - CSS selector of the element to check
 * @param {Object} options - Additional options
 * @param {string} options.scope - Overrides parent scope
 * @param {number} options.index - Reduce the set of matched elements to the one at the specified index
 * @return {Descriptor}
 */
export function contains(selector, options = {}) {
  return {
    isDescriptor: true,

    value(textToSearch) {
      let elements = findElementWithAssert(this, selector, options);

      return every(elements, function(element) {
        return element.text().indexOf(textToSearch) >= 0
      });
    }
  };
}
<commit_msg>Use jsdoc documentation on contains property<commit_after>import { findElementWithAssert, every } from '../helpers';

/**
 * Validates if an element or a set of elements contain a subtext
 *
 * @example
 *
 * // Lorem ipsum
 *
 * let page = PageObject.create({
 *  spanContains: PageObject.contains('span')
 * });
 *
 * assert.ok(page.spanContains('ipsum'));
 *
 * @example
 *
 * // lorem
 * // ipsum
 * // dolor
 *
 * let page = PageObject.create({
 *   spansContain: PageObject.contains('span', { multiple: true })
 * });
 *
 * // not all spans contain 'lorem'
 * assert.ok(!page.spansContain('lorem'));
 *
 * @example
 *
 * // super text
 * // regular text
 *
 * let page = PageObject.create({
 *   spansContain: PageObject.contains('span', { multiple: true })
 * });
 *
 * // all spans contain 'text'
 * assert.ok(page.spanContains('text'));
 *
 * @example
 *
 * //
lorem

 * //
ipsum

 * //
dolor

 *
 * let page = PageObject.create({
 *   spanContains: PageObject.contains('span', { scope: '.scope' })
 * });
 *
 * assert.ok(!page.spanContains('lorem'));
 * assert.ok(page.foo('ipsum'));
 *
 * @example
 *
 * //
lorem

 * //
ipsum

 * //
dolor

 *
 * let page = PageObject.create({
 *   scope: '.scope',

 *   spanContains: PageObject.contains('span')
 * });
 *
 * assert.ok(!page.spanContains('lorem'));
 * assert.ok(page.foo('ipsum'));
 *
 * @public
 *
 * @param {string} selector - CSS selector of the element to check
 * @param {Object} options - Additional options
 * @param {string} options.scope - Nests provided scope with parent's scope
 * @param {number} options.at - Reduce the set of matched elements to the one at the specified index
 * @param {boolean} options.resetScope - Override parent's scope
 * @param {boolean} options.multiple - Check if all elements matched by selector contain the subtext
 * @return {Descriptor}
 *
 * @throws Will throw an error if no element matches selector
 * @throws Will throw an error if multiple elements are matched by selector and multiple options is not set
 */
export function contains(selector, options = {}) {
  return {
    isDescriptor: true,

    value(textToSearch) {
      let elements = findElementWithAssert(this, selector, options);

      return every(elements, function(element) {
        return element.text().indexOf(textToSearch) >= 0
      });
    }
  };
}
<|endoftext|>


<commit_before>define(function (require) {

  var React = require('react/addons'),
    Backbone = require('backbone'),
    _ = require('underscore'),
    stores = require('stores'),

    BootstrapModalMixin = require('components/mixins/BootstrapModalMixin.react'),
    BreadcrumbNav = require('components/common/breadcrumb/BreadcrumbNav.react'),

    ImageSelectStep = require('./launch/steps/ImageSelectStep.react'),
    NameIdentityVersionStep = require('./launch/steps/NameIdentityVersionStep.react'),
    SizeSelectStep = require('./launch/steps/SizeSelectStep.react'),
    ProjectSelectStep = require('./launch/steps/ProjectSelectStep.react'),
    UserOptionsStep = require('./launch/steps/UserOptionsStep.react'),
    AdministratorOptionsStep = require('./launch/steps/AdminOptionsStep.react'),
    ReviewLaunchStep = require('./launch/steps/ReviewLaunchStep.react');

  var IMAGE_STEP = 0,
    INFORMATION_STEP = 1,
    SIZE_STEP = 2,
    PROJECT_STEP = 3,
    OPTIONS_STEP = 4,
    ADMIN_OPTIONS_STEP = 5,
    REVIEW_STEP = 6;

  return React.createClass({
    mixins: [BootstrapModalMixin],

    propTypes: {
      image: React.PropTypes.instanceOf(Backbone.Model),
      project: React.PropTypes.instanceOf(Backbone.Model),
      onConfirm: React.PropTypes.instanceOf(Backbone.Model),
    },

    getInitialState: function () {
      return {
	image: this.props.image,
        project: this.props.project,
        step: this.props.image ? INFORMATION_STEP : IMAGE_STEP,
        title: "Image",
        breadcrumbs: [
            {name:"Image",step:IMAGE_STEP, inactive:this.props.image ? true : false},
            {name:"Version & Provider",step:INFORMATION_STEP},
            {name:"Size",step:SIZE_STEP},
            {name:"Project",step:PROJECT_STEP, inactive:this.props.project ? true : false},
            {name:"Options",step:OPTIONS_STEP, inactive:true},
            {name:"Review",step:REVIEW_STEP}
        ]
      };
    },
    renderImageSelect: function() {
        return (
                <ImageSelectStep
                    image={this.state.image}
                            onPrevious={this.cancel}
                            onNext={this.onNext}
                />
      );
    },
    renderNameStep: function() {
        return (
                <NameIdentityVersionStep
                    image={this.state.image}
                    name={this.state.name}
                    identity={this.state.identity}
                    version={this.state.version}
                    onPrevious={this.onPrevious}
                    onNext={this.onNext}
                />
      );
    },
    renderSizeStep: function() {
        return (
                <SizeSelectStep
                    image={this.state.image}
                    identity={this.state.identity}
                    size={this.state.size}
                    onPrevious={this.onPrevious}
                    onNext={this.onNext}
                />
      );
    },
    renderProjectStep: function () {
      return (
        <ProjectSelectStep
          project={this.state.project}
          onPrevious={this.onPrevious}
          onNext={this.onNext}
          onFinished={this.toReview}
          />
      );
    },
    renderUserOptionsStep: function () {
      return (
        <UserOptionsStep
          launchOptions={this.state.launchOptions}
          onPrevious={this.onPrevious}
          onNext={this.onNext}
          onFinished={this.toReview}
          />
      );
    },
    renderStaffOptionsStep: function () {
      return (
        <AdministratorOptionsStep
          launchOptions={this.state.launchOptions}
          onPrevious={this.onPrevious}
          onNext={this.onNext}
          onFinished={this.toReview}
          />
      );
    },
    renderReviewLaunchStep: function () {
      return (
        <ReviewLaunchStep
          launchData={this.state}
          onPrevious={this.onPrevious}
          onNext={this.onCompleted}
          />
      );
    },
    renderBody: function () {
      var step = this.state.step;
      switch(step) {
	case IMAGE_STEP:
          return this.renderImageSelect();
        case INFORMATION_STEP:
          return this.renderNameStep();
        case SIZE_STEP:
          return this.renderSizeStep();
        case PROJECT_STEP:
          return this.renderProjectStep();
        case OPTIONS_STEP:
        //return this.renderUserOptionsStep(); //TODO: Re-enable when 'Boot Scripts', 'Licenses' are added.
        case ADMIN_OPTIONS_STEP:
        //return this.renderStaffOptionsStep(); //TODO: Re-enable when 'Hypervisor-Select', 'No-Deploy' are added.
        case REVIEW_STEP:
          return this.renderReviewLaunchStep();
      }
    },

    hoverTitleChange: function (text) {
      this.setState({title: text});
    },

    changeTitleBack: function () {
      this.setState({title: this.state.breadcrumbs[this.state.step].name});
    },

    renderBreadCrumbTrail: function () {
      var user = stores.ProfileStore.get();
      var self = this;
      var breadcrumbs = this.state.breadcrumbs;

      if (user.get('is_staff') && breadcrumbs[5].step !== 5) {
        breadcrumbs.splice(5, 0, {name: "Admin", step: ADMIN_OPTIONS_STEP, inactive: true});
      }
      breadcrumbs.map(function(breadcrumb, index, array){
          var state;
          if(breadcrumb.inactive){
              state = "inactive"
          } else if(breadcrumb.step === self.state.step) {
              state = "active"
          } else if (breadcrumb.step < self.state.step) {
              state = "available"
          } else {
              state = ""
          }
         breadcrumb.state = state;
      });
      return (<BreadcrumbNav
          breadcrumbs={breadcrumbs}
          onMouseOn={this.hoverTitleChange}
          onMouseOff={this.changeTitleBack}
          step = {this.state.step}
          onCrumbClick={self.toStep}
          />
      );
    },
    render: function () {
      return (

                {this.renderCloseButton()}
                Instance Launch Wizard- {this.state.title}

                {this.renderBreadCrumbTrail()}

                {this.renderBody()}

      );
    },

    //
    // Mounting & State
    // ----------------
    //

    getState: function () {
      return this.state;
    },

    updateState: function () {
      if (this.isMounted()) this.setState(this.getState());
    },

    componentDidMount: function () {
      stores.ProviderStore.addChangeListener(this.updateState);
      stores.IdentityStore.addChangeListener(this.updateState);
      stores.SizeStore.addChangeListener(this.updateState);
      stores.ProjectStore.addChangeListener(this.updateState);
      stores.ProjectVolumeStore.addChangeListener(this.updateState);
      stores.ProjectInstanceStore.addChangeListener(this.updateState);
      stores.InstanceStore.addChangeListener(this.updateState);
      stores.ImageVersionStore.addChangeListener(this.updateState);
      stores.MaintenanceMessageStore.addChangeListener(this.updateState);
    },

    componentWillUnmount: function () {
      stores.ProviderStore.removeChangeListener(this.updateState);
      stores.IdentityStore.removeChangeListener(this.updateState);
      stores.SizeStore.removeChangeListener(this.updateState);
      stores.ProjectStore.removeChangeListener(this.updateState);
      stores.ProjectVolumeStore.removeChangeListener(this.updateState);
      stores.ProjectInstanceStore.removeChangeListener(this.updateState);
      stores.InstanceStore.removeChangeListener(this.updateState);
      stores.ImageVersionStore.removeChangeListener(this.updateState);
      stores.MaintenanceMessageStore.removeChangeListener(this.updateState);
    },

    //
    // Internal Modal Callbacks
    // ------------------------
    //

    cancel: function () {
      this.hide();
    },
    onCompleted: function (launch_data) {
      this.hide();
      this.props.onConfirm(launch_data);
    },
    onPrevious: function(data) {
        var previousStep = this.state.step - 1,
            data = data || {},
            state = _.extend({step: previousStep}, data);
        if(this.props.image && this.state.step == INFORMATION_STEP) {
            //Don't go to 'Step 0' if image provided.
            this.cancel()
        }
        if(this.state.step == REVIEW_STEP) {
            //TODO: Remove this when re-adding User/Admin Options
            if(this.props.project) {
                //Skip 'Project Selection' step if project provided.
                state.step = SIZE_STEP;
            } else {
                state.step = PROJECT_STEP;
            }
      }
      state.title = this.state.breadcrumbs[state.step].name;
      this.setState(state);
    },
    onNext: function (data) {
      var nextStep = this.state.step + 1,
        data = data || {},
        state = _.extend({step: nextStep}, data);
      if (this.props.project && state.step == PROJECT_STEP) {
        //Skip to the review step.
        state.step = REVIEW_STEP;
      } else if (this.state.step == PROJECT_STEP) {
        //TODO: Remove this line when re-adding User/Admin Options
        state.step = REVIEW_STEP;
      }
      state.title = this.state.breadcrumbs[state.step].name;
      this.setState(state);
    },
    toReview: function (data) {
      var state = _.extend({step: REVIEW_STEP}, data);
      this.setState(state);
    },
    toStep: function (breadcrumb) {
      this.setState({title: this.state.breadcrumbs[breadcrumb.step].name});
      this.setState({step: breadcrumb.step});
    }
  });

});
<commit_msg>fix array out of bounds error for review_step<commit_after>define(function (require) {

  var React = require('react/addons'),
    Backbone = require('backbone'),
    _ = require('underscore'),
    stores = require('stores'),

    BootstrapModalMixin = require('components/mixins/BootstrapModalMixin.react'),
    BreadcrumbNav = require('components/common/breadcrumb/BreadcrumbNav.react'),

    ImageSelectStep = require('./launch/steps/ImageSelectStep.react'),
    NameIdentityVersionStep = require('./launch/steps/NameIdentityVersionStep.react'),
    SizeSelectStep = require('./launch/steps/SizeSelectStep.react'),
    ProjectSelectStep = require('./launch/steps/ProjectSelectStep.react'),
    UserOptionsStep = require('./launch/steps/UserOptionsStep.react'),
    AdministratorOptionsStep = require('./launch/steps/AdminOptionsStep.react'),
    ReviewLaunchStep = require('./launch/steps/ReviewLaunchStep.react');

  var IMAGE_STEP = 0,
    INFORMATION_STEP = 1,
    SIZE_STEP = 2,
    PROJECT_STEP = 3,
    OPTIONS_STEP = 4,
    ADMIN_OPTIONS_STEP = 5,
    REVIEW_STEP = 6;

  return React.createClass({
    mixins: [BootstrapModalMixin],

    propTypes: {
      image: React.PropTypes.instanceOf(Backbone.Model),
      project: React.PropTypes.instanceOf(Backbone.Model),
      onConfirm: React.PropTypes.instanceOf(Backbone.Model),
    },

    getInitialState: function () {
      return {
	image: this.props.image,
        project: this.props.project,
        step: this.props.image ? INFORMATION_STEP : IMAGE_STEP,
        title: "Image",
        breadcrumbs: [
            {name:"Image",step:IMAGE_STEP, inactive:this.props.image ? true : false},
            {name:"Version & Provider",step:INFORMATION_STEP},
            {name:"Size",step:SIZE_STEP},
            {name:"Project",step:PROJECT_STEP, inactive:this.props.project ? true : false},
            {name:"Options",step:OPTIONS_STEP, inactive:true},
            {name:"Review",step:REVIEW_STEP}
        ]
      };
    },
    renderImageSelect: function() {
        return (
                <ImageSelectStep
                    image={this.state.image}
                            onPrevious={this.cancel}
                            onNext={this.onNext}
                />
      );
    },
    renderNameStep: function() {
        return (
                <NameIdentityVersionStep
                    image={this.state.image}
                    name={this.state.name}
                    identity={this.state.identity}
                    version={this.state.version}
                    onPrevious={this.onPrevious}
                    onNext={this.onNext}
                />
      );
    },
    renderSizeStep: function() {
        return (
                <SizeSelectStep
                    image={this.state.image}
                    identity={this.state.identity}
                    size={this.state.size}
                    onPrevious={this.onPrevious}
                    onNext={this.onNext}
                />
      );
    },
    renderProjectStep: function () {
      return (
        <ProjectSelectStep
          project={this.state.project}
          onPrevious={this.onPrevious}
          onNext={this.onNext}
          onFinished={this.toReview}
          />
      );
    },
    renderUserOptionsStep: function () {
      return (
        <UserOptionsStep
          launchOptions={this.state.launchOptions}
          onPrevious={this.onPrevious}
          onNext={this.onNext}
          onFinished={this.toReview}
          />
      );
    },
    renderStaffOptionsStep: function () {
      return (
        <AdministratorOptionsStep
          launchOptions={this.state.launchOptions}
          onPrevious={this.onPrevious}
          onNext={this.onNext}
          onFinished={this.toReview}
          />
      );
    },
    renderReviewLaunchStep: function () {
      return (
        <ReviewLaunchStep
          launchData={this.state}
          onPrevious={this.onPrevious}
          onNext={this.onCompleted}
          />
      );
    },
    renderBody: function () {
      var step = this.state.step;
      switch(step) {
	case IMAGE_STEP:
          return this.renderImageSelect();
        case INFORMATION_STEP:
          return this.renderNameStep();
        case SIZE_STEP:
          return this.renderSizeStep();
        case PROJECT_STEP:
          return this.renderProjectStep();
        case OPTIONS_STEP:
        //return this.renderUserOptionsStep(); //TODO: Re-enable when 'Boot Scripts', 'Licenses' are added.
        case ADMIN_OPTIONS_STEP:
        //return this.renderStaffOptionsStep(); //TODO: Re-enable when 'Hypervisor-Select', 'No-Deploy' are added.
        case REVIEW_STEP:
          return this.renderReviewLaunchStep();
      }
    },

    hoverTitleChange: function (text) {
      this.setState({title: text});
    },

    changeTitleBack: function () {
      this.setState({title: this.state.breadcrumbs[this.state.step].name});
    },

    renderBreadCrumbTrail: function () {
      var user = stores.ProfileStore.get();
      var self = this;
      var breadcrumbs = this.state.breadcrumbs;

      if (user.get('is_staff') && breadcrumbs[5].step !== 5) {
        breadcrumbs.splice(5, 0, {name: "Admin", step: ADMIN_OPTIONS_STEP, inactive: true});
      }
      breadcrumbs.map(function(breadcrumb, index, array){
          var state;
          if(breadcrumb.inactive){
              state = "inactive"
          } else if(breadcrumb.step === self.state.step) {
              state = "active"
          } else if (breadcrumb.step < self.state.step) {
              state = "available"
          } else {
              state = ""
          }
         breadcrumb.state = state;
      });
      return (<BreadcrumbNav
          breadcrumbs={breadcrumbs}
          onMouseOn={this.hoverTitleChange}
          onMouseOff={this.changeTitleBack}
          step = {this.state.step}
          onCrumbClick={self.toStep}
          />
      );
    },
    render: function () {
      return (

                {this.renderCloseButton()}
                Instance Launch Wizard- {this.state.title}

                {this.renderBreadCrumbTrail()}

                {this.renderBody()}

      );
    },

    //
    // Mounting & State
    // ----------------
    //

    getState: function () {
      return this.state;
    },

    updateState: function () {
      if (this.isMounted()) this.setState(this.getState());
    },

    componentDidMount: function () {
      stores.ProviderStore.addChangeListener(this.updateState);
      stores.IdentityStore.addChangeListener(this.updateState);
      stores.SizeStore.addChangeListener(this.updateState);
      stores.ProjectStore.addChangeListener(this.updateState);
      stores.ProjectVolumeStore.addChangeListener(this.updateState);
      stores.ProjectInstanceStore.addChangeListener(this.updateState);
      stores.InstanceStore.addChangeListener(this.updateState);
      stores.ImageVersionStore.addChangeListener(this.updateState);
      stores.MaintenanceMessageStore.addChangeListener(this.updateState);
    },

    componentWillUnmount: function () {
      stores.ProviderStore.removeChangeListener(this.updateState);
      stores.IdentityStore.removeChangeListener(this.updateState);
      stores.SizeStore.removeChangeListener(this.updateState);
      stores.ProjectStore.removeChangeListener(this.updateState);
      stores.ProjectVolumeStore.removeChangeListener(this.updateState);
      stores.ProjectInstanceStore.removeChangeListener(this.updateState);
      stores.InstanceStore.removeChangeListener(this.updateState);
      stores.ImageVersionStore.removeChangeListener(this.updateState);
      stores.MaintenanceMessageStore.removeChangeListener(this.updateState);
    },

    //
    // Internal Modal Callbacks
    // ------------------------
    //

    cancel: function () {
      this.hide();
    },
    onCompleted: function (launch_data) {
      this.hide();
      this.props.onConfirm(launch_data);
    },
    onPrevious: function(data) {
        var previousStep = this.state.step - 1,
            data = data || {},
            state = _.extend({step: previousStep}, data);
        if(this.props.image && this.state.step == INFORMATION_STEP) {
            //Don't go to 'Step 0' if image provided.
            this.cancel()
        }
        if(this.state.step == REVIEW_STEP) {
            //TODO: Remove this when re-adding User/Admin Options
            if(this.props.project) {
                //Skip 'Project Selection' step if project provided.
                state.step = SIZE_STEP;
            } else {
                state.step = PROJECT_STEP;
            }
      }
      state.title = this.state.breadcrumbs[state.step].name;
      this.setState(state);
    },
    onNext: function (data) {
      var nextStep = this.state.step + 1,
        data = data || {},
        state = _.extend({step: nextStep}, data);
      if (this.props.project && state.step == PROJECT_STEP) {
        //Skip to the review step.
        state.step = REVIEW_STEP - 1;
      } else if (this.state.step == PROJECT_STEP) {
        //TODO: Remove this line when re-adding User/Admin Options
        state.step = REVIEW_STEP - 1;
      }
      state.title = this.state.breadcrumbs[state.step].name;
      this.setState(state);
    },
    toReview: function (data) {
      var state = _.extend({step: REVIEW_STEP}, data);
      this.setState(state);
    },
    toStep: function (breadcrumb) {
      this.setState({title: this.state.breadcrumbs[breadcrumb.step].name});
      this.setState({step: breadcrumb.step});
    }
  });

});
<|endoftext|>


<commit_before>var L = A.Lang,
	isArray = L.isArray,
	isNumber = L.isNumber,
	isString = L.isString,

	isNode = function(v) {
		return (v instanceof A.Node);
	},

	isNodeList = function(v) {
		return (v instanceof A.NodeList);
	},

	toInitialCap = A.cached(
		function(str) {
			return str.substring(0, 1).toUpperCase() + str.substring(1);
		}
	),

	ADD = 'add',
	ADD_NODE = 'addNode',
	BOUNDING_BOX = 'boundingBox',
	BUTTON = 'button',
	BUTTON_TYPE = 'buttonType',
	CONTENT_BOX = 'contentBox',
	CONTAINER = 'container',
	DEFAULT = 'default',
	DEFAULT_NAME = 'defaultName',
	DEFAULT_OPTIONS = 'defaultOptions',
	DEFAULT_VALUE = 'defaultValue',
	DOT = '.',
	DRAG = 'drag',
	DRAG_CONTAINER = 'dragContainer',
	DRAG_CONTAINER_NODE = 'dragContainerNode',
	DRAG_NODES_LIST = 'dragNodesList',
	DROP = 'drop',
	DROP_CONTAINER = 'dropContainer',
	DROP_CONTAINER_NODE = 'dropContainerNode',
	EMPTY_STR = '',
	FIELD = 'field',
	FIELDS = 'fields',
	FORM_BUILDER_FIELD = 'form-builder-field',
	FORM_BUILDER_MULTIPLE_CHOICE_FIELD = 'form-builder-multiple-choice-field',
	ICON = 'icon',
	ID = 'id',
	INPUT = 'input',
	ITEM = 'item',
	LABEL = 'label',
	MULTIPLE = 'multiple',
	NAME = 'name',
	NODE = 'node',
	OPTION = 'option',
	OPTION_TEMPLATE = 'optionTemplate',
	OPTIONS = 'options',
	PREDEFINED_VALUE = 'predefinedValue',
	PROXY = 'proxy',
	REMOVE = 'remove',
	RESET = 'reset',
	SUBMIT = 'submit',
	SPACE = ' ',
	TEMPLATE = 'template',
	TEMPLATE_NODE = 'templateNode',
	TEXT = 'text',
	TYPE = 'type',
	VALUE = 'value',

	getCN = A.ClassNameManager.getClassName,

	CSS_FIELD_INPUT = getCN(FIELD, INPUT),
	CSS_FIELD_INPUT_TEXT = getCN(FIELD, INPUT, TEXT),
	CSS_FIELD_OPTIONS_ADD = getCN(FIELD, OPTIONS, ADD),
	CSS_FIELD_OPTIONS_ITEM = getCN(FIELD, OPTIONS, ITEM),
	CSS_FIELD_OPTIONS_ITEM_INPUT = getCN(FIELD, OPTIONS, ITEM, INPUT),
	CSS_FIELD_OPTIONS_ITEM_INPUT_NAME = getCN(FIELD, OPTIONS, ITEM, INPUT, NAME),
	CSS_FIELD_OPTIONS_ITEM_INPUT_VALUE = getCN(FIELD, OPTIONS, ITEM, INPUT, VALUE),
	CSS_FIELD_OPTIONS_ITEM_REMOVE = getCN(FIELD, OPTIONS, ITEM, REMOVE),

	CSS_FORM_BUILDER_FIELD = getCN(FORM_BUILDER_FIELD),
	CSS_FORM_BUILDER_FIELD_NODE = getCN(FORM_BUILDER_FIELD, NODE),
	CSS_FORM_BUILDER_INPUT_FIELD_NODE = getCN(FORM_BUILDER_INPUT_FIELD, NODE),

	CSS_STATE_DEFAULT = getCN(STATE, DEFAULT),

	TPL_OPTION = '
' +
					'<input type="text" name="name" class="' + [CSS_FIELD_OPTIONS_ITEM_INPUT, CSS_FIELD_OPTIONS_ITEM_INPUT_NAME, CSS_FIELD_INPUT, CSS_FIELD_INPUT_TEXT].join(SPACE) + '" value="{name}" />' +
					'<input type="text" name="value" class="' + [CSS_FIELD_OPTIONS_ITEM_INPUT, CSS_FIELD_OPTIONS_ITEM_INPUT_VALUE, CSS_FIELD_INPUT, CSS_FIELD_INPUT_TEXT].join(SPACE) + '" value="{value}" />' +
					' ' +
				 '
';

	TPL_ADD = 'Add an option',

	KEY_ENTER = 13

var FieldOptions = A.Component.create({

	NAME: OPTIONS,

	ATTRS: {

		allowClear: {
			value: false
		},

		defaultName: {
			value: EMPTY_STR
		},

		defaultValue: {
			value: EMPTY_STR
		},

		options: {
			value: [],
			getter: '_getOptions',
			validator: isArray
		},

		addNode: {
			valueFn: function() {
				return A.Node.create(TPL_ADD);
			}
		}

	},

	HTML_PARSER: {
		addNode: DOT + CSS_FIELD_OPTIONS_ADD
	},

	UI_ATTRS: [OPTIONS],

	EXTENDS: A.Widget,

	prototype: {

		initializer: function() {
			var instance = this;

			instance.boundingBox = instance.get(BOUNDING_BOX);
			instance.contentBox = instance.get(CONTENT_BOX);
		},

		renderUI: function() {
			var instance = this;
			var boundingBox = instance.boundingBox;
			var addNode = instance.get(ADD_NODE);

			if (!addNode.inDoc()) {
				boundingBox.append(addNode);
			}
		},

		bindUI: function() {
			var instance = this;
			var boundingBox = instance.boundingBox;
			var addNode = instance.get(ADD_NODE);

			addNode.on('click', A.bind(instance._onClickAdd, instance));

			boundingBox.delegate('click', A.bind(instance._onClickOptionRemove, instance), DOT + CSS_FIELD_OPTIONS_ITEM_REMOVE);
			boundingBox.delegate('keypress', A.bind(instance._onKeyPressOption, instance), DOT + CSS_FIELD_OPTIONS_ITEM_INPUT);
		},

		add: function(option) {
			var instance = this;
			var options = instance.get(OPTIONS);

			options.push(option);

			instance.set(OPTIONS, options);
		},

		clear: function() {
			var instance = this;

			if (instance.get(ALLOW_CLEAR)) {
				instance.set(OPTIONS, []);
			}
		},

		remove: function(index) {
			var instance = this;
			var optionNode = instance._getOptionNode(index);

			if (optionNode) {
				optionNode.remove();
			}

			instance.items = instance.contentBox.all(DOT + CSS_FIELD_OPTIONS_ITEM);
		},

		_addNewOption: function() {
			var instance = this;

			var newOptionNode = instance._createOption(
				{
					name: instance.get(DEFAULT_NAME),
					value: instance.get(DEFAULT_VALUE)
				}
			);

			newOptionNode = A.Node.create(newOptionNode);

			instance.contentBox.append(newOptionNode);

			var newOptionNodeInput = newOptionNode.one(INPUT);

			newOptionNodeInput.focus();
			newOptionNodeInput.select();

			instance.items = instance.contentBox.all(DOT + CSS_FIELD_OPTIONS_ITEM);

			return newOptionNode;
		},

		_createOption: function(option) {
			var  instance = this;

			return A.substitute(TPL_OPTION, option);
		},

		_getOptionNode: function(index) {
			var instance = this;

			return instance.items.item(index);
		},

		_getOptions: function(val) {
			var instance = this;
			var options = [];

			if (instance.items) {
				A.each(instance.items, function(option) {
					var nameInput = option.one(DOT + CSS_FIELD_OPTIONS_ITEM_INPUT_NAME);
					var valueInput = option.one(DOT + CSS_FIELD_OPTIONS_ITEM_INPUT_VALUE);

					options.push(
						{
							name: nameInput.val(),
							value: valueInput.val()
						}
					);
				});
			}
			else {
				options = val;
			}

			return options;
		},

		_indexOfTarget: function(target) {
			var instance = this;
			var currentItem = target.ancestor(DOT + CSS_FIELD_OPTIONS_ITEM);

			return instance.items.indexOf(currentItem);
		},

		_onClickAdd: function(event) {
			var instance = this;

			instance._addNewOption();
		},

		_onClickOptionRemove: function(event) {
			var instance = this;
			var options = instance.get(OPTIONS);
			var index = instance._indexOfTarget(event.target);

			instance.remove(index);
		},

		_onKeyPressOption: function(event) {
			var instance = this;
			var options = instance.get(OPTIONS);
			var target = event.currentTarget;
			var keyCode = event.keyCode;
			var items = instance.items;

			if (keyCode == KEY_ENTER) {
				var index = instance._indexOfTarget(target);
				var isValue = target.hasClass(CSS_FIELD_OPTIONS_ITEM_INPUT_VALUE);

				if ((index == items.size() - 1) && isValue) {
					instance._addNewOption();
				}
			}
		},

		_uiSetOptions: function(val) {
			var instance = this;
			var buffer = [];
			var contentBox = instance.get(CONTENT_BOX);

			contentBox.empty();

			A.each(val, function(item) {
				contentBox.append(instance._createOption(item));
			});

			instance.items = contentBox.all(DOT + CSS_FIELD_OPTIONS_ITEM);
		}
	}
});

var FormBuilderMultipleChoiceField = A.Component.create({

	NAME: FORM_BUILDER_MULTIPLE_CHOICE_FIELD,

	ATTRS: {

		/**
		 * Wether the field accepts children or nothing
		 *
		 * @attribute acceptChildren
		 */
		acceptChildren: {
			value: false,
			readOnly: true
		},

		/**
		 * The options of the multiple choice field
		 *
		 * @attribute options
		 */
		options: {
			value:
			[
				{
					name: 'option 1',
					value: 'value 1'
				},
				{
					name: 'option 2',
					value: 'value 2'
				},
				{
					name: 'option 3',
					value: 'value 3'
				}
			]
		},

		/**
		 * The template for each option
		 *
		 * @attribute optionTemplate
		 */
		optionTemplate: {
			value: '<option value="{value}">{name}</option>'
		},

	},

	UI_ATTRS: [ACCEPT_CHILDREN, PREDEFINED_VALUE, LABEL, NAME, OPTIONS, SHOW_LABEL],

	CSS_PREFIX: CSS_FORM_BUILDER_FIELD,

	HTML_PARSER: {
		templateNode: DOT + CSS_FORM_BUILDER_FIELD_NODE
	},

	EXTENDS: A.FormBuilderField,

	prototype: {

		/**
		 * Initializer
		 *
		 * @method initializer
		 */
		initializer: function() {
			var instance = this;

			A.FormBuilderMultipleChoiceField.superclass.initializer.apply(instance, arguments);
		},

		/**
		 * Returns the A.Node of the field's HTML content
		 *
		 * @method getFieldNode
		 */
		getNode: function() {
			var instance = this;

			return A.FormBuilderMultipleChoiceField.superclass.getNode.apply(instance, arguments);
		},

		/**
		 * Renders the settings UI
		 *
		 * @method renderSettings
		 */
		renderSettings: function() {
			var instance = this;

			A.FormBuilderMultipleChoiceField.superclass.renderSettings.apply(instance, arguments);

			if (!instance._renderedMultipleChoiceSettings) {
				instance._renderedMultipleChoiceSettings = true;

				var optionsPanelBody = A.Node.create(TPL_DIV);

				instance.optionsPanel = new A.Panel(
					{
						bodyContent: optionsPanelBody,
						collapsible: true,
						title: 'Options'
					}
				).render();

				instance.options = new FieldOptions(
					{
						options: instance.get(OPTIONS)
					}
				).render(optionsPanelBody);

				instance.fieldSettingsNode.append(instance.optionsPanel.get(BOUNDING_BOX));
			}
		},

		/**
		 * Saves the settings info from the settings form to the settings
		 * attribute
		 *
		 * @method saveSettings
		 */
		saveSettings: function() {
			var instance = this;

			A.FormBuilderMultipleChoiceField.superclass.saveSettings.apply(instance, arguments);

			instance.set(OPTIONS, instance.options.get(OPTIONS));
		},

		_uiSetOptions: function(val) {
			var instance = this;
			var templateNode = instance.get(TEMPLATE_NODE);

			templateNode.empty();

			A.each(val, function(item) {
				templateNode.append(
					A.substitute(instance.get(OPTION_TEMPLATE), item)
				);
			});
		}

	}

});

A.FormBuilderMultipleChoiceField = FormBuilderMultipleChoiceField;

A.FormBuilder.types['multiple-choice'] = A.FormBuilderMultipleChoiceField;
<commit_msg>AUI-366 - FormBuilder<commit_after>var L = A.Lang,
	isArray = L.isArray,
	isNumber = L.isNumber,
	isString = L.isString,

	isNode = function(v) {
		return (v instanceof A.Node);
	},

	isNodeList = function(v) {
		return (v instanceof A.NodeList);
	},

	toInitialCap = A.cached(
		function(str) {
			return str.substring(0, 1).toUpperCase() + str.substring(1);
		}
	),

	ADD = 'add',
	ADD_NODE = 'addNode',
	BOUNDING_BOX = 'boundingBox',
	BUTTON = 'button',
	BUTTON_TYPE = 'buttonType',
	CONTENT_BOX = 'contentBox',
	CONTAINER = 'container',
	DEFAULT = 'default',
	DEFAULT_NAME = 'defaultName',
	DEFAULT_OPTIONS = 'defaultOptions',
	DEFAULT_VALUE = 'defaultValue',
	DOT = '.',
	DRAG = 'drag',
	DRAG_CONTAINER = 'dragContainer',
	DRAG_CONTAINER_NODE = 'dragContainerNode',
	DRAG_NODES_LIST = 'dragNodesList',
	DROP = 'drop',
	DROP_CONTAINER = 'dropContainer',
	DROP_CONTAINER_NODE = 'dropContainerNode',
	EMPTY_STR = '',
	FIELD = 'field',
	FIELDS = 'fields',
	FORM_BUILDER_FIELD = 'form-builder-field',
	FORM_BUILDER_MULTIPLE_CHOICE_FIELD = 'form-builder-multiple-choice-field',
	ICON = 'icon',
	ID = 'id',
	INPUT = 'input',
	ITEM = 'item',
	LABEL = 'label',
	MULTIPLE = 'multiple',
	NAME = 'name',
	NODE = 'node',
	OPTION = 'option',
	OPTION_TEMPLATE = 'optionTemplate',
	OPTIONS = 'options',
	PREDEFINED_VALUE = 'predefinedValue',
	PROXY = 'proxy',
	REMOVE = 'remove',
	RESET = 'reset',
	SUBMIT = 'submit',
	SPACE = ' ',
	TEMPLATE = 'template',
	TEMPLATE_NODE = 'templateNode',
	TEXT = 'text',
	TYPE = 'type',
	VALUE = 'value',

	getCN = A.ClassNameManager.getClassName,

	CSS_FIELD_INPUT = getCN(FIELD, INPUT),
	CSS_FIELD_INPUT_TEXT = getCN(FIELD, INPUT, TEXT),
	CSS_FIELD_OPTIONS_ADD = getCN(FIELD, OPTIONS, ADD),
	CSS_FIELD_OPTIONS_ITEM = getCN(FIELD, OPTIONS, ITEM),
	CSS_FIELD_OPTIONS_ITEM_INPUT = getCN(FIELD, OPTIONS, ITEM, INPUT),
	CSS_FIELD_OPTIONS_ITEM_INPUT_NAME = getCN(FIELD, OPTIONS, ITEM, INPUT, NAME),
	CSS_FIELD_OPTIONS_ITEM_INPUT_VALUE = getCN(FIELD, OPTIONS, ITEM, INPUT, VALUE),
	CSS_FIELD_OPTIONS_ITEM_REMOVE = getCN(FIELD, OPTIONS, ITEM, REMOVE),

	CSS_FORM_BUILDER_FIELD = getCN(FORM_BUILDER_FIELD),
	CSS_FORM_BUILDER_FIELD_NODE = getCN(FORM_BUILDER_FIELD, NODE),
	CSS_FORM_BUILDER_INPUT_FIELD_NODE = getCN(FORM_BUILDER_INPUT_FIELD, NODE),

	CSS_STATE_DEFAULT = getCN(STATE, DEFAULT),

	TPL_OPTION = '
' +
					'<input type="text" name="name" class="' + [CSS_FIELD_OPTIONS_ITEM_INPUT, CSS_FIELD_OPTIONS_ITEM_INPUT_NAME, CSS_FIELD_INPUT, CSS_FIELD_INPUT_TEXT].join(SPACE) + '" value="{name}" />' +
					'<input type="text" name="value" class="' + [CSS_FIELD_OPTIONS_ITEM_INPUT, CSS_FIELD_OPTIONS_ITEM_INPUT_VALUE, CSS_FIELD_INPUT, CSS_FIELD_INPUT_TEXT].join(SPACE) + '" value="{value}" />' +
					' ' +
				 '
';

	TPL_ADD = 'Add an option',

	ENTER = 'ENTER';

var FieldOptions = A.Component.create({

	NAME: OPTIONS,

	ATTRS: {

		allowClear: {
			value: false
		},

		defaultName: {
			value: EMPTY_STR
		},

		defaultValue: {
			value: EMPTY_STR
		},

		options: {
			value: [],
			getter: '_getOptions',
			validator: isArray
		},

		addNode: {
			valueFn: function() {
				return A.Node.create(TPL_ADD);
			}
		}

	},

	HTML_PARSER: {
		addNode: DOT + CSS_FIELD_OPTIONS_ADD
	},

	UI_ATTRS: [OPTIONS],

	EXTENDS: A.Widget,

	prototype: {

		initializer: function() {
			var instance = this;

			instance.boundingBox = instance.get(BOUNDING_BOX);
			instance.contentBox = instance.get(CONTENT_BOX);
		},

		renderUI: function() {
			var instance = this;
			var boundingBox = instance.boundingBox;
			var addNode = instance.get(ADD_NODE);

			if (!addNode.inDoc()) {
				boundingBox.append(addNode);
			}
		},

		bindUI: function() {
			var instance = this;
			var boundingBox = instance.boundingBox;
			var addNode = instance.get(ADD_NODE);

			addNode.on('click', A.bind(instance._onClickAdd, instance));

			boundingBox.delegate('click', A.bind(instance._onClickOptionRemove, instance), DOT + CSS_FIELD_OPTIONS_ITEM_REMOVE);
			boundingBox.delegate('keypress', A.bind(instance._onKeyPressOption, instance), DOT + CSS_FIELD_OPTIONS_ITEM_INPUT);
		},

		add: function(option) {
			var instance = this;
			var options = instance.get(OPTIONS);

			options.push(option);

			instance.set(OPTIONS, options);
		},

		clear: function() {
			var instance = this;

			if (instance.get(ALLOW_CLEAR)) {
				instance.set(OPTIONS, []);
			}
		},

		remove: function(index) {
			var instance = this;
			var optionNode = instance._getOptionNode(index);

			if (optionNode) {
				optionNode.remove();
			}

			instance.items = instance.contentBox.all(DOT + CSS_FIELD_OPTIONS_ITEM);
		},

		_addNewOption: function() {
			var instance = this;

			var newOptionNode = instance._createOption(
				{
					name: instance.get(DEFAULT_NAME),
					value: instance.get(DEFAULT_VALUE)
				}
			);

			newOptionNode = A.Node.create(newOptionNode);

			instance.contentBox.append(newOptionNode);

			var newOptionNodeInput = newOptionNode.one(INPUT);

			newOptionNodeInput.focus();
			newOptionNodeInput.select();

			instance.items = instance.contentBox.all(DOT + CSS_FIELD_OPTIONS_ITEM);

			return newOptionNode;
		},

		_createOption: function(option) {
			var  instance = this;

			return A.substitute(TPL_OPTION, option);
		},

		_getOptionNode: function(index) {
			var instance = this;

			return instance.items.item(index);
		},

		_getOptions: function(val) {
			var instance = this;
			var options = [];

			if (instance.items) {
				A.each(instance.items, function(option) {
					var nameInput = option.one(DOT + CSS_FIELD_OPTIONS_ITEM_INPUT_NAME);
					var valueInput = option.one(DOT + CSS_FIELD_OPTIONS_ITEM_INPUT_VALUE);

					options.push(
						{
							name: nameInput.val(),
							value: valueInput.val()
						}
					);
				});
			}
			else {
				options = val;
			}

			return options;
		},

		_indexOfTarget: function(target) {
			var instance = this;
			var currentItem = target.ancestor(DOT + CSS_FIELD_OPTIONS_ITEM);

			return instance.items.indexOf(currentItem);
		},

		_onClickAdd: function(event) {
			var instance = this;

			instance._addNewOption();
		},

		_onClickOptionRemove: function(event) {
			var instance = this;
			var options = instance.get(OPTIONS);
			var index = instance._indexOfTarget(event.target);

			instance.remove(index);
		},

		_onKeyPressOption: function(event) {
			var instance = this;
			var options = instance.get(OPTIONS);
			var target = event.currentTarget;
			var items = instance.items;

			if (event.isKey(ENTER)) {
				var index = instance._indexOfTarget(target);
				var isValue = target.hasClass(CSS_FIELD_OPTIONS_ITEM_INPUT_VALUE);

				if ((index == items.size() - 1) && isValue) {
					instance._addNewOption();
				}
			}
		},

		_uiSetOptions: function(val) {
			var instance = this;
			var buffer = [];
			var contentBox = instance.get(CONTENT_BOX);

			contentBox.empty();

			A.each(val, function(item) {
				contentBox.append(instance._createOption(item));
			});

			instance.items = contentBox.all(DOT + CSS_FIELD_OPTIONS_ITEM);
		}
	}
});

var FormBuilderMultipleChoiceField = A.Component.create({

	NAME: FORM_BUILDER_MULTIPLE_CHOICE_FIELD,

	ATTRS: {

		/**
		 * Wether the field accepts children or nothing
		 *
		 * @attribute acceptChildren
		 */
		acceptChildren: {
			value: false,
			readOnly: true
		},

		/**
		 * The options of the multiple choice field
		 *
		 * @attribute options
		 */
		options: {
			value:
			[
				{
					name: 'option 1',
					value: 'value 1'
				},
				{
					name: 'option 2',
					value: 'value 2'
				},
				{
					name: 'option 3',
					value: 'value 3'
				}
			]
		},

		/**
		 * The template for each option
		 *
		 * @attribute optionTemplate
		 */
		optionTemplate: {
			value: '<option value="{value}">{name}</option>'
		},

	},

	UI_ATTRS: [ACCEPT_CHILDREN, PREDEFINED_VALUE, LABEL, NAME, OPTIONS, SHOW_LABEL],

	CSS_PREFIX: CSS_FORM_BUILDER_FIELD,

	HTML_PARSER: {
		templateNode: DOT + CSS_FORM_BUILDER_FIELD_NODE
	},

	EXTENDS: A.FormBuilderField,

	prototype: {

		/**
		 * Initializer
		 *
		 * @method initializer
		 */
		initializer: function() {
			var instance = this;

			A.FormBuilderMultipleChoiceField.superclass.initializer.apply(instance, arguments);
		},

		/**
		 * Returns the A.Node of the field's HTML content
		 *
		 * @method getFieldNode
		 */
		getNode: function() {
			var instance = this;

			return A.FormBuilderMultipleChoiceField.superclass.getNode.apply(instance, arguments);
		},

		/**
		 * Renders the settings UI
		 *
		 * @method renderSettings
		 */
		renderSettings: function() {
			var instance = this;

			A.FormBuilderMultipleChoiceField.superclass.renderSettings.apply(instance, arguments);

			if (!instance._renderedMultipleChoiceSettings) {
				instance._renderedMultipleChoiceSettings = true;

				var optionsPanelBody = A.Node.create(TPL_DIV);

				instance.optionsPanel = new A.Panel(
					{
						bodyContent: optionsPanelBody,
						collapsible: true,
						title: 'Options'
					}
				).render();

				instance.options = new FieldOptions(
					{
						options: instance.get(OPTIONS)
					}
				).render(optionsPanelBody);

				instance.fieldSettingsNode.append(instance.optionsPanel.get(BOUNDING_BOX));
			}
		},

		/**
		 * Saves the settings info from the settings form to the settings
		 * attribute
		 *
		 * @method saveSettings
		 */
		saveSettings: function() {
			var instance = this;

			A.FormBuilderMultipleChoiceField.superclass.saveSettings.apply(instance, arguments);

			instance.set(OPTIONS, instance.options.get(OPTIONS));
		},

		_uiSetOptions: function(val) {
			var instance = this;
			var templateNode = instance.get(TEMPLATE_NODE);

			templateNode.empty();

			A.each(val, function(item) {
				templateNode.append(
					A.substitute(instance.get(OPTION_TEMPLATE), item)
				);
			});
		}

	}

});

A.FormBuilderMultipleChoiceField = FormBuilderMultipleChoiceField;

A.FormBuilder.types['multiple-choice'] = A.FormBuilderMultipleChoiceField;
<|endoftext|>


<commit_before>'use strict';

function globalModule_Try(moduleString) {
	try {
		return require(moduleString);
	} catch (exception) {
		console.log("FAILED TO LOAD: \"" + moduleString + "\"");
		console.log(exception);
		return null;
	}
}

function dump_debug_string(string) {
	var fileSystem_Module = globalModule_Try('fs');
	var inHouseFileHandle = fileSystem_Module.openSync("./local_debug_dump.txt", 'a');
	fileSystem_Module.writeSync(inHouseFileHandle, string);
	fileSystem_Module.closeSync(inHouseFileHandle);
}

// var endMarker = " MIN_END\n";
// dump_debug_string("1: " + regExp_ResultArray[1] + ".min" +
// regExp_ResultArray[2] + carriageReturn + endMarker);
// dump_debug_string("2 no_cr: " + regExp_ResultArray[1] + endMarker);
// dump_debug_string("3 no_cr: " + regExp_ResultArray[1] + ".min" + endMarker);
// dump_debug_string("4 no_cr: " + regExp_ResultArray[1] + ".min" +
// regExp_ResultArray[2] + endMarker);
// dump_debug_string("5: " + regExp_ResultArray[1] + ".min" +
// regExp_ResultArray[2] + carriageReturn + endMarker);
// dump_debug_string("TARGET no_cr: " + regExp_ResultArray[2] + endMarker);
//
// var endMarker = " REGULAR_END\n";
// dump_debug_string("1: " + regExp_ResultArray[1] + regExp_ResultArray[2] +
// carriageReturn + endMarker);
// dump_debug_string("2 no_cr: " + regExp_ResultArray[1] + endMarker);
// dump_debug_string("3 no_cr: " + regExp_ResultArray[1] + regExp_ResultArray[2]
// + endMarker);
// dump_debug_string("4: " + regExp_ResultArray[1] + regExp_ResultArray[2] +
// carriageReturn + endMarker);
// dump_debug_string("TARGET no_cr: " + regExp_ResultArray[2] + endMarker);

function message_locator_service(mainMessage) {
	var path_Module = globalModule_Try('path');
	var stackTrace_Module = globalModule_Try('stack-trace');
	var currentFrame = stackTrace_Module.get()[1];
	console.log(mainMessage + " >>> \"" + path_Module.basename(currentFrame.getFileName()) + ":" +
	    currentFrame.getLineNumber() + "\"\n");
}

function spot_the_head(htmlLineArray) {
	var headAreaMark_Array = [ -1, -1 ];
	var headMark_RegExp = new RegExp("<\\s*\\/?\\s*head\\s*>", "i");
	for (var i = 0; i < htmlLineArray.length; i++) {
		if (headMark_RegExp.exec(htmlLineArray[i]) !== null) {
			if (headAreaMark_Array[0] === -1) {
				headAreaMark_Array[0] = i;
			} else {
				headAreaMark_Array[1] = i;
				break;
			}
		}
	}
	if (headAreaMark_Array[0] === -1 || headAreaMark_Array[1] === -1) {
		message_locator_service("HEAD AREA BOUNDRIES BUGGY OR NOT FOUND AT ALL...!");
		return false;
	} else {
		return headAreaMark_Array;
	}
}

function carriage_return_needed() {
	var os_Module = globalModule_Try('os');
	var windowsSpotter_RegExp = new RegExp("windows", "i");
	if (windowsSpotter_RegExp.exec(os_Module.type()) !== null) {
		return true;
	} else {
		return false;
	}
}

function end_of_line_clean_save(fileName, array, carriageReturn) {
	var carriageReturnString = "";
	if (carriageReturn) {
		carriageReturnString = "\r";
	}
	var fileSystem_Module = globalModule_Try('fs');
	var currentFileHandle = fileSystem_Module.openSync(fileName, 'w');

	var lineSpotter_RegExp = new RegExp("^([\\x20\\x09]*)(.*)\\x0d*$", "i");
	var initialLineResultArray = lineSpotter_RegExp.exec(array[0]);
	if (initialLineResultArray !== null) {
		if (initialLineResultArray[2]) {
			fileSystem_Module.writeSync(currentFileHandle, initialLineResultArray[1] + initialLineResultArray[2] +
			    carriageReturnString + "\n");
		}
	} else {
		message_locator_service("MISSED THE INITIAL LINE...!");
		return false;
	}
	for (var j = 1; j < (array.length - 1); j++) {
		var lineResultArray = lineSpotter_RegExp.exec(array[j]);
		if (lineResultArray !== null) {
			if (j === (array.length - 2)) {
				var nextToLast_ResultArray = lineSpotter_RegExp.exec(array[array.length - 1]);
				if (!nextToLast_ResultArray[2]) {
					fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2]);
				} else {
					fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2] + carriageReturnString +
					    "\n");
				}
			} else {
				fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2] + carriageReturnString +
				    "\n");
			}
		} else {
			message_locator_service("MISSED A LINE...!");
			return false;
		}
	}
	var finalLineResultArray = lineSpotter_RegExp.exec(array[array.length - 1]);
	if (finalLineResultArray !== null) {
		if (finalLineResultArray[2]) {
			fileSystem_Module.writeSync(currentFileHandle, finalLineResultArray[1] + finalLineResultArray[2]);
		}
	} else {
		message_locator_service("MISSED THE FINAL LINE...!");
		return false;
	}
	fileSystem_Module.closeSync(currentFileHandle);
	return true;
}

function array_from_file_delete(entire_fileName) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(entire_fileName)) {
		var targetFile_LineArray = fileSystem_Module.readFileSync(entire_fileName, 'utf8', 'r').toString().split('\n');
		fileSystem_Module.unlinkSync(entire_fileName);
		return targetFile_LineArray;
	} else {
		message_locator_service("TARGET FILE DOES NOT EXIST...!");
		return false;
	}
}

function array_from_file(entire_fileName) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(entire_fileName)) {
		var targetFile_LineArray = fileSystem_Module.readFileSync(entire_fileName, 'utf8', 'r').toString().split('\n');
		return targetFile_LineArray;
	} else {
		message_locator_service("TARGET FILE DOES NOT EXIST...!");
		return false;
	}
}

// Switching html head area to minified targets...
function toMin(headStart, headEnd, carriageReturn, contentArray) {
	var changed = false;
	var hasMin_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)(?:\\.min)+(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	var carelessAboutMin_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	for (var i = (headStart + 1); i < headEnd; i++) {
		if (hasMin_RegExp.exec(contentArray[i]) === null) {
			var regExp_ResultArray = carelessAboutMin_RegExp.exec(contentArray[i]);
			if (regExp_ResultArray !== null) {
				contentArray[i] = regExp_ResultArray[1] + ".min" + regExp_ResultArray[2] + carriageReturn;
				if (!changed) {
					changed = true;
				}
			}
		}
	}
	if (changed) {
		return contentArray;
	} else {
		return false;
	}
}

// Switching html head area to regular targets...
function toRegular(headStart, headEnd, carriageReturn, contentArray) {
	var changed = false;
	var minSuspect_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)\\.min(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	for (var i = (headStart + 1); i < headEnd; i++) {
		var regExp_ResultArray = minSuspect_RegExp.exec(contentArray[i]);
		if (regExp_ResultArray !== null) {
			contentArray[i] = regExp_ResultArray[1] + regExp_ResultArray[2] + carriageReturn;
			if (!changed) {
				changed = true;
			}
		}
	}
	if (changed) {
		return contentArray;
	} else {
		return false;
	}
}

function delete_writingArray_ToFile(fileName, array) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(fileName)) {
		fileSystem_Module.unlinkSync(fileName);
	}
	var inHouseFileHandle = fileSystem_Module.openSync(fileName, 'w');
	for (var i = 0; i < (array.length - 1); i++) {
		fileSystem_Module.writeSync(inHouseFileHandle, array[i] + "\n");
	}
	if (array[array.length - 1]) {
		fileSystem_Module.writeSync(inHouseFileHandle, array[array.length - 1]);
	}
	fileSystem_Module.closeSync(inHouseFileHandle);
}

module.exports = {
  process_wildcard_input : function(direction, source, directory) {
	  var wildcard_extractor_RegExp = new RegExp("^\\*(.+)$");
	  var result_array = wildcard_extractor_RegExp.exec(source);
	  if (result_array) {
		  var tail_string = result_array[1];
		  var prepared_tail = tail_string.replace(/\./ig, "\\.");
		  var wildcard_RegExp = new RegExp("^(.+" + prepared_tail + ")$", "i");
		  var fileSystem_Module = globalModule_Try('fs');
		  var raw_file_array = fileSystem_Module.readdirSync(directory);
		  var targets_file_array = [];
		  var counter = 1;
		  for (var i = 0; i < raw_file_array.length; i++) {
			  var single_file_result_array = wildcard_RegExp.exec(raw_file_array[i]);
			  if (single_file_result_array) {
				  console.log(counter + ": " + single_file_result_array[1]);
				  counter++;
			  }
		  }
	  } else {
		  message_locator_service("NO VALID WILDCARD FOUND...!");
	  }
	  console.log("\n");
  },

  toggle_all_head_links : function(direction, file) {
	  var pointToMin = false;
	  if (direction === 'min') {
		  pointToMin = true;
	  }
	  var targetFile_LineArray = array_from_file(file);
	  if (targetFile_LineArray) {
		  var windowsNeeded_carriageReturn = "";
		  if (carriage_return_needed) {
			  windowsNeeded_carriageReturn = "\r";
		  }
		  var headStart = spot_the_head(targetFile_LineArray)[0];
		  var headEnd = spot_the_head(targetFile_LineArray)[1];

		  // Actual array manipulation...
		  if (pointToMin) {
			  targetFile_LineArray = toMin(headStart, headEnd, windowsNeeded_carriageReturn, targetFile_LineArray);
			  if (targetFile_LineArray) {
				  delete_writingArray_ToFile(file, targetFile_LineArray);
				  return true;
			  } else {
				  return true;
			  }
		  } else {
			  targetFile_LineArray = toRegular(headStart, headEnd, windowsNeeded_carriageReturn, targetFile_LineArray);
			  if (targetFile_LineArray) {
				  delete_writingArray_ToFile(file, targetFile_LineArray);
				  return true;
			  } else {
				  return true;
			  }
		  }
	  } else {
		  message_locator_service("FAILED TO GET VALID DATA ARRAY...!");
		  return false;
	  }
  },

  end_of_line_refresh : function(file) {
	  console.log("CURRENTLY REFRESHING FILE: \"" + file + "\"");
	  var targetFile_LineArray = array_from_file_delete(file);
	  if (targetFile_LineArray) {
		  return end_of_line_clean_save(file, targetFile_LineArray, carriage_return_needed());
	  } else {
		  message_locator_service("FAILED TO GET VALID DATA ARRAY...!");
		  return false;
	  }
  }
};
<commit_msg>Getting a valid array... - MH - PT<commit_after>'use strict';

function globalModule_Try(moduleString) {
	try {
		return require(moduleString);
	} catch (exception) {
		console.log("FAILED TO LOAD: \"" + moduleString + "\"");
		console.log(exception);
		return null;
	}
}

function dump_debug_string(string) {
	var fileSystem_Module = globalModule_Try('fs');
	var inHouseFileHandle = fileSystem_Module.openSync("./local_debug_dump.txt", 'a');
	fileSystem_Module.writeSync(inHouseFileHandle, string);
	fileSystem_Module.closeSync(inHouseFileHandle);
}

// var endMarker = " MIN_END\n";
// dump_debug_string("1: " + regExp_ResultArray[1] + ".min" +
// regExp_ResultArray[2] + carriageReturn + endMarker);
// dump_debug_string("2 no_cr: " + regExp_ResultArray[1] + endMarker);
// dump_debug_string("3 no_cr: " + regExp_ResultArray[1] + ".min" + endMarker);
// dump_debug_string("4 no_cr: " + regExp_ResultArray[1] + ".min" +
// regExp_ResultArray[2] + endMarker);
// dump_debug_string("5: " + regExp_ResultArray[1] + ".min" +
// regExp_ResultArray[2] + carriageReturn + endMarker);
// dump_debug_string("TARGET no_cr: " + regExp_ResultArray[2] + endMarker);
//
// var endMarker = " REGULAR_END\n";
// dump_debug_string("1: " + regExp_ResultArray[1] + regExp_ResultArray[2] +
// carriageReturn + endMarker);
// dump_debug_string("2 no_cr: " + regExp_ResultArray[1] + endMarker);
// dump_debug_string("3 no_cr: " + regExp_ResultArray[1] + regExp_ResultArray[2]
// + endMarker);
// dump_debug_string("4: " + regExp_ResultArray[1] + regExp_ResultArray[2] +
// carriageReturn + endMarker);
// dump_debug_string("TARGET no_cr: " + regExp_ResultArray[2] + endMarker);

function message_locator_service(mainMessage) {
	var path_Module = globalModule_Try('path');
	var stackTrace_Module = globalModule_Try('stack-trace');
	var currentFrame = stackTrace_Module.get()[1];
	console.log(mainMessage + " >>> \"" + path_Module.basename(currentFrame.getFileName()) + ":" +
	    currentFrame.getLineNumber() + "\"\n");
}

function spot_the_head(htmlLineArray) {
	var headAreaMark_Array = [ -1, -1 ];
	var headMark_RegExp = new RegExp("<\\s*\\/?\\s*head\\s*>", "i");
	for (var i = 0; i < htmlLineArray.length; i++) {
		if (headMark_RegExp.exec(htmlLineArray[i]) !== null) {
			if (headAreaMark_Array[0] === -1) {
				headAreaMark_Array[0] = i;
			} else {
				headAreaMark_Array[1] = i;
				break;
			}
		}
	}
	if (headAreaMark_Array[0] === -1 || headAreaMark_Array[1] === -1) {
		message_locator_service("HEAD AREA BOUNDRIES BUGGY OR NOT FOUND AT ALL...!");
		return false;
	} else {
		return headAreaMark_Array;
	}
}

function carriage_return_needed() {
	var os_Module = globalModule_Try('os');
	var windowsSpotter_RegExp = new RegExp("windows", "i");
	if (windowsSpotter_RegExp.exec(os_Module.type()) !== null) {
		return true;
	} else {
		return false;
	}
}

function end_of_line_clean_save(fileName, array, carriageReturn) {
	var carriageReturnString = "";
	if (carriageReturn) {
		carriageReturnString = "\r";
	}
	var fileSystem_Module = globalModule_Try('fs');
	var currentFileHandle = fileSystem_Module.openSync(fileName, 'w');

	var lineSpotter_RegExp = new RegExp("^([\\x20\\x09]*)(.*)\\x0d*$", "i");
	var initialLineResultArray = lineSpotter_RegExp.exec(array[0]);
	if (initialLineResultArray !== null) {
		if (initialLineResultArray[2]) {
			fileSystem_Module.writeSync(currentFileHandle, initialLineResultArray[1] + initialLineResultArray[2] +
			    carriageReturnString + "\n");
		}
	} else {
		message_locator_service("MISSED THE INITIAL LINE...!");
		return false;
	}
	for (var j = 1; j < (array.length - 1); j++) {
		var lineResultArray = lineSpotter_RegExp.exec(array[j]);
		if (lineResultArray !== null) {
			if (j === (array.length - 2)) {
				var nextToLast_ResultArray = lineSpotter_RegExp.exec(array[array.length - 1]);
				if (!nextToLast_ResultArray[2]) {
					fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2]);
				} else {
					fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2] + carriageReturnString +
					    "\n");
				}
			} else {
				fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2] + carriageReturnString +
				    "\n");
			}
		} else {
			message_locator_service("MISSED A LINE...!");
			return false;
		}
	}
	var finalLineResultArray = lineSpotter_RegExp.exec(array[array.length - 1]);
	if (finalLineResultArray !== null) {
		if (finalLineResultArray[2]) {
			fileSystem_Module.writeSync(currentFileHandle, finalLineResultArray[1] + finalLineResultArray[2]);
		}
	} else {
		message_locator_service("MISSED THE FINAL LINE...!");
		return false;
	}
	fileSystem_Module.closeSync(currentFileHandle);
	return true;
}

function array_from_file_delete(entire_fileName) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(entire_fileName)) {
		var targetFile_LineArray = fileSystem_Module.readFileSync(entire_fileName, 'utf8', 'r').toString().split('\n');
		fileSystem_Module.unlinkSync(entire_fileName);
		return targetFile_LineArray;
	} else {
		message_locator_service("TARGET FILE DOES NOT EXIST...!");
		return false;
	}
}

function array_from_file(entire_fileName) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(entire_fileName)) {
		var targetFile_LineArray = fileSystem_Module.readFileSync(entire_fileName, 'utf8', 'r').toString().split('\n');
		return targetFile_LineArray;
	} else {
		message_locator_service("TARGET FILE DOES NOT EXIST...!");
		return false;
	}
}

// Switching html head area to minified targets...
function toMin(headStart, headEnd, carriageReturn, contentArray) {
	var changed = false;
	var hasMin_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)(?:\\.min)+(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	var carelessAboutMin_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	for (var i = (headStart + 1); i < headEnd; i++) {
		if (hasMin_RegExp.exec(contentArray[i]) === null) {
			var regExp_ResultArray = carelessAboutMin_RegExp.exec(contentArray[i]);
			if (regExp_ResultArray !== null) {
				contentArray[i] = regExp_ResultArray[1] + ".min" + regExp_ResultArray[2] + carriageReturn;
				if (!changed) {
					changed = true;
				}
			}
		}
	}
	if (changed) {
		return contentArray;
	} else {
		return false;
	}
}

// Switching html head area to regular targets...
function toRegular(headStart, headEnd, carriageReturn, contentArray) {
	var changed = false;
	var minSuspect_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)\\.min(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	for (var i = (headStart + 1); i < headEnd; i++) {
		var regExp_ResultArray = minSuspect_RegExp.exec(contentArray[i]);
		if (regExp_ResultArray !== null) {
			contentArray[i] = regExp_ResultArray[1] + regExp_ResultArray[2] + carriageReturn;
			if (!changed) {
				changed = true;
			}
		}
	}
	if (changed) {
		return contentArray;
	} else {
		return false;
	}
}

function delete_writingArray_ToFile(fileName, array) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(fileName)) {
		fileSystem_Module.unlinkSync(fileName);
	}
	var inHouseFileHandle = fileSystem_Module.openSync(fileName, 'w');
	for (var i = 0; i < (array.length - 1); i++) {
		fileSystem_Module.writeSync(inHouseFileHandle, array[i] + "\n");
	}
	if (array[array.length - 1]) {
		fileSystem_Module.writeSync(inHouseFileHandle, array[array.length - 1]);
	}
	fileSystem_Module.closeSync(inHouseFileHandle);
}

module.exports = {
  process_wildcard_input : function(direction, source, directory) {
	  var wildcard_extractor_RegExp = new RegExp("^\\*(.+)$");
	  var result_array = wildcard_extractor_RegExp.exec(source);
	  var final_files_array = [];
	  if (result_array) {
		  var tail_string = result_array[1];
		  var prepared_tail = tail_string.replace(/\./ig, "\\.");
		  var wildcard_RegExp = new RegExp("^(.+" + prepared_tail + ")$", "i");
		  var fileSystem_Module = globalModule_Try('fs');
		  var raw_file_array = fileSystem_Module.readdirSync(directory);
		  var targets_file_array = [];
		  var counter = 1;
		  for (var i = 0; i < raw_file_array.length; i++) {
			  var single_file_result_array = wildcard_RegExp.exec(raw_file_array[i]);
			  if (single_file_result_array) {
				  console.log(counter + ": " + single_file_result_array[1]);
				  final_files_array.push(directory + single_file_result_array[1]);
				  counter++;
			  }
		  }
		  for (var j = 0; j < final_files_array.length; j++) {
			  console.log(final_files_array[j]);
		  }
	  } else {
		  message_locator_service("NO VALID WILDCARD FOUND...!");
	  }
	  console.log("\n");
  },

  toggle_all_head_links : function(direction, file) {
	  var pointToMin = false;
	  if (direction === 'min') {
		  pointToMin = true;
	  }
	  var targetFile_LineArray = array_from_file(file);
	  if (targetFile_LineArray) {
		  var windowsNeeded_carriageReturn = "";
		  if (carriage_return_needed) {
			  windowsNeeded_carriageReturn = "\r";
		  }
		  var headStart = spot_the_head(targetFile_LineArray)[0];
		  var headEnd = spot_the_head(targetFile_LineArray)[1];

		  // Actual array manipulation...
		  if (pointToMin) {
			  targetFile_LineArray = toMin(headStart, headEnd, windowsNeeded_carriageReturn, targetFile_LineArray);
			  if (targetFile_LineArray) {
				  delete_writingArray_ToFile(file, targetFile_LineArray);
				  return true;
			  } else {
				  return true;
			  }
		  } else {
			  targetFile_LineArray = toRegular(headStart, headEnd, windowsNeeded_carriageReturn, targetFile_LineArray);
			  if (targetFile_LineArray) {
				  delete_writingArray_ToFile(file, targetFile_LineArray);
				  return true;
			  } else {
				  return true;
			  }
		  }
	  } else {
		  message_locator_service("FAILED TO GET VALID DATA ARRAY...!");
		  return false;
	  }
  },

  end_of_line_refresh : function(file) {
	  console.log("CURRENTLY REFRESHING FILE: \"" + file + "\"");
	  var targetFile_LineArray = array_from_file_delete(file);
	  if (targetFile_LineArray) {
		  return end_of_line_clean_save(file, targetFile_LineArray, carriage_return_needed());
	  } else {
		  message_locator_service("FAILED TO GET VALID DATA ARRAY...!");
		  return false;
	  }
  }
};
<|endoftext|>


<commit_before>/**
 * Copyright 2014 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

var path = require("path");
var when = require("when");

var settings = module.exports = {
    uiPort: process.env.PORT || 1880,
    mqttReconnectTime: 15000,
    serialReconnectTime: 15000,
    debugMaxLength: 10000000,

    // Add the nodes in
    nodesDir: path.join(__dirname,"nodes"),

    // Blacklist the non-bluemix friendly nodes
    nodesExcludes:[ '66-mongodb.js','75-exec.js','35-arduino.js','36-rpi-gpio.js','25-serial.js','28-tail.js','50-file.js','31-tcpin.js','32-udp.js','23-watch.js' ],

    // Enable module reinstalls on start-up; this ensures modules installed
    // post-deploy are restored after a restage
    autoInstallModules: true,

    // Move the admin UI
    httpAdminRoot: '/red',

    // You can protect the user interface with a userid and password by using the following property
    // the password must be an md5 hash  eg.. 5f4dcc3b5aa765d61d8327deb882cf99 ('password')
    //httpAdminAuth: {user:"user",pass:"5f4dcc3b5aa765d61d8327deb882cf99"},

    // Serve up the welcome page
    httpStatic: path.join(__dirname,"public"),

    functionGlobalContext: { },

    storageModule: require("./mongostorage"),

    httpNodeCors: {
        origin: "*",
        methods: "GET,PUT,POST,DELETE"
    },

    // Disbled Credential Secret
    credentialSecret: false
}

if (process.env.NODE_RED_USERNAME && process.env.NODE_RED_PASSWORD) {
    settings.adminAuth = {
        type: "credentials",
        users: function(username) {
            if (process.env.NODE_RED_USERNAME == username) {
                return when.resolve({username:username,permissions:"*"});
            } else {
                return when.resolve(null);
            }
        },
        authenticate: function(username, password) {
            if (process.env.NODE_RED_USERNAME == username &&
                process.env.NODE_RED_PASSWORD == password) {
                return when.resolve({username:username,permissions:"*"});
            } else {
                return when.resolve(null);
            }
        }
    }
}

settings.mongoAppname = 'nodered';
settings.mongoUrl = process.env.MONGODB_URI;
<commit_msg>set security<commit_after>/**
 * Copyright 2014 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

var path = require("path");
var when = require("when");

var settings = module.exports = {
    uiPort: process.env.PORT || 1880,
    mqttReconnectTime: 15000,
    serialReconnectTime: 15000,
    debugMaxLength: 10000000,

    // Add the nodes in
    nodesDir: path.join(__dirname,"nodes"),

    // Blacklist the non-bluemix friendly nodes
    nodesExcludes:[ '66-mongodb.js','75-exec.js','35-arduino.js','36-rpi-gpio.js','25-serial.js','28-tail.js','50-file.js','31-tcpin.js','32-udp.js','23-watch.js' ],

    // Enable module reinstalls on start-up; this ensures modules installed
    // post-deploy are restored after a restage
    autoInstallModules: true,

    // Move the admin UI
    httpAdminRoot: '/red',

    // You can protect the user interface with a userid and password by using the following property
    // the password must be an md5 hash  eg.. 5f4dcc3b5aa765d61d8327deb882cf99 ('password')
    httpAdminAuth: {user:"iotmakassar",pass:"$2a$08$bZ6cSb3xbbjE2vaSPIBMvuBgKVRSi7rOluDZ/fv2hDqVkOSFJUzbK"},

    // Serve up the welcome page
    httpStatic: path.join(__dirname,"public"),

    functionGlobalContext: { },

    storageModule: require("./mongostorage"),

    httpNodeCors: {
        origin: "*",
        methods: "GET,PUT,POST,DELETE"
    },

    // Disbled Credential Secret
    credentialSecret: false
}

if (process.env.NODE_RED_USERNAME && process.env.NODE_RED_PASSWORD) {
    settings.adminAuth = {
        type: "credentials",
        users: function(username) {
            if (process.env.NODE_RED_USERNAME == username) {
                return when.resolve({username:username,permissions:"*"});
            } else {
                return when.resolve(null);
            }
        },
        authenticate: function(username, password) {
            if (process.env.NODE_RED_USERNAME == username &&
                process.env.NODE_RED_PASSWORD == password) {
                return when.resolve({username:username,permissions:"*"});
            } else {
                return when.resolve(null);
            }
        }
    }
}

settings.mongoAppname = 'nodered';
settings.mongoUrl = process.env.MONGODB_URI;
<|endoftext|>


<commit_before>define(function (require) {
    var system = require('durandal/system');
    var routes = {}, autoNavPath, sammy;

    //NOTE: Sammy.js is not required by the core of Durandal.
    //However, this plugin leverages it to enable navigation.

    function construct(ctor, args) {
        function F() {
            return ctor.apply(this, args);
        }
        F.prototype = ctor.prototype;
        return new F();
    }

    return {
        navigationReady:ko.observable(false),
        navigation: ko.observableArray([]),
        navigateBack:function () {
            window.history.back();
        },
        navigateTo:function (url) {
            sammy.setLocation(url);
        },
        mapAuto: function (path) {
            autoNavPath = path;
        },
        mapNav: function (url, moduleId, name) {
            this.mapRoute(url, moduleId, name, true);
        },
        mapRoute: function (url, moduleId, name, isNav) {
            var that = this;
            var routeInfo = {
                url: url,
                moduleId: moduleId,
                name: name || (url.substring(0, 1).toUpperCase() + url.substring(1))
            };

            routes[url] = routeInfo;

            if (isNav) {
                routeInfo.isActive = ko.computed(function() {
                    return that.navigationReady() && that.activator() && that.activator().__moduleId__ == routeInfo.moduleId;
                });

                this.navigation.push(routeInfo);
            }
        },
        enable: function (activator, defaultRoute) {
            var cancelling = false, previousRoute;

            this.activator = activator;

            function trySwap(item, title) {
                activator.activateItem(item).then(function (succeeded) {
                    if (succeeded) {
                        document.title = title;
                        previousRoute = sammy.last_location[1].replace('/', '');
                    } else {
                        cancelling = true;
                        sammy.setLocation(previousRoute);
                        cancelling = false;
                    }
                });
            }

            function activateRoute(route) {
                var parts = route.split('/');
                var lookup = parts[0];
                var params = parts.splice(1);
                var routeInfo = routes[lookup];

                if (!routeInfo) {
                    if (!autoNavPath) {
                        return;
                    }

                    routeInfo = {
                        moduleId: autoNavPath + "/" + lookup,
                        name: lookup.substring(0, 1).toUpperCase() + lookup.substring(1)
                    };
                }

                system.acquire(routeInfo.moduleId).then(function (module) {
                    if (typeof module == "function") {
                        if (params && params.length > 0) {
                            trySwap(construct(module, params), routeInfo.name);
                        } else {
                            trySwap(new module(), routeInfo.name);
                        }
                    } else {
                        trySwap(module, routeInfo.name);
                    }
                });
            }

            sammy = Sammy(function(route) {
                route.get('', function() {
                    if (cancelling) {
                        return;
                    }

                    var fragment = this.path.split('#/');
                    if (fragment.length == 2) {
                        activateRoute(fragment[1]);
                    } else {
                        activateRoute(defaultRoute);
                    }
                });
            });

            sammy._checkFormSubmission = function () {
                return false;
            };

            this.navigationReady(true);

            sammy.run();
        }
    };
});<commit_msg>Default auto routing to view models.<commit_after>define(function (require) {
    var system = require('durandal/system');
    var routes = {}, autoNavPath, sammy;

    //NOTE: Sammy.js is not required by the core of Durandal.
    //However, this plugin leverages it to enable navigation.

    function construct(ctor, args) {
        function F() {
            return ctor.apply(this, args);
        }
        F.prototype = ctor.prototype;
        return new F();
    }

    return {
        navigationReady:ko.observable(false),
        navigation: ko.observableArray([]),
        navigateBack:function () {
            window.history.back();
        },
        navigateTo:function (url) {
            sammy.setLocation(url);
        },
        mapAuto: function (path) {
            autoNavPath = path || 'viewmodels';
        },
        mapNav: function (url, moduleId, name) {
            this.mapRoute(url, moduleId, name, true);
        },
        mapRoute: function (url, moduleId, name, isNav) {
            var that = this;
            var routeInfo = {
                url: url,
                moduleId: moduleId,
                name: name || (url.substring(0, 1).toUpperCase() + url.substring(1))
            };

            routes[url] = routeInfo;

            if (isNav) {
                routeInfo.isActive = ko.computed(function() {
                    return that.navigationReady() && that.activator() && that.activator().__moduleId__ == routeInfo.moduleId;
                });

                this.navigation.push(routeInfo);
            }
        },
        enable: function (activator, defaultRoute) {
            var cancelling = false, previousRoute;

            this.activator = activator;

            function trySwap(item, title) {
                activator.activateItem(item).then(function (succeeded) {
                    if (succeeded) {
                        document.title = title;
                        previousRoute = sammy.last_location[1].replace('/', '');
                    } else {
                        cancelling = true;
                        sammy.setLocation(previousRoute);
                        cancelling = false;
                    }
                });
            }

            function activateRoute(route) {
                var parts = route.split('/');
                var lookup = parts[0];
                var params = parts.splice(1);
                var routeInfo = routes[lookup];

                if (!routeInfo) {
                    if (!autoNavPath) {
                        return;
                    }

                    routeInfo = {
                        moduleId: autoNavPath + "/" + lookup,
                        name: lookup.substring(0, 1).toUpperCase() + lookup.substring(1)
                    };
                }

                system.acquire(routeInfo.moduleId).then(function (module) {
                    if (typeof module == "function") {
                        if (params && params.length > 0) {
                            trySwap(construct(module, params), routeInfo.name);
                        } else {
                            trySwap(new module(), routeInfo.name);
                        }
                    } else {
                        trySwap(module, routeInfo.name);
                    }
                });
            }

            sammy = Sammy(function(route) {
                route.get('', function() {
                    if (cancelling) {
                        return;
                    }

                    var fragment = this.path.split('#/');
                    if (fragment.length == 2) {
                        activateRoute(fragment[1]);
                    } else {
                        activateRoute(defaultRoute);
                    }
                });
            });

            sammy._checkFormSubmission = function () {
                return false;
            };

            this.navigationReady(true);

            sammy.run();
        }
    };
});<|endoftext|>