<commit_before>import React from 'react';
import ClassNames from 'classnames';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import Icon from './../icon';

/**
 * A Flash widget.
 *
 * The flash is rendered in two sections: a ventral message 'flash', and a
 * dorsal coloured, expanding 'slider'.
 *
 * == How to use an Flash in a component:
 *
 * In your file
 *
 *   import Flash from 'carbon/lib/components/flash';
 *
 * To render a Flash, setup open and cancel handlers in your view to trigger
 * the message on and off:
 *
 *  <Flash open={ openStatus } onDismiss={ myOnDismiss } message='Alert!' />
 *
 * By default, the flash renders with a clickable close icon that hooks up with the onDismiss function.
 * To instead have the flash disappear after a given time period, pass a prop of timeout in milliseconds.
 *
 *  <Flash open={ openStatus } onDismiss={ myOnDismiss } message='Alert!' timeout={ 2000 }/>
 *
 * @class Flash
 * @constructor
 */
class Flash extends React.Component {

  static propTypes = {

    /**
     * A custom close event handler
     *
     * @property onDismiss
     * @type {Function}
     */
    onDismiss: React.PropTypes.func.isRequired,

    /**
     * Sets the open state of the flash.
     *
     * @property open
     * @type {Boolean}
     * @default false
     */
    open: React.PropTypes.bool.isRequired,

    /**
     * Type of notification.
     *
     * @property type
     * @type {String}
     */
    type: React.PropTypes.string,

    /**
     * Contents of message.
     *
     * @property message
     * @type {String}
     */
    message: React.PropTypes.string.isRequired,

    /**
     * Time for flash to remain on screen
     *
     * @property timeout
     * @type {Number} in milliseconds
     */
    timeout: React.PropTypes.number
  }

  static defaultProps = {
    type: 'alert'
  }

  /**
   *  Conditionally triggers close action after flash displayed.
   *
   * @method componentDidUpdate
   * @return(Void)
   */
  componentDidUpdate(prevProps) {
    if (this.props.timeout && this.props.open === true) {
      if (prevProps.open != this.props.open) {
        setTimeout(() => {
          this.props.onDismiss();
        }, this.props.timeout);
      }
    }
  }

  /**
   * Returns the icon to display depending on type
   *
   * @method iconType
   * @return {String}
   */
  get iconType() {
    let icon;

    switch(this.props.type) {
      case 'success':
        icon = 'tick';
        break;
      case 'error':
        icon = 'warning';
        break;
      case 'alert':
        icon = 'warning';
        break;
      default:
        icon = this.props.type;
        break;
    }
    return icon;
  }

  /**
   * Returns the computed HTML for the flash.
   *
   * @method flashHTML
   * @return {Object} JSX for flash
   */
  get flashHTML() {
    let contents = [];

    contents.push(<Icon className='ui-flash__icon' type={ this.iconType } key="icon" />);

    contents.push(

                    { this.props.message }

);

    if (!this.props.timeout) {
      contents.push(

                      <Icon type='close' />

);
    }

    return

             { contents }

;
  }

  /**
   * Returns the computed HTML for the slider.
   *
   * @method flashHTML
   * @return {Object} JSX for flash
   */
  get sliderHTML() {
    return (

    );
  }

  /**
   * Renders the component.
   *
   * @method render
   * @return {Object} JSX
   */
  render() {
    let flashHTML, sliderHTML, mainClasses;

    mainClasses = ClassNames(
      'ui-flash',
      this.props.className,
      `ui-flash--${this.props.type}`
    );

    if (this.props.open) {
      flashHTML = this.flashHTML;
      sliderHTML = this.sliderHTML;
    }

    return (

        <ReactCSSTransitionGroup
          transitionName="ui-flash__slider"
          transitionEnterTimeout={ 600 }
          transitionLeaveTimeout={ 600 }>
          { sliderHTML }
          <ReactCSSTransitionGroup
            transitionName="ui-flash__content"
            transitionEnterTimeout={ 800 }
            transitionLeaveTimeout={ 600 } >
            { flashHTML }
          </ReactCSSTransitionGroup>
        </ReactCSSTransitionGroup>

    );
  }
}

export default Flash;
<commit_msg>adjusted anim time<commit_after>import React from 'react';
import ClassNames from 'classnames';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import Icon from './../icon';

/**
 * A Flash widget.
 *
 * The flash is rendered in two sections: a ventral message 'flash', and a
 * dorsal coloured, expanding 'slider'.
 *
 * == How to use an Flash in a component:
 *
 * In your file
 *
 *   import Flash from 'carbon/lib/components/flash';
 *
 * To render a Flash, setup open and cancel handlers in your view to trigger
 * the message on and off:
 *
 *  <Flash open={ openStatus } onDismiss={ myOnDismiss } message='Alert!' />
 *
 * By default, the flash renders with a clickable close icon that hooks up with the onDismiss function.
 * To instead have the flash disappear after a given time period, pass a prop of timeout in milliseconds.
 *
 *  <Flash open={ openStatus } onDismiss={ myOnDismiss } message='Alert!' timeout={ 2000 }/>
 *
 * @class Flash
 * @constructor
 */
class Flash extends React.Component {

  static propTypes = {

    /**
     * A custom close event handler
     *
     * @property onDismiss
     * @type {Function}
     */
    onDismiss: React.PropTypes.func.isRequired,

    /**
     * Sets the open state of the flash.
     *
     * @property open
     * @type {Boolean}
     * @default false
     */
    open: React.PropTypes.bool.isRequired,

    /**
     * Type of notification.
     *
     * @property type
     * @type {String}
     */
    type: React.PropTypes.string,

    /**
     * Contents of message.
     *
     * @property message
     * @type {String}
     */
    message: React.PropTypes.string.isRequired,

    /**
     * Time for flash to remain on screen
     *
     * @property timeout
     * @type {Number} in milliseconds
     */
    timeout: React.PropTypes.number
  }

  static defaultProps = {
    type: 'alert'
  }

  /**
   *  Conditionally triggers close action after flash displayed.
   *
   * @method componentDidUpdate
   * @return(Void)
   */
  componentDidUpdate(prevProps) {
    if (this.props.timeout && this.props.open === true) {
      if (prevProps.open != this.props.open) {
        setTimeout(() => {
          this.props.onDismiss();
        }, this.props.timeout);
      }
    }
  }

  /**
   * Returns the icon to display depending on type
   *
   * @method iconType
   * @return {String}
   */
  get iconType() {
    let icon;

    switch(this.props.type) {
      case 'success':
        icon = 'tick';
        break;
      case 'error':
        icon = 'warning';
        break;
      case 'alert':
        icon = 'warning';
        break;
      default:
        icon = this.props.type;
        break;
    }
    return icon;
  }

  /**
   * Returns the computed HTML for the flash.
   *
   * @method flashHTML
   * @return {Object} JSX for flash
   */
  get flashHTML() {
    let contents = [];

    contents.push(<Icon className='ui-flash__icon' type={ this.iconType } key="icon" />);

    contents.push(

                    { this.props.message }

);

    if (!this.props.timeout) {
      contents.push(

                      <Icon type='close' />

);
    }

    return

             { contents }

;
  }

  /**
   * Returns the computed HTML for the slider.
   *
   * @method flashHTML
   * @return {Object} JSX for flash
   */
  get sliderHTML() {
    return (

    );
  }

  /**
   * Renders the component.
   *
   * @method render
   * @return {Object} JSX
   */
  render() {
    let flashHTML, sliderHTML, mainClasses;

    mainClasses = ClassNames(
      'ui-flash',
      this.props.className,
      `ui-flash--${this.props.type}`
    );

    if (this.props.open) {
      flashHTML = this.flashHTML;
      sliderHTML = this.sliderHTML;
    }

    return (

        <ReactCSSTransitionGroup
          transitionName="ui-flash__slider"
          transitionEnterTimeout={ 600 }
          transitionLeaveTimeout={ 600 }>
          { sliderHTML }
          <ReactCSSTransitionGroup
            transitionName="ui-flash__content"
            transitionEnterTimeout={ 800 }
            transitionLeaveTimeout={ 500 } >
            { flashHTML }
          </ReactCSSTransitionGroup>
        </ReactCSSTransitionGroup>

    );
  }
}

export default Flash;
<|endoftext|>


<commit_before>'use strict';

var angular = require('angular');
var Promise = require('bluebird');
var MODULE_NAME = 'mwl.bluebird';

// In regards to: https://github.com/petkaantonov/bluebird#for-library-authors
// My reasoning behind not doing this is to prevent bundling bluebird code with this library

function $qBluebird(resolve, reject) {
  return new Promise(resolve, reject);
}

$qBluebird.prototype = Promise.prototype;

angular.extend($qBluebird, Promise);

//Make bluebird API compatible with angular's subset of Q
//Adapted from: https://gist.github.com/petkaantonov/8363789 and https://github.com/petkaantonov/bluebird-q

$qBluebird.defer = function() {
  var b = $qBluebird.pending();
  b.resolve = angular.bind(b, b.fulfill);
  b.reject = angular.bind(b, b.reject);
  b.notify = angular.bind(b, b.progress);
  return b;
};

$qBluebird.reject = $qBluebird.rejected;
$qBluebird.when = $qBluebird.cast;

var originalAll = $qBluebird.all;
$qBluebird.all = function(promises) {

  if (angular.isObject(promises) && !angular.isArray(promises)) {
    return $qBluebird.props(promises);
  } else {
    return originalAll.call($qBluebird, promises);
  }

};

var originalFinally = $qBluebird.prototype.finally;
$qBluebird.prototype.finally = function(finallyCallback, progressCallback) {
  this.progressed(progressCallback);
  return originalFinally.call(this, finallyCallback);
};

$qBluebird.onPossiblyUnhandledRejection(angular.noop);

angular
  .module(MODULE_NAME, [])
  .constant('Bluebird', $qBluebird)
  .config(function($provide, Bluebird) {

    $provide.decorator('$q', function() {
      return Bluebird;
    });

  })
  .run(function($rootScope, Bluebird) {

    Bluebird.setScheduler(function(cb) {
      $rootScope.$evalAsync(cb);
    });

  });

module.exports = MODULE_NAME;
<commit_msg>Cleaner module name export<commit_after>'use strict';

var angular = require('angular');
var Promise = require('bluebird');

// In regards to: https://github.com/petkaantonov/bluebird#for-library-authors
// My reasoning behind not doing this is to prevent bundling bluebird code with this library

function $qBluebird(resolve, reject) {
  return new Promise(resolve, reject);
}

$qBluebird.prototype = Promise.prototype;

angular.extend($qBluebird, Promise);

//Make bluebird API compatible with angular's subset of Q
//Adapted from: https://gist.github.com/petkaantonov/8363789 and https://github.com/petkaantonov/bluebird-q

$qBluebird.defer = function() {
  var b = $qBluebird.pending();
  b.resolve = angular.bind(b, b.fulfill);
  b.reject = angular.bind(b, b.reject);
  b.notify = angular.bind(b, b.progress);
  return b;
};

$qBluebird.reject = $qBluebird.rejected;
$qBluebird.when = $qBluebird.cast;

var originalAll = $qBluebird.all;
$qBluebird.all = function(promises) {

  if (angular.isObject(promises) && !angular.isArray(promises)) {
    return $qBluebird.props(promises);
  } else {
    return originalAll.call($qBluebird, promises);
  }

};

var originalFinally = $qBluebird.prototype.finally;
$qBluebird.prototype.finally = function(finallyCallback, progressCallback) {
  this.progressed(progressCallback);
  return originalFinally.call(this, finallyCallback);
};

$qBluebird.onPossiblyUnhandledRejection(angular.noop);

var ngModule = angular
  .module('mwl.bluebird', [])
  .constant('Bluebird', $qBluebird)
  .config(function($provide, Bluebird) {

    $provide.decorator('$q', function() {
      return Bluebird;
    });

  })
  .run(function($rootScope, Bluebird) {

    Bluebird.setScheduler(function(cb) {
      $rootScope.$evalAsync(cb);
    });

  });

module.exports = ngModule.name;
<|endoftext|>


<commit_before>import React from 'react';
import {
  distanceFieldBoost, elementFieldBoost, intervalFieldBoost,
  textFieldBoost, filterFieldBoost,
} from 'sajari';

import Base from './Base.js';
import Components from '../constants/QueryComponentConstants.js';

// TODO(tbillington): Use children of intervalFieldBoost as points

const FieldBoost = props => {
  const { data, namespace, ...others } = props;
  return (
    <Base
      {...others}
      runDefault='all'
      componentName={Components.META_BOOST}
      data={data}
      namespace={namespace}
    />
  );
};

FieldBoost.propTypes = {
  data: React.PropTypes.object,
  namespace: React.PropTypes.string,
};

const FilterFieldBoost = props => {
  const { filter, value, ...others } = props;
  return (
    <FieldBoost
      {...others}
      data={filterFieldBoost(filter, value)}
    />
  );
};

FilterFieldBoost.propTypes = {
  filter: React.PropTypes.object.isRequired,
  value: React.PropTypes.any.isRequired,
};

const ElementFieldBoost = props => {
  const { field, values, namespace, ...others } = props;
  return (
    <FieldBoost
      {...others}
      data={elementFieldBoost(field, values)}
      namespace={namespace}
    />
  );
};

ElementFieldBoost.propTypes = {
  field: React.PropTypes.string.isRequired,
  values: React.PropTypes.string.isRequired,
  namespace: React.PropTypes.string,
};

const IntervalFieldBoost = props => {
  const { field, points, namespace, ...others } = props;
  return (
    <FieldBoost
      {...others}
      data={intervalFieldBoost(field, points)}
      namespace={namespace}
    />
  );
};

IntervalFieldBoost.propTypes = {
  field: React.PropTypes.string.isRequired,
  points: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
  namespace: React.PropTypes.string,
};

const TextFieldBoost = props => {
  const { field, text, namespace, ...others } = props;
  return (
    <FieldBoost
      {...others}
      data={textFieldBoost(field, text)}
      namespace={namespace}
    />
  );
};

TextFieldBoost.propTypes = {
  field: React.PropTypes.string.isRequired,
  text: React.PropTypes.string.isRequired,
  namespace: React.PropTypes.string,
};

const FeatureFieldBoost = props => {
  const { data, namespace, ...others } = props
  return (
    <Base
      {...others}
      runDefault='all'
      componentName={Components.FEATURE_BOOST}
      data={data}
      namespace={namespace}
    />
  )
}

export {
  IntervalFieldBoost, TextFieldBoost, ElementFieldBoost,
  FilterFieldBoost, FieldBoost, FeatureFieldBoost,
};
<commit_msg>Fix FieldBoost not using correct component type<commit_after>import React from 'react';
import {
  distanceFieldBoost, elementFieldBoost, intervalFieldBoost,
  textFieldBoost, filterFieldBoost,
} from 'sajari';

import Base from './Base.js';
import Components from '../constants/QueryComponentConstants.js';

// TODO(tbillington): Use children of intervalFieldBoost as points

const FieldBoost = props => {
  const { data, namespace, ...others } = props;
  return (
    <Base
      {...others}
      runDefault='all'
      componentName={Components.FIELD_BOOSTS}
      data={data}
      namespace={namespace}
    />
  );
};

FieldBoost.propTypes = {
  data: React.PropTypes.object,
  namespace: React.PropTypes.string,
};

const FilterFieldBoost = props => {
  const { filter, value, ...others } = props;
  return (
    <FieldBoost
      {...others}
      data={filterFieldBoost(filter, value)}
    />
  );
};

FilterFieldBoost.propTypes = {
  filter: React.PropTypes.object.isRequired,
  value: React.PropTypes.any.isRequired,
};

const ElementFieldBoost = props => {
  const { field, values, namespace, ...others } = props;
  return (
    <FieldBoost
      {...others}
      data={elementFieldBoost(field, values)}
      namespace={namespace}
    />
  );
};

ElementFieldBoost.propTypes = {
  field: React.PropTypes.string.isRequired,
  values: React.PropTypes.string.isRequired,
  namespace: React.PropTypes.string,
};

const IntervalFieldBoost = props => {
  const { field, points, namespace, ...others } = props;
  return (
    <FieldBoost
      {...others}
      data={intervalFieldBoost(field, points)}
      namespace={namespace}
    />
  );
};

IntervalFieldBoost.propTypes = {
  field: React.PropTypes.string.isRequired,
  points: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
  namespace: React.PropTypes.string,
};

const TextFieldBoost = props => {
  const { field, text, namespace, ...others } = props;
  return (
    <FieldBoost
      {...others}
      data={textFieldBoost(field, text)}
      namespace={namespace}
    />
  );
};

TextFieldBoost.propTypes = {
  field: React.PropTypes.string.isRequired,
  text: React.PropTypes.string.isRequired,
  namespace: React.PropTypes.string,
};

const FeatureFieldBoost = props => {
  const { data, namespace, ...others } = props
  return (
    <Base
      {...others}
      runDefault='all'
      componentName={Components.FEATURE_BOOST}
      data={data}
      namespace={namespace}
    />
  )
}

export {
  IntervalFieldBoost, TextFieldBoost, ElementFieldBoost,
  FilterFieldBoost, FieldBoost, FeatureFieldBoost,
};
<|endoftext|>


<commit_before>function toggleObject(e, selector) {
	e.preventDefault();
	$(selector).toggleClass('toggled');
}

function resetForm() {
	$('.btn-form').attr('disabled', 'disabled');
	$('input').val('');
	$('select').prop('selectedIndex', 0);
}

function firstInput() {
	if ($('#name').val() != '') {
		$('.btn-form').removeAttr('disabled');
	} else {
		$('.btn-form').attr('disabled', 'disabled');
	}
}

function openDatepicker(selector) {
	$(selector).datepicker({
		autoclose : true,
		format : 'd MM yyyy'
	});
}

function getDateFormat(param, dateFormat) {
	if (param != '') {
		return moment(param).format(dateFormat);
	}
}

function getSpinner() {
	var options = {
		lines : 11,
		length : 10,
		width : 3,
		radius : 10,
		corners : 1,
		top : '50%',
		left : '50%',
		right : '50%'
	};

	return new Spinner(options);
}

function getAlertNotification(titleVal, textVal, typeVal, buttonVal, classVal) {
	sweetAlert({
		title : titleVal,
		text : textVal,
		type : typeVal,
		confirmButtonText : buttonVal,
		confirmButtonClass : classVal
	});
}

function saveorupdateData() {
	var birthdate = $('#birthdate').val();
	var birthdateDB = getDateFormat(birthdate, 'YYYY-MM-DD');
	var jsonObject = {
		'id' : $('#employeeId').val(),
		'name' : $('#name').val(),
		'gender' : $('#gender').val(),
		'birthdate' : birthdateDB,
		'phone' : $('#phone').val(),
		'email' : $('#email').val()
	};

	var spinner = getSpinner();
	var request = $.ajax({
		type : 'POST',
		url : path + '/master/employee/saveorupdate',
		contentType : 'application/json; charset=UTF-8',
		data : JSON.stringify(jsonObject),
		beforeSend : function() {
			var target = $('body').get(0);
			spinner.spin(target);
		}
	});

	request.success(function(data) {
		spinner.stop();
		switch (data.response) {
		case 'success': {
			getAlertNotification('Success!', 'Data successfully saved!', 'success', 'OK', 'btn-success');
			resetForm();
			resetButton();
			break;
		}
		case 'fail': {
			getAlertNotification('Failed!', 'Failed saving data!', 'error', 'Cancel', 'btn-danger');
			break;
		}
		}
	});

	request.error(function(textStatus, errorThrown) {
		spinner.stop();
		getAlertNotification(errorThrown, textStatus, 'warning', 'Dismiss', 'btn-warning');
	});
}

function updateData(jsonObject) {
	var employees = JSON.parse(jsonObject);
	var birthdate = birthdateFormatter(employees.birthdate);

	$('#employeeId').val(employees.id);
	$('#name').val(employees.name);
	$('#birthdate').val(birthdate);
	$('#gender').val(employees.gender);
	$('#phone').val(employees.phone);
	$('#email').val(employees.email);
}

function deleteData(jsonObject) {
	var spinner = getSpinner();
	var request = $.ajax({
		type : 'POST',
		url : path + '/master/employee/delete',
		contentType : 'application/json; charset=UTF-8',
		data : jsonObject,
		beforeSend : function() {
			var target = $('employee-data').get(0);
			spinner.spin(target);
		}
	});

	request.success(function(data) {
		spinner.stop();
		switch (data.response) {
		case 'success': {
			getAlertNotification('Success!', 'Data successfully deleted!', 'success', 'OK', 'btn-success');
			break;
		}
		case 'fail': {
			getAlertNotification('Failed!', 'Failed deleting data!', 'error', 'Cancel', 'btn-danger');
			break;
		}
		}
	});

	request.error(function(textStatus, errorThrown) {
		spinner.stop();
		getAlertNotification(errorThrown, textStatus, 'warning', 'Dismiss', 'btn-warning');
	});
}

function getEmployeeData(selector) {
	$(selector).bootstrapTable({
		cache : false,
		height : 400,
		method : 'GET',
		search : true,
		searchAlign : 'left',
		showRefresh : true,
		url : path + '/master/employee/search',

		columns : [ {
			field : 'id',
			visible : false
		}, {
			align : 'left',
			field : 'name',
			title : 'Name'
		}, {
			align : 'center',
			field : 'gender',
			title : 'Gender'
		}, {
			align : 'left',
			field : 'birthdate',
			formatter : 'birthdateTableFormatter',
			title : 'Birthdate'
		}, {
			align : 'center',
			field : 'phone',
			formatter : 'genericFormatter',
			title : 'Phone Number'
		}, {
			align : 'left',
			field : 'email',
			formatter : 'genericFormatter',
			title : 'Email'
		}, {
			align : 'center',
			field : 'action',
			formatter : 'actionFormatter',
			events : 'actionEvents',
			title : 'Action'
		} ]
	});
}

function genericFormatter(value) {
	if (value != '') {
		return value;
	} else {
		return 'N/A';
	}
}

function birthdateFormatter(value) {
	if (value != null) {
		return getDateFormat(value, 'D MMMM YYYY');
	} else {
		return '';
	}
}

function birthdateTableFormatter(value) {
	if (value != null) {
		return getDateFormat(value, 'D MMMM YYYY');
	} else {
		return 'N/A';
	}
}

function actionFormatter(value, row, index) {
	return [ '',
	         	'',
	         '',
	         '',
	         	'',
	         '' ].join('');
}

window.actionEvents = {
	'click .edit' : function(e, value, row, index) {
		var jsonObject = JSON.stringify(row);
		updateData(jsonObject);
		updateButton();
	},
	'click .delete' : function(e, value, row, index) {
		var jsonObject = JSON.stringify(row);
		deleteData(jsonObject);
	}
};

function resetButton() {
	$('#form-save').show();
	$('#form-update').hide();
}

function updateButton() {
	$('#search-modal').modal('hide');
	$('#form-save').hide();
	$('#form-update').removeAttr('disabled');
	$('#form-update').show();
}<commit_msg>Add auto refresh table data when searching employee data<commit_after>function toggleObject(e, selector) {
	e.preventDefault();
	$(selector).toggleClass('toggled');
}

function resetForm() {
	$('.btn-form').attr('disabled', 'disabled');
	$('input').val('');
	$('select').prop('selectedIndex', 0);
}

function firstInput() {
	if ($('#name').val() != '') {
		$('.btn-form').removeAttr('disabled');
	} else {
		$('.btn-form').attr('disabled', 'disabled');
	}
}

function openDatepicker(selector) {
	$(selector).datepicker({
		autoclose : true,
		format : 'd MM yyyy'
	});
}

function getDateFormat(param, dateFormat) {
	if (param != '') {
		return moment(param).format(dateFormat);
	}
}

function getSpinner() {
	var options = {
		lines : 11,
		length : 10,
		width : 3,
		radius : 10,
		corners : 1,
		top : '50%',
		left : '50%',
		right : '50%'
	};

	return new Spinner(options);
}

function getAlertNotification(titleVal, textVal, typeVal, buttonVal, classVal) {
	sweetAlert({
		title : titleVal,
		text : textVal,
		type : typeVal,
		confirmButtonText : buttonVal,
		confirmButtonClass : classVal
	});
}

function saveorupdateData() {
	var birthdate = $('#birthdate').val();
	var birthdateDB = getDateFormat(birthdate, 'YYYY-MM-DD');
	var jsonObject = {
		'id' : $('#employeeId').val(),
		'name' : $('#name').val(),
		'gender' : $('#gender').val(),
		'birthdate' : birthdateDB,
		'phone' : $('#phone').val(),
		'email' : $('#email').val()
	};

	var spinner = getSpinner();
	var request = $.ajax({
		type : 'POST',
		url : path + '/master/employee/saveorupdate',
		contentType : 'application/json; charset=UTF-8',
		data : JSON.stringify(jsonObject),
		beforeSend : function() {
			var target = $('body').get(0);
			spinner.spin(target);
		}
	});

	request.success(function(data) {
		spinner.stop();
		switch (data.response) {
		case 'success': {
			getAlertNotification('Success!', 'Data successfully saved!', 'success', 'OK', 'btn-success');
			resetForm();
			resetButton();
			break;
		}
		case 'fail': {
			getAlertNotification('Failed!', 'Failed saving data!', 'error', 'Cancel', 'btn-danger');
			break;
		}
		}
	});

	request.error(function(textStatus, errorThrown) {
		spinner.stop();
		getAlertNotification(errorThrown, textStatus, 'warning', 'Dismiss', 'btn-warning');
	});
}

function updateData(jsonObject) {
	var employees = JSON.parse(jsonObject);
	var birthdate = birthdateFormatter(employees.birthdate);

	$('#employeeId').val(employees.id);
	$('#name').val(employees.name);
	$('#birthdate').val(birthdate);
	$('#gender').val(employees.gender);
	$('#phone').val(employees.phone);
	$('#email').val(employees.email);
}

function deleteData(jsonObject) {
	var spinner = getSpinner();
	var request = $.ajax({
		type : 'POST',
		url : path + '/master/employee/delete',
		contentType : 'application/json; charset=UTF-8',
		data : jsonObject,
		beforeSend : function() {
			var target = $('employee-data').get(0);
			spinner.spin(target);
		}
	});

	request.success(function(data) {
		spinner.stop();
		switch (data.response) {
		case 'success': {
			getAlertNotification('Success!', 'Data successfully deleted!', 'success', 'OK', 'btn-success');
			break;
		}
		case 'fail': {
			getAlertNotification('Failed!', 'Failed deleting data!', 'error', 'Cancel', 'btn-danger');
			break;
		}
		}
	});

	request.error(function(textStatus, errorThrown) {
		spinner.stop();
		getAlertNotification(errorThrown, textStatus, 'warning', 'Dismiss', 'btn-warning');
	});
}

function getEmployeeData(selector) {
	$(selector).bootstrapTable('refresh').bootstrapTable({
		cache : false,
		height : 400,
		method : 'GET',
		search : true,
		searchAlign : 'left',
		showRefresh : true,
		url : path + '/master/employee/search',

		columns : [ {
			align : 'center',
			field : 'action',
			formatter : 'actionFormatter',
			events : 'actionEvents',
			title : 'Action'
		}, {
			field : 'id',
			visible : false
		}, {
			align : 'left',
			field : 'name',
			title : 'Name'
		}, {
			align : 'center',
			field : 'gender',
			title : 'Gender'
		}, {
			align : 'left',
			field : 'birthdate',
			formatter : 'birthdateTableFormatter',
			title : 'Birthdate'
		}, {
			align : 'center',
			field : 'phone',
			formatter : 'genericFormatter',
			title : 'Phone Number'
		}, {
			align : 'left',
			field : 'email',
			formatter : 'genericFormatter',
			title : 'Email'
		} ]
	});
}

function genericFormatter(value) {
	if (value != '') {
		return value;
	} else {
		return 'N/A';
	}
}

function birthdateFormatter(value) {
	if (value != null) {
		return getDateFormat(value, 'D MMMM YYYY');
	} else {
		return '';
	}
}

function birthdateTableFormatter(value) {
	if (value != null) {
		return getDateFormat(value, 'D MMMM YYYY');
	} else {
		return 'N/A';
	}
}

function actionFormatter(value, row, index) {
	return [ '',
	         	'',
	         '',
	         '',
	         	'',
	         '' ].join('');
}

window.actionEvents = {
	'click .edit' : function(e, value, row, index) {
		var jsonObject = JSON.stringify(row);
		updateData(jsonObject);
		updateButton();
	},
	'click .delete' : function(e, value, row, index) {
		var jsonObject = JSON.stringify(row);
		deleteData(jsonObject);
	}
};

function resetButton() {
	$('#form-save').show();
	$('#form-update').hide();
}

function updateButton() {
	$('#search-modal').modal('hide');
	$('#form-save').hide();
	$('#form-update').removeAttr('disabled');
	$('#form-update').show();
}<|endoftext|>


<commit_before>function ActionButton(html, callback)
{
    /*
     * Default Color: #DDDDDD; (light gray)
     * Hovered: Darken uniformly (-111111)
     * Selected: Set blue (|0000FF)
     */
    var self = this; // <- I hate javascript.
    this.hover = function()
    {
        self.hovered = true;
        if(self.selected) self.html.style.backgroundColor = '#CCCCFF';
        else self.html.style.backgroundColor = '#CCCCCC';
    };
    this.unhover = function()
    {
        self.hovered = false;
        if(self.selected) self.html.style.backgroundColor = '#DDDDFF';
        else self.html.style.backgroundColor = '#DDDDDD';
    };
    this.select = function()
    {
        self.selected = true;
        if(self.hovered) self.html.style.backgroundColor = '#CCCCFF';
        else self.html.style.backgroundColor = '#DDDDFF';
    };
    this.deselect = function()
    {
        self.callback(self);
        self.selected = false;
        if(self.hovered) self.html.style.backgroundColor = '#CCCCCC'
        else self.html.style.backgroundColor = '#DDDDDD';
    };
    this.hovered = false;
    this.selected = false;

    this.html = html;
    this.callback = callback;
    this.html.addEventListener('mouseover', this.hover, false);
    this.html.addEventListener('mouseout', this.unhover, false);
    this.html.addEventListener('mousedown', this.select, false);
    this.html.addEventListener('mouseup', this.deselect, false);
}

/* Note- the callback is in charge of enforcing the single selection */
/* Sends (self) to callback on click */
function SingleSelectionButton(html, callback)
{
    /*
     * Default Color: #DDDDDD; (light gray)
     * Hovered: Darken uniformly (-111111)
     * Selected: Set blue (|0000FF)
     */
    var self = this; // <- I hate javascript.
    this.hover = function()
    {
        self.hovered = true;
        if(self.selected) self.html.style.backgroundColor = '#CCCCFF';
        else self.html.style.backgroundColor = '#CCCCCC';
    };
    this.unhover = function()
    {
        self.hovered = false;
        if(self.selected) self.html.style.backgroundColor = '#DDDDFF';
        else self.html.style.backgroundColor = '#DDDDDD';
    };
    this.select = function()
    {
        self.callback(self);
        self.selected = true;
        if(self.hovered) self.html.style.backgroundColor = '#CCCCFF';
        else self.html.style.backgroundColor = '#DDDDFF';
    };
    this.deselect = function()
    {
        self.selected = false;
        if(self.hovered) self.html.style.backgroundColor = '#CCCCCC'
        else self.html.style.backgroundColor = '#DDDDDD';
    };
    this.hovered = false;
    this.selected = false;

    this.html = html;
    this.callback = callback;
    this.html.addEventListener('mouseover', this.hover, false);
    this.html.addEventListener('mouseout', this.unhover, false);
    this.html.addEventListener('click', this.select, false);
}

/* Sends (self, selected) to callback on click */
function SelectionCell(html, odd, callback, object)
{
    /*
     * Default Color: #DDDDDD; (light gray)
     * Odd Id'd: Darken uniformly (-222222)
     * Hovered: Darken uniformly (-111111)
     * Selected: Set blue (|0000FF)
     */
    var self = this; // <- I hate javascript.
    this.hover = function()
    {
        self.hovered = true;
        if(self.selected) self.html.style.backgroundColor = '#AAAAFF';
        else self.html.style.backgroundColor = '#AAAAAA';
    };
    this.unhover = function()
    {
        self.hovered = false;
        if(self.odd)
        {
            if(self.selected) self.html.style.backgroundColor = '#BBBBFF';
            else self.html.style.backgroundColor = '#BBBBBB';
        }
        else
        {
            if(self.selected) self.html.style.backgroundColor = '#DDDDFF';
            else self.html.style.backgroundColor = '#DDDDDD';
        }
    };
    this.select = function()
    {
        self.selected = true;
        if(self.odd)
        {
            if(self.hovered) self.html.style.backgroundColor = '#AAAAFF';
            else self.html.style.backgroundColor = '#BBBBFF';
        }
        else
        {
            if(self.hovered) self.html.style.backgroundColor = '#CCCCFF';
            else self.html.style.backgroundColor = '#DDDDFF';
        }
    };
    this.deselect = function()
    {
        self.selected = false;
        if(self.odd)
        {
            if(self.hovered) self.html.style.backgroundColor = '#AAAAAA'
            else self.html.style.backgroundColor = '#BBBBBB';
        }
        else
        {
            if(self.hovered) self.html.style.backgroundColor = '#CCCCCC'
            else self.html.style.backgroundColor = '#DDDDDD';
        }
    };
    this.clicked = function()
    {
        self.callback(self, !self.selected);
        if(self.selected)self.deselect();
        else self.select();
    }

    this.hovered = false;
    this.selected = false;

    this.html = html;
    this.odd = odd;
    this.callback = callback;
    this.object = object;
    this.html.addEventListener('mouseover', this.hover, false);
    this.html.addEventListener('mouseout', this.unhover, false);
    this.html.addEventListener('click', this.clicked, false);

    this.deselect(); //give self odd coloring
}

/* Note- the callback is in charge of enforcing the single selection */
/* Sends (self) to callback on click */
function SingleSelectionCell(html, odd, callback, object)
{
    /*
     * Default Color: #DDDDDD; (light gray)
     * Odd Id'd: Darken uniformly (-222222)
     * Hovered: Darken uniformly (-111111)
     * Selected: Set blue (|0000FF)
     */
    var self = this; // <- I hate javascript.
    this.hover = function()
    {
        self.hovered = true;
        if(self.selected) self.html.style.backgroundColor = '#AAAAFF';
        else self.html.style.backgroundColor = '#AAAAAA';
    };
    this.unhover = function()
    {
        self.hovered = false;
        if(self.odd)
        {
            if(self.selected) self.html.style.backgroundColor = '#BBBBFF';
            else self.html.style.backgroundColor = '#BBBBBB';
        }
        else
        {
            if(self.selected) self.html.style.backgroundColor = '#DDDDFF';
            else self.html.style.backgroundColor = '#DDDDDD';
        }
    };
    this.select = function()
    {
        self.callback(self);
        self.selected = true;
        if(self.odd)
        {
            if(self.hovered) self.html.style.backgroundColor = '#AAAAFF';
            else self.html.style.backgroundColor = '#BBBBFF';
        }
        else
        {
            if(self.hovered) self.html.style.backgroundColor = '#CCCCFF';
            else self.html.style.backgroundColor = '#DDDDFF';
        }
    };
    this.deselect = function()
    {
        self.selected = false;
        if(self.odd)
        {
            if(self.hovered) self.html.style.backgroundColor = '#AAAAAA'
            else self.html.style.backgroundColor = '#BBBBBB';
        }
        else
        {
            if(self.hovered) self.html.style.backgroundColor = '#CCCCCC'
            else self.html.style.backgroundColor = '#DDDDDD';
        }
    };

    this.hovered = false;
    this.selected = false;

    this.html = html;
    this.odd = odd;
    this.callback = callback;
    this.object = object;
    this.html.addEventListener('mouseover', this.hover, false);
    this.html.addEventListener('mouseout', this.unhover, false);
    this.html.addEventListener('click', this.select, false);

    this.deselect(); //Set its color
}

function NoteView(html, object)
{
    this.html = html;
    this.object = object;

    this.constructHTML = function()
    {
        if(!this.object) return;

        //Ok. This next bit of codes is going to look ridiculous... but since the DOM has no easy way of heirarchical access, its the best I can think of.
        //I recommend opening 'index.html' and finding the xml defining 'note_view_construct' (the DOM node cloned to be this.html) as reference (vim command ':sp index.html')
        this.html.children[0].children[0].innerHTML = this.object.title;
        this.html.children[0].children[1].innerHTML = this.object.likes+' likes, '+this.object.comments.length+' comments';
        this.html.children[0].children[2].innerHTML = this.object.username;

        this.html.children[1].innerHTML = 'Tags: '+object.tagString;

        //Content
        for(var i = 0; i < this.object.contents.length; i++)
            this.html.children[2].appendChild(this.constructContentHTML(this.object.contents[i]));

        alert(JSON.stringify(this.object.comments));
        //Comments
        for(var i = 0; i < this.object.comments.length; i++)
            this.html.children[4].appendChild(this.constructCommentHTML(this.object.comments[i]));
    };

    this.constructContentHTML = function(content)
    {
        var contentHTML = document.getElementById('note_content_cell_construct').cloneNode(true);
        switch(content.type)
        {
            case 'TEXT':
                contentHTML.innerHTML = content.text;
                break;
            case 'PHOTO':
                contentHTML.innerHTML = '';
                break;
            case 'AUDIO':
                contentHTML.innerHTML = content.media_url;
                break;
            case 'VIDEO':
                contentHTML.innerHTML = content.media_url;
                break;
        }
        return contentHTML;
    };

    this.constructCommentHTML = function(comment)
    {
        var commentHTML = document.getElementById('note_comment_cell_construct').cloneNode(true);
        commentHTML.children[0].innerHTML = comment.username;
        commentHTML.appendChild(this.constructContentHTML({"type":"TEXT","text":comment.text}));
        for(var i = 0; i < comment.contents.length; i++)
            commentHTML.appendChild(this.constructContentHTML(comment.contents[i]));
        return commentHTML;
    }

    this.constructHTML();
}
<commit_msg>final attempt at comments<commit_after>function ActionButton(html, callback)
{
    /*
     * Default Color: #DDDDDD; (light gray)
     * Hovered: Darken uniformly (-111111)
     * Selected: Set blue (|0000FF)
     */
    var self = this; // <- I hate javascript.
    this.hover = function()
    {
        self.hovered = true;
        if(self.selected) self.html.style.backgroundColor = '#CCCCFF';
        else self.html.style.backgroundColor = '#CCCCCC';
    };
    this.unhover = function()
    {
        self.hovered = false;
        if(self.selected) self.html.style.backgroundColor = '#DDDDFF';
        else self.html.style.backgroundColor = '#DDDDDD';
    };
    this.select = function()
    {
        self.selected = true;
        if(self.hovered) self.html.style.backgroundColor = '#CCCCFF';
        else self.html.style.backgroundColor = '#DDDDFF';
    };
    this.deselect = function()
    {
        self.callback(self);
        self.selected = false;
        if(self.hovered) self.html.style.backgroundColor = '#CCCCCC'
        else self.html.style.backgroundColor = '#DDDDDD';
    };
    this.hovered = false;
    this.selected = false;

    this.html = html;
    this.callback = callback;
    this.html.addEventListener('mouseover', this.hover, false);
    this.html.addEventListener('mouseout', this.unhover, false);
    this.html.addEventListener('mousedown', this.select, false);
    this.html.addEventListener('mouseup', this.deselect, false);
}

/* Note- the callback is in charge of enforcing the single selection */
/* Sends (self) to callback on click */
function SingleSelectionButton(html, callback)
{
    /*
     * Default Color: #DDDDDD; (light gray)
     * Hovered: Darken uniformly (-111111)
     * Selected: Set blue (|0000FF)
     */
    var self = this; // <- I hate javascript.
    this.hover = function()
    {
        self.hovered = true;
        if(self.selected) self.html.style.backgroundColor = '#CCCCFF';
        else self.html.style.backgroundColor = '#CCCCCC';
    };
    this.unhover = function()
    {
        self.hovered = false;
        if(self.selected) self.html.style.backgroundColor = '#DDDDFF';
        else self.html.style.backgroundColor = '#DDDDDD';
    };
    this.select = function()
    {
        self.callback(self);
        self.selected = true;
        if(self.hovered) self.html.style.backgroundColor = '#CCCCFF';
        else self.html.style.backgroundColor = '#DDDDFF';
    };
    this.deselect = function()
    {
        self.selected = false;
        if(self.hovered) self.html.style.backgroundColor = '#CCCCCC'
        else self.html.style.backgroundColor = '#DDDDDD';
    };
    this.hovered = false;
    this.selected = false;

    this.html = html;
    this.callback = callback;
    this.html.addEventListener('mouseover', this.hover, false);
    this.html.addEventListener('mouseout', this.unhover, false);
    this.html.addEventListener('click', this.select, false);
}

/* Sends (self, selected) to callback on click */
function SelectionCell(html, odd, callback, object)
{
    /*
     * Default Color: #DDDDDD; (light gray)
     * Odd Id'd: Darken uniformly (-222222)
     * Hovered: Darken uniformly (-111111)
     * Selected: Set blue (|0000FF)
     */
    var self = this; // <- I hate javascript.
    this.hover = function()
    {
        self.hovered = true;
        if(self.selected) self.html.style.backgroundColor = '#AAAAFF';
        else self.html.style.backgroundColor = '#AAAAAA';
    };
    this.unhover = function()
    {
        self.hovered = false;
        if(self.odd)
        {
            if(self.selected) self.html.style.backgroundColor = '#BBBBFF';
            else self.html.style.backgroundColor = '#BBBBBB';
        }
        else
        {
            if(self.selected) self.html.style.backgroundColor = '#DDDDFF';
            else self.html.style.backgroundColor = '#DDDDDD';
        }
    };
    this.select = function()
    {
        self.selected = true;
        if(self.odd)
        {
            if(self.hovered) self.html.style.backgroundColor = '#AAAAFF';
            else self.html.style.backgroundColor = '#BBBBFF';
        }
        else
        {
            if(self.hovered) self.html.style.backgroundColor = '#CCCCFF';
            else self.html.style.backgroundColor = '#DDDDFF';
        }
    };
    this.deselect = function()
    {
        self.selected = false;
        if(self.odd)
        {
            if(self.hovered) self.html.style.backgroundColor = '#AAAAAA'
            else self.html.style.backgroundColor = '#BBBBBB';
        }
        else
        {
            if(self.hovered) self.html.style.backgroundColor = '#CCCCCC'
            else self.html.style.backgroundColor = '#DDDDDD';
        }
    };
    this.clicked = function()
    {
        self.callback(self, !self.selected);
        if(self.selected)self.deselect();
        else self.select();
    }

    this.hovered = false;
    this.selected = false;

    this.html = html;
    this.odd = odd;
    this.callback = callback;
    this.object = object;
    this.html.addEventListener('mouseover', this.hover, false);
    this.html.addEventListener('mouseout', this.unhover, false);
    this.html.addEventListener('click', this.clicked, false);

    this.deselect(); //give self odd coloring
}

/* Note- the callback is in charge of enforcing the single selection */
/* Sends (self) to callback on click */
function SingleSelectionCell(html, odd, callback, object)
{
    /*
     * Default Color: #DDDDDD; (light gray)
     * Odd Id'd: Darken uniformly (-222222)
     * Hovered: Darken uniformly (-111111)
     * Selected: Set blue (|0000FF)
     */
    var self = this; // <- I hate javascript.
    this.hover = function()
    {
        self.hovered = true;
        if(self.selected) self.html.style.backgroundColor = '#AAAAFF';
        else self.html.style.backgroundColor = '#AAAAAA';
    };
    this.unhover = function()
    {
        self.hovered = false;
        if(self.odd)
        {
            if(self.selected) self.html.style.backgroundColor = '#BBBBFF';
            else self.html.style.backgroundColor = '#BBBBBB';
        }
        else
        {
            if(self.selected) self.html.style.backgroundColor = '#DDDDFF';
            else self.html.style.backgroundColor = '#DDDDDD';
        }
    };
    this.select = function()
    {
        self.callback(self);
        self.selected = true;
        if(self.odd)
        {
            if(self.hovered) self.html.style.backgroundColor = '#AAAAFF';
            else self.html.style.backgroundColor = '#BBBBFF';
        }
        else
        {
            if(self.hovered) self.html.style.backgroundColor = '#CCCCFF';
            else self.html.style.backgroundColor = '#DDDDFF';
        }
    };
    this.deselect = function()
    {
        self.selected = false;
        if(self.odd)
        {
            if(self.hovered) self.html.style.backgroundColor = '#AAAAAA'
            else self.html.style.backgroundColor = '#BBBBBB';
        }
        else
        {
            if(self.hovered) self.html.style.backgroundColor = '#CCCCCC'
            else self.html.style.backgroundColor = '#DDDDDD';
        }
    };

    this.hovered = false;
    this.selected = false;

    this.html = html;
    this.odd = odd;
    this.callback = callback;
    this.object = object;
    this.html.addEventListener('mouseover', this.hover, false);
    this.html.addEventListener('mouseout', this.unhover, false);
    this.html.addEventListener('click', this.select, false);

    this.deselect(); //Set its color
}

function NoteView(html, object)
{
    this.html = html;
    this.object = object;

    this.constructHTML = function()
    {
        if(!this.object) return;

        //Ok. This next bit of codes is going to look ridiculous... but since the DOM has no easy way of heirarchical access, its the best I can think of.
        //I recommend opening 'index.html' and finding the xml defining 'note_view_construct' (the DOM node cloned to be this.html) as reference (vim command ':sp index.html')
        this.html.children[0].children[0].innerHTML = this.object.title;
        this.html.children[0].children[1].innerHTML = this.object.likes+' likes, '+this.object.comments.length+' comments';
        this.html.children[0].children[2].innerHTML = this.object.username;

        this.html.children[1].innerHTML = 'Tags: '+object.tagString;

        //Content
        for(var i = 0; i < this.object.contents.length; i++)
            this.html.children[2].appendChild(this.constructContentHTML(this.object.contents[i]));

        alert(JSON.stringify(this.object.comments));
        //Comments
        for(var i = 0; i < this.object.comments.length; i++)
            this.html.children[4].appendChild(this.constructCommentHTML(this.object.comments[i]));
    };

    this.constructContentHTML = function(content)
    {
        var contentHTML = document.getElementById('note_content_cell_construct').cloneNode(true);
        switch(content.type)
        {
            case 'TEXT':
                contentHTML.innerHTML = content.text;
                break;
            case 'PHOTO':
                contentHTML.innerHTML = '';
                break;
            case 'AUDIO':
                contentHTML.innerHTML = content.media_url;
                break;
            case 'VIDEO':
                contentHTML.innerHTML = content.media_url;
                break;
        }
        return contentHTML;
    };

    this.constructCommentHTML = function(comment)
    {
        var commentHTML = document.getElementById('note_comment_cell_construct').cloneNode(true);
        commentHTML.children[0].innerHTML = comment.username;
        commentHTML.appendChild(this.constructContentHTML({"type":"TEXT","text":comment.title}));
        for(var i = 0; i < comment.contents.length; i++)
            commentHTML.appendChild(this.constructContentHTML(comment.contents[i]));
        return commentHTML;
    }

    this.constructHTML();
}
<|endoftext|>


<commit_before>/**
 *
Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 * Please see the LICENSE file for information about licensing.

 *
 * WARNING: The Code Processor IS NOT fully reentrant! A second invokation of the code processor prior to the first
 * one finishing will kill the first instance and the second invokation may be unstable.
 *
 * @module CodeProcessor
 * @author Bryan Hughes <bhughes@appcelerator.com>
 */

// ******** Requires ********

var xml2js = require("xml2js"),
	wrench = require("wrench"),

	path = require("path"),
	fs = require("fs"),
	util = require("util"),

	is = require("./TiUtil").is,
	capitalize = require("./TiUtil").capitalize,

	Messaging = require("./Messaging"),
	RuleProcessor = require("./RuleProcessor"),

	Exceptions = require("./Exceptions"),

	AST = require("./AST"),
	Base = require("./Base"),
	Context = require("./Context"),
	Runtime = require("./Runtime"),

	plugins;

// ******** Module exposure for plugins ********

exports.Base = Base;
exports.Context = Context;
exports.Runtime = Runtime;
exports.Messaging = Messaging;
exports.Exceptions = Exceptions;

// ******** Constants ********

var DEFAULT_ANALYSIS_PRECISION = 2,
	DEFAULT_CODE_MINIFICATION = true;

// ******** Prime the rules ********

var rules = wrench.readdirSyncRecursive(path.join(__dirname, "rules")),
	i = 0,
	len = rules.length;
for (; i < len; i++) {
	require(path.join(__dirname, "rules", rules[i]));
}

// ******** Event Documentation ********

/**
 * Indicates that a file is about to be processed.
 *
 * @name module:CodeProcessor.fileProcessingBegin
 * @event
 * @property {JSContext} context The current state of the processor.
 * @property {Object} eventData The data for the event.
 * @property {String} eventData.file The name of the file for which parsing is about to begin.
 * @see CodeProcessor#on
 */

/**
 * Indicates that a file has finished being processed successfully.
 *
 * @name module:CodeProcessor.fileProcessingEnd
 * @event
 * @property {JSContext} context The current state of the processor.
 * @property {Object} eventData The data for the event.
 * @property {String} eventData.file The name of the file for which parsing has just ended.
 * @see CodeProcessor#on
 */

/**
 * Indicates that a requested file, either the entry point file or one that was required/included, could not be loaded .
 *
 * @name module:CodeProcessor.fileLoadError
 * @event
 * @property {JSContext} context The current state of the processor.
 * @property {Object} eventData The data for the event.
 * @property {String} eventData.file The name of the file attempted to load.
 * @property {String} eventData.error Description of the error (e.g. "File Not Found").
 * @see CodeProcessor#on
 */

/**
 * Indicates that a parse error was encountered. Note: parse errors also invoke the {@link CodeProcessor#process} method's
 * error callback with the information below.
 *
 * @name module:CodeProcessor.parseError
 * @event
 * @property {JSContext} context The current state of the processor.
 * @property {Object} eventData The data for the event.
 * @property {String} eventData.message The error message as reported from the underlying AST technology.
 * @property {String} eventData.file The file that the error occured in.
 * @property {Integer} eventData.line The line of the file where the error occured.
 * @property {Integer} eventData.column The column of the file where the error occured.
 * @see CodeProcessor#on
 */

/**
 * Indicates that all parsing has been completed successfully. Note: parsing complete also invokes the
 * {@link CodeProcessor#process} method's completion callback with the information below.
 *
 * @name module:CodeProcessor.processingComplete
 * @event
 * @property {JSContext} context The current state of the processor.
 * @property {Object={}} eventData The data for the event. This is an empty object
 * @see CodeProcessor#on
 */

// ******** Application Methods ********

/**
 * Begins to process a project. If only one function is supplied as an argument, it is assumed to be the
 * completionCallback.
 *
 * @function
 * @param {String} projectRoot The path to the root folder of the project. The processor will look for the tiapp.xml
 *		file in this folder.
 * @param {Array[String]} pluginList A list of plugins to load. Each name must correspond with a subdirectory containing
 *		a node module in the "plugins" directory.
 * @param {Object} [options] Options for controlling the code processor
 * @param {Boolean} [options.invokeMethods] Indicates whether or not methods should be invoked. Default is true.
 * @param {Boolean} [options.evaluateLoops] Indicates whether or not to evaluate loops. Default is false.
 * @param {Winston Logger} [options.logger] An instance of a winston logger (with syslog levels) to use instead of
 *		creating an internal logger instance
 * @param {function} [completionCallback] A callback to be called when all processing has completed successfully.
 * @param {function} [errorCallback] A callback to be called when an error occurred that prevents processing from
 *		continuing, e.g. a syntax error in code.
 * @throws {module:Exceptions.InvalidArguments} Thrown when the project root does not exist.
 * @throws {module:Exceptions.InvalidArguments} Thrown when the tiapp.xml file could not be found.
 * @throws {module:Exceptions.InvalidArguments} Thrown when invalid callbacks are supplied.
 */
exports.process = function process(projectRoot, pluginList, options, completionCallback, errorCallback) {

	// Make sure that the project exists
	if (!fs.existsSync(projectRoot)) {
		throw new Exceptions.InvalidArgumentsError("Error: project root '" + projectRoot + "' does not exist.");
	}

	// Validate the tiapp.xml
	var tiappxmlpath = path.join(projectRoot, "tiapp.xml");
	if (!fs.existsSync(tiappxmlpath)) {
		throw new Exceptions.InvalidArgumentsError("Error: tiapp.xml file '" + tiappxmlpath + "' does not exist.");
	}

	// Parse the tiapp.xml file
	Messaging.log("debug", "Processing tiapp.xml '" + tiappxmlpath + "'");
	(new xml2js.Parser()).parseString(fs.readFileSync(tiappxmlpath).toString(), function (err, result) {

		// Check if there was an error parsing tiapp.xml
		if (err) {
			Messaging.log("error", "Could not parse '" + tiappxmlpath + "': " + err);
		} else {

			// Wrap in a set timeout so that exceptions don't get thrown through the xml parser
			setTimeout(function () {

				// Calculate the various directories of interest
				var codeProcessingDirectory = path.join(projectRoot, "build", "codeprocessing"),
					entryPoint = "app.js";

				// TODO: Replace next line with incremental build mechanism
				fs.rmdir(codeProcessingDirectory);

				// Create the code processing directory, if it doesn't exist
				if (!fs.existsSync(codeProcessingDirectory)) {
					wrench.mkdirSyncRecursive(codeProcessingDirectory);
				}

				// Copy the resources directory into the working directory
				wrench.copyDirSyncRecursive(path.join(projectRoot, "Resources"), path.join(codeProcessingDirectory, "Resources"));

				// TODO: Copy modules located inside the project to the working dir

				// Find out what the main file is
				if (result.mobileweb.main) {
					entryPoint = result.mobileweb.main;
				}
				entryPoint = path.join(codeProcessingDirectory, "Resources", entryPoint);
				if (!fs.existsSync(entryPoint)) {
					throw new Exceptions.InvalidArgumentsError("Error: Project entry point '" + entryPoint + "' does not exist.");
				}
				Messaging.log("debug", "Processing app main '" + entryPoint + "'");

				// Process the project
				processHelper([entryPoint], pluginList, options, completionCallback, errorCallback);
			}, 0);
		}
	});
};

/**
 *
 *
 * @method
 * @returns {Object}
 */
exports.getResults = function getResults() {
	var results = {
			errors: Messaging.getReportedErrors(),
			warnings: Messaging.getReportedWarnings(),
			plugins: {}
		},
		i;
	for(i in plugins) {
		results.plugins[i] = plugins[i].getResults();
	}
	return results;
};

// ******** Plugin Methods ********

/**
 * Processes a file.
 *
 * @function
 * @param {String} file The path to the file to parse
 * @param {Boolean} [createExports] Whether or not to create a module.exports object in the file's context
 * @param {Boolean} [useCurrentContext] Whether or not to create a new context in the file
 * @returns {{@link module:Base.ObjectType} | undefined} The value of module.exports, if one was requested
 */
exports.processFile = function processFile(file, createExports, useCurrentContext) {

	var root,
		module,
		results;

	// Make sure the file exists
	if (fs.existsSync(file)) {

		// Fire the parsing begin event
		Messaging.fireEvent("fileProcessingBegin", {
			file: file
		});

		// Set the current file
		Runtime.fileStack.push(file);

		// Read in the file and generate the AST
		root = AST.parse(file);
		if (root) {
			// Process the project
			root.createExports = createExports;
			root.useCurrentContext = useCurrentContext;
			results = RuleProcessor.processRule(root);
		}

		// Restore the previous file
		Runtime.fileStack.pop();

	} else {
		throw new Exceptions.InvalidArgumentsError("Could not load file '" + file + "'");
	}
	return results;
};

// ******** Unit Test Methods ********

/**
 * Runs the supplied files in a unit-test like manner.
 *
 * @method
 * @param {Array[String]} files The files to run. Files are executed in the order they appear in the array.
 * @returns {Boolean} Whether or not an exception was thrown in code (aka whether or not the unit test passed).
 */
exports.runUnitTest = function runUnitTest(files, pluginList, options, completionCallback, errorCallback) {
	try {
		var result = processHelper(files, pluginList, options, completionCallback, errorCallback);
		return !result || result[0] !== "throw";
	} catch(e) {
		return false;
	}
}

// ******** Internal Methods ********

function processHelper(files, pluginList, options, completionCallback, errorCallback) {

	// Process the options
	if (options) {

		// Store the logger
		if (options.logger) {
			Messaging.setLogger(options.logger);
		}

		// Parse the invoke methods option
		if (options.invokeMethods !== undefined) {
			Runtime.options.invokeMethods = !!options.invokeMethods;
		}
		Messaging.log("debug", "Setting processing option: methods will " +
				(Runtime.options.invokeMethods ? "" : "not ") + "be invoked");

		// Parse the evaluate loops option
		if (options.evaluateLoops !== undefined) {
			Runtime.options.evaluateLoops = !!options.evaluateLoops;
		}
		Messaging.log("debug", "Setting processing option: loops will " +
				(Runtime.options.evaluateLoops ? "" : "not ") + "be evaluated");
	}

	// Load the plugins
	plugins = {};
	var i = 0,
		len = pluginList.length,
		pluginPath;
	for (; i < len; i++) {
		pluginPath = path.resolve(path.join(__dirname, "..", "plugins", pluginList[i]));
		if (fs.existsSync(pluginPath)) {
			Messaging.log("debug", "Loading plugin '" + pluginList[i] + "' at " + pluginPath);
			plugins[pluginList[i]] = new (require(pluginPath))({
				Base: Base,
				Context: Context,
				Runtime: Runtime,
				Messaging: Messaging,
				Exceptions: Exceptions,
				processFile: exports.processFile
			});
		}
	}

	// Hook up the callbacks
	Messaging.on("processingComplete", completionCallback);
	Messaging.on("processingError", errorCallback);

	// Parse the project for all listener sets
	var tags = Messaging.getTags(),
		results,
		j;
	processingLoop: for (i = 0, len = tags.length; i < len; i++) {
		Messaging.log("debug", "Processing event listener set '" + tags[i] + "'");

		// Load the listener set
		Messaging.loadListenerSet(tags[i]);

		// Initialize the runtime
		Runtime.globalObject = new Base.ObjectType();
		var env = Context.NewObjectEnvironment(Runtime.globalObject, null);
		Runtime.globalContext = new Context.ExecutionContext(
				env,
				env,
				exports.globalObject);
		Runtime.contextStack = [Runtime.globalContext];

		// Fire the process event
		Messaging.fireEvent("projectProcessingBegin");

		// Process the files
		for(j = 0; j < files.length; j++) {

			results = exports.processFile(files[i], false);

			// Check if an exception was thrown
			if (results && results[0] === "throw") {
				Messaging.reportError({
					description: "Uncaught exception",
					exception: results[1]
				})
				break processingLoop;
			}
		}
	}

	Messaging.fireEvent("processingComplete");
	return results;
}<commit_msg>[TIMOB-9075] Cleaned up how errors are caught.<commit_after>/**
 *
Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 * Please see the LICENSE file for information about licensing.

 *
 * WARNING: The Code Processor IS NOT fully reentrant! A second invokation of the code processor prior to the first
 * one finishing will kill the first instance and the second invokation may be unstable.
 *
 * @module CodeProcessor
 * @author Bryan Hughes <bhughes@appcelerator.com>
 */

// ******** Requires ********

var xml2js = require("xml2js"),
	wrench = require("wrench"),

	path = require("path"),
	fs = require("fs"),
	util = require("util"),

	is = require("./TiUtil").is,
	capitalize = require("./TiUtil").capitalize,

	Messaging = require("./Messaging"),
	RuleProcessor = require("./RuleProcessor"),

	Exceptions = require("./Exceptions"),

	AST = require("./AST"),
	Base = require("./Base"),
	Context = require("./Context"),
	Runtime = require("./Runtime"),

	plugins;

// ******** Module exposure for plugins ********

exports.Base = Base;
exports.Context = Context;
exports.Runtime = Runtime;
exports.Messaging = Messaging;
exports.Exceptions = Exceptions;

// ******** Constants ********

var DEFAULT_ANALYSIS_PRECISION = 2,
	DEFAULT_CODE_MINIFICATION = true;

// ******** Prime the rules ********

var rules = wrench.readdirSyncRecursive(path.join(__dirname, "rules")),
	i = 0,
	len = rules.length;
for (; i < len; i++) {
	require(path.join(__dirname, "rules", rules[i]));
}

// ******** Event Documentation ********

/**
 * Indicates that a file is about to be processed.
 *
 * @name module:CodeProcessor.fileProcessingBegin
 * @event
 * @property {JSContext} context The current state of the processor.
 * @property {Object} eventData The data for the event.
 * @property {String} eventData.file The name of the file for which parsing is about to begin.
 * @see CodeProcessor#on
 */

/**
 * Indicates that a file has finished being processed successfully.
 *
 * @name module:CodeProcessor.fileProcessingEnd
 * @event
 * @property {JSContext} context The current state of the processor.
 * @property {Object} eventData The data for the event.
 * @property {String} eventData.file The name of the file for which parsing has just ended.
 * @see CodeProcessor#on
 */

/**
 * Indicates that a requested file, either the entry point file or one that was required/included, could not be loaded .
 *
 * @name module:CodeProcessor.fileLoadError
 * @event
 * @property {JSContext} context The current state of the processor.
 * @property {Object} eventData The data for the event.
 * @property {String} eventData.file The name of the file attempted to load.
 * @property {String} eventData.error Description of the error (e.g. "File Not Found").
 * @see CodeProcessor#on
 */

/**
 * Indicates that a parse error was encountered. Note: parse errors also invoke the {@link CodeProcessor#process} method's
 * error callback with the information below.
 *
 * @name module:CodeProcessor.parseError
 * @event
 * @property {JSContext} context The current state of the processor.
 * @property {Object} eventData The data for the event.
 * @property {String} eventData.message The error message as reported from the underlying AST technology.
 * @property {String} eventData.file The file that the error occured in.
 * @property {Integer} eventData.line The line of the file where the error occured.
 * @property {Integer} eventData.column The column of the file where the error occured.
 * @see CodeProcessor#on
 */

/**
 * Indicates that all parsing has been completed successfully. Note: parsing complete also invokes the
 * {@link CodeProcessor#process} method's completion callback with the information below.
 *
 * @name module:CodeProcessor.processingComplete
 * @event
 * @property {JSContext} context The current state of the processor.
 * @property {Object={}} eventData The data for the event. This is an empty object
 * @see CodeProcessor#on
 */

// ******** Application Methods ********

/**
 * Begins to process a project. If only one function is supplied as an argument, it is assumed to be the
 * completionCallback.
 *
 * @function
 * @param {String} projectRoot The path to the root folder of the project. The processor will look for the tiapp.xml
 *		file in this folder.
 * @param {Array[String]} pluginList A list of plugins to load. Each name must correspond with a subdirectory containing
 *		a node module in the "plugins" directory.
 * @param {Object} [options] Options for controlling the code processor
 * @param {Boolean} [options.invokeMethods] Indicates whether or not methods should be invoked. Default is true.
 * @param {Boolean} [options.evaluateLoops] Indicates whether or not to evaluate loops. Default is false.
 * @param {Winston Logger} [options.logger] An instance of a winston logger (with syslog levels) to use instead of
 *		creating an internal logger instance
 * @param {function} [completionCallback] A callback to be called when all processing has completed successfully.
 * @param {function} [errorCallback] A callback to be called when an error occurred that prevents processing from
 *		continuing, e.g. a syntax error in code.
 * @throws {module:Exceptions.InvalidArguments} Thrown when the project root does not exist.
 * @throws {module:Exceptions.InvalidArguments} Thrown when the tiapp.xml file could not be found.
 * @throws {module:Exceptions.InvalidArguments} Thrown when invalid callbacks are supplied.
 */
exports.process = function process(projectRoot, pluginList, options, completionCallback, errorCallback) {

	// Make sure that the project exists
	if (!fs.existsSync(projectRoot)) {
		throw new Exceptions.InvalidArgumentsError("Error: project root '" + projectRoot + "' does not exist.");
	}

	// Validate the tiapp.xml
	var tiappxmlpath = path.join(projectRoot, "tiapp.xml");
	if (!fs.existsSync(tiappxmlpath)) {
		throw new Exceptions.InvalidArgumentsError("Error: tiapp.xml file '" + tiappxmlpath + "' does not exist.");
	}

	// Parse the tiapp.xml file
	Messaging.log("debug", "Processing tiapp.xml '" + tiappxmlpath + "'");
	(new xml2js.Parser()).parseString(fs.readFileSync(tiappxmlpath).toString(), function (err, result) {

		// Check if there was an error parsing tiapp.xml
		if (err) {
			Messaging.log("error", "Could not parse '" + tiappxmlpath + "': " + err);
		} else {

			// Wrap in a set timeout so that exceptions don't get thrown through the xml parser
			setTimeout(function () {

				// Calculate the various directories of interest
				var codeProcessingDirectory = path.join(projectRoot, "build", "codeprocessing"),
					entryPoint = "app.js";

				// TODO: Replace next line with incremental build mechanism
				fs.rmdir(codeProcessingDirectory);

				// Create the code processing directory, if it doesn't exist
				if (!fs.existsSync(codeProcessingDirectory)) {
					wrench.mkdirSyncRecursive(codeProcessingDirectory);
				}

				// Copy the resources directory into the working directory
				wrench.copyDirSyncRecursive(path.join(projectRoot, "Resources"), path.join(codeProcessingDirectory, "Resources"));

				// TODO: Copy modules located inside the project to the working dir

				// Find out what the main file is
				if (result.mobileweb.main) {
					entryPoint = result.mobileweb.main;
				}
				entryPoint = path.join(codeProcessingDirectory, "Resources", entryPoint);
				if (!fs.existsSync(entryPoint)) {
					throw new Exceptions.InvalidArgumentsError("Error: Project entry point '" + entryPoint + "' does not exist.");
				}
				Messaging.log("debug", "Processing app main '" + entryPoint + "'");

				// Process the project
				processHelper([entryPoint], pluginList, options, completionCallback, errorCallback);
			}, 0);
		}
	});
};

/**
 *
 *
 * @method
 * @returns {Object}
 */
exports.getResults = function getResults() {
	var results = {
			errors: Messaging.getReportedErrors(),
			warnings: Messaging.getReportedWarnings(),
			plugins: {}
		},
		i;
	for(i in plugins) {
		results.plugins[i] = plugins[i].getResults();
	}
	return results;
};

// ******** Plugin Methods ********

/**
 * Processes a file.
 *
 * @function
 * @param {String} file The path to the file to parse
 * @param {Boolean} [createExports] Whether or not to create a module.exports object in the file's context
 * @param {Boolean} [useCurrentContext] Whether or not to create a new context in the file
 * @returns {{@link module:Base.ObjectType} | undefined} The value of module.exports, if one was requested
 */
exports.processFile = function processFile(file, createExports, useCurrentContext) {

	var root,
		module,
		results;

	// Make sure the file exists
	if (fs.existsSync(file)) {

		// Fire the parsing begin event
		Messaging.fireEvent("fileProcessingBegin", {
			file: file
		});

		// Set the current file
		Runtime.fileStack.push(file);

		// Read in the file and generate the AST
		root = AST.parse(file);
		if (root) {
			// Process the project
			root.createExports = createExports;
			root.useCurrentContext = useCurrentContext;
			results = RuleProcessor.processRule(root);
		}

		// Restore the previous file
		Runtime.fileStack.pop();

	} else {
		throw new Exceptions.InvalidArgumentsError("Could not load file '" + file + "'");
	}
	return results;
};

// ******** Unit Test Methods ********

/**
 * Runs the supplied files in a unit-test like manner.
 *
 * @method
 * @param {Array[String]} files The files to run. Files are executed in the order they appear in the array.
 * @returns {Boolean} Whether or not an exception was thrown in code (aka whether or not the unit test passed).
 */
exports.runUnitTest = function runUnitTest(files, pluginList, options, completionCallback, errorCallback) {
	try {
		var result = processHelper(files, pluginList, options, completionCallback, errorCallback);
		return !result || result[0] !== "throw";
	} catch(e) {
		return false;
	}
}

// ******** Internal Methods ********

function processHelper(files, pluginList, options, completionCallback, errorCallback) {

	// Process the options
	if (options) {

		// Store the logger
		if (options.logger) {
			Messaging.setLogger(options.logger);
		}

		// Parse the invoke methods option
		if (options.invokeMethods !== undefined) {
			Runtime.options.invokeMethods = !!options.invokeMethods;
		}
		Messaging.log("debug", "Setting processing option: methods will " +
			(Runtime.options.invokeMethods ? "" : "not ") + "be invoked");

		// Parse the evaluate loops option
		if (options.evaluateLoops !== undefined) {
			Runtime.options.evaluateLoops = !!options.evaluateLoops;
		}
		Messaging.log("debug", "Setting processing option: loops will " +
				(Runtime.options.evaluateLoops ? "" : "not ") + "be evaluated");
	}

	// Load the plugins
	plugins = {};
	var i = 0,
		len = pluginList.length,
		pluginPath;
	for (; i < len; i++) {
		pluginPath = path.resolve(path.join(__dirname, "..", "plugins", pluginList[i]));
		if (fs.existsSync(pluginPath)) {
			Messaging.log("debug", "Loading plugin '" + pluginList[i] + "' at " + pluginPath);
			plugins[pluginList[i]] = new (require(pluginPath))({
				Base: Base,
				Context: Context,
				Runtime: Runtime,
				Messaging: Messaging,
				Exceptions: Exceptions,
				processFile: exports.processFile
			});
		}
	}

	// Hook up the callbacks
	Messaging.on("processingComplete", completionCallback);
	Messaging.on("processingError", errorCallback);

	// Parse the project for all listener sets
	var tags = Messaging.getTags(),
		results,
		j;
	processingLoop: for (i = 0, len = tags.length; i < len; i++) {
		Messaging.log("debug", "Processing event listener set '" + tags[i] + "'");

		// Load the listener set
		Messaging.loadListenerSet(tags[i]);

		// Initialize the runtime
		Runtime.globalObject = new Base.ObjectType();
		var env = Context.NewObjectEnvironment(Runtime.globalObject, null);
		Runtime.globalContext = new Context.ExecutionContext(
				env,
				env,
				exports.globalObject);
		Runtime.contextStack = [Runtime.globalContext];

		// Fire the process event
		Messaging.fireEvent("projectProcessingBegin");

		// Process the files
		for(j = 0; j < files.length; j++) {

			try {
				results = exports.processFile(files[i], false);

				// Check if an exception was thrown
				if (results && results[0] === "throw") {
					Messaging.reportError({
						description: "Uncaught exception",
						exception: results[1]
					});
					break processingLoop;
				}
			} catch(e) {
				results = ["throw", undefined, undefined];
				Messaging.reportError({
					description: e.message
				});
				break processingLoop;
			}
		}
	}

	Messaging.fireEvent("processingComplete");
	return results;
}<|endoftext|>


<commit_before>var outputDisplay; // defaults are the first valid options in the displays array
var outputAudio; // set in main.js
var displayBlanked = false;

function setDisplayOutput(device) {
    console.log("set display output to:", device);
    outputDisplay = device;
}

function setAudioOutput(device) {
    console.log("set audio output to:", device);
    outputAudio = device;
}

function switchDisplayInput(input) {
    console.log("switching display input of", outputDisplay, "to", input);

    var body = {};

    body = {
        displays: [{
            name: outputDisplay,
            input: input
        }]
    };

    console.log(body);

    put(body);
}

function switchAudioInput(input) {
    console.log("switching audio input of", outputAudio, "to", input);

    var body = {};

    body = {
        audioDevices: [{
            name: outputAudio,
            input: input
        }]
    };

    console.log(body);

    put(body);
}

function blankDisplay() {
    console.log("blank display");

    var body = {};

    if (displayBlanked == true) {
        body = {
            displays: [{
                name: outputDisplay,
                blanked: false
            }]
        };
        displayBlanked = false;
    } else {
        body = {
            displays: [{
                name: outputDisplay,
                blanked: true
            }]
        };
        displayBlanked = true;
    }

    console.log(body);

    put(body);
    showVolume();
}

var volumeIncrement = 1;

function increaseVolume() {
    if (volume == "MUTED") {
        volume = previousVolume;
    }

    if (volume < 100) {
        volume += volumeIncrement;
    }

    console.log("pressed volume up");

    var body = {
        audioDevices: [{
            name: outputAudio,
            volume: volume
        }]
    };

    console.log(body);

    quietPut(body);
    showVolume();
}

function decreaseVolume() {
    if (volume == "MUTED") {
        volume = previousVolume;
    }

    if (volume > 0) {
        volume -= volumeIncrement;
    }

    console.log("Pressed");

    var body = {
        audioDevices: [{
            name: outputAudio,
            volume: volume
        }]
    };

    console.log(body);

    quietPut(body);
    showVolume();
}

function muteVolume() {
    console.log("Pressed");

    var body = {
        audioDevices: [{
            name: outputAudio,
            muted: true
        }]
    };

    if (volume == "MUTED") {
        volume = previousVolume;
        body.audioDevices[0].muted = false;
    } else {
        previousVolume = volume;
        volume = "MUTED";
    }

    console.log(body);

    put(body);
    showVolume();
}

function powerOn() {
    if (outputDisplay == "room") {
        body = {
            power: "on"
        };
    } else {
        body = {
            displays: [{
                name: outputDisplay,
                power: "on"
            }]
        };
    }

    put(body);
}

function powerOff() {
    if (outputDevice == "room") {
        body = {
            power: "standby"
        };
    } else {
        body = {
            displays: [{
                name: outputDisplay,
                power: "standby"
            }]
        };
    }

    put(body);
}

function put(body) {
    $.ajax({
        type: "PUT",
        url: url,
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: JSON.stringify(body),
        success: pleaseWait(),
        contentType: "application/json; charset=utf-8"
    });
}

function quietPut(body) {
    $.ajax({
        type: "PUT",
        url: url,
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: JSON.stringify(body),
        contentType: "application/json; charset=utf-8"
    });
}
<commit_msg>blank display works<commit_after>var outputDisplay; // defaults are the first valid options in the displays array
var outputAudio; // set in main.js
var displayBlanked = false;

function setDisplayOutput(device) {
    console.log("set display output to:", device);
    outputDisplay = device;
}

function setAudioOutput(device) {
    console.log("set audio output to:", device);
    outputAudio = device;
}

function switchDisplayInput(input) {
    console.log("switching display input of", outputDisplay, "to", input);

    var body = {};

    body = {
        displays: [{
            name: outputDisplay,
            input: input
        }]
    };

    console.log(body);

    put(body);
}

function switchAudioInput(input) {
    console.log("switching audio input of", outputAudio, "to", input);

    var body = {};

    body = {
        audioDevices: [{
            name: outputAudio,
            input: input
        }]
    };

    console.log(body);

    put(body);
}

function blankDisplay() {
    console.log("blank/unblank display");

    var body = {};

    if (displayBlanked == true) {
        body = {
            displays: [{
                name: outputDisplay,
                blanked: false
            }]
        };
        displayBlanked = false;
    } else {
        body = {
            displays: [{
                name: outputDisplay,
                blanked: true
            }]
        };
        displayBlanked = true;
    }

    console.log(body);

    put(body);
    showVolume();
}

var volumeIncrement = 1;

function increaseVolume() {
    if (volume == "MUTED") {
        volume = previousVolume;
    }

    if (volume < 100) {
        volume += volumeIncrement;
    }

    console.log("pressed volume up");

    var body = {
        audioDevices: [{
            name: outputAudio,
            volume: volume
        }]
    };

    console.log(body);

    quietPut(body);
    showVolume();
}

function decreaseVolume() {
    if (volume == "MUTED") {
        volume = previousVolume;
    }

    if (volume > 0) {
        volume -= volumeIncrement;
    }

    console.log("Pressed");

    var body = {
        audioDevices: [{
            name: outputAudio,
            volume: volume
        }]
    };

    console.log(body);

    quietPut(body);
    showVolume();
}

function muteVolume() {
    console.log("Pressed");

    var body = {
        audioDevices: [{
            name: outputAudio,
            muted: true
        }]
    };

    if (volume == "MUTED") {
        volume = previousVolume;
        body.audioDevices[0].muted = false;
    } else {
        previousVolume = volume;
        volume = "MUTED";
    }

    console.log(body);

    put(body);
    showVolume();
}

function powerOn() {
    if (outputDisplay == "room") {
        body = {
            power: "on"
        };
    } else {
        body = {
            displays: [{
                name: outputDisplay,
                power: "on"
            }]
        };
    }

    put(body);
}

function powerOff() {
    if (outputDevice == "room") {
        body = {
            power: "standby"
        };
    } else {
        body = {
            displays: [{
                name: outputDisplay,
                power: "standby"
            }]
        };
    }

    put(body);
}

function put(body) {
    $.ajax({
        type: "PUT",
        url: url,
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: JSON.stringify(body),
        success: pleaseWait(),
        contentType: "application/json; charset=utf-8"
    });
}

function quietPut(body) {
    $.ajax({
        type: "PUT",
        url: url,
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: JSON.stringify(body),
        contentType: "application/json; charset=utf-8"
    });
}
<|endoftext|>


<commit_before>var Cerobee = require('clerobee');
var clerobee = new Cerobee( 16 );

var _ = require('lodash');

/**
* Communication abstractation used for interaction between entities
*
* @class Communication
* @constructor
*/
function Communication(originalId, flowId, externalId, source, event, params, callback, target, error, response){
	this.id = clerobee.generate();
	this.originalId = originalId || this.id;
	this.flowId = flowId || clerobee.generate();

	this.externalId = externalId;

	this.date = Date.now();

	this.source = source;

	this.event = event;

	this.params = params || [];

	if( target )
		this.target = target;
	if( error )
		this.error = error;
	if( response )
		this.response = response;

	if( callback )
		this.callback = callback;
}

var commPrototype = Communication.prototype;

/**
* Check mandatory properies
*
* @method checkProperties
* @param {Array of String} names Attribute names to check
*/
commPrototype.checkProperties = function( names ){
	var i;
	for ( i=0; i<names.length; i+=1 )
		if( !global._.has( this, names[i]) )
			throw new Error( 'Invalid. The property %s must be present.', names[i] );
};

/**
* Validates the message integrity
*
* @method checkValidity
*/
commPrototype.checkValidity = function() {
	this.checkProperties( ['id', 'originalId', 'flowId', 'date', 'source', 'event'] );
	if( this.error || this.response ){
		if( this.error && this.response )
			throw new Error('Invalid comm: comm has both error and response attributes.');
		if( this.id === this.originalId )
			throw new Error('Invalid comm: originalId and Id must be different in a response.');
	}
};

/**
* Creates a clone of this message object
*
* @method spread
*/
commPrototype.spread = function( ) {
	var comm = new Communication( this.originalId, this.flowId, this.externalId, this.source, this.event, this.params );
	comm.id = this.id;
	comm.date = this.date;
	comm.params = this.params.slice();
	comm.callback = null;
	return comm;
};

/**
* Creates a new response object
*
* @method twist
* @param {String} name Name of the responding entity
* @param {Error} error Error object if occurred
* @param {Object} response Response object if exists
*/
commPrototype.twist = function( name, error, response ) {
	var comm = new Communication( this.id, this.flowId, this.externalId, this.source, this.event, this.params, this.callback,  name, error, response );
	return comm;
};

/**
* Creates a sub-communication object within the same flow
*
* @method burst
* @param {String} name Name of the sending entity
* @param {String} event Name of the event to be sent
* @param {Array of Object} params Array of objects to be sent withing the event
* @param {Function} callback Callback function to deliver the response if exists
*/
commPrototype.burst = function( name, event, params, callback ) {
	var comm = new Communication( null, this.flowId, this.externalId, name, event, params, callback );
	return comm;
};

/**
* Extracts response objects from the response attribute
*/
commPrototype.flattenResponse = function(){
	if( !this.response ) return null;
	if( Array.isArray( this.response ) ){
		return _.map( this.response, function(comm){ return comm.response; } );
	}
	else{
		return this.response.response;
	}
};

module.exports = Communication;
<commit_msg>serious event handling error fixed<commit_after>var Cerobee = require('clerobee');
var clerobee = new Cerobee( 16 );

var _ = require('lodash');

/**
* Communication abstractation used for interaction between entities
*
* @class Communication
* @constructor
*/
function Communication(originalId, flowId, externalId, source, event, params, callback, target, error, response){
	this.id = clerobee.generate();
	this.originalId = originalId || this.id;
	this.flowId = flowId || clerobee.generate();

	this.externalId = externalId;

	this.date = Date.now();

	this.source = source;

	this.event = event;

	this.params = params || [];

	if( target )
		this.target = target;
	if( error )
		this.error = error;
	if( response )
		this.response = response;

	if( callback )
		this.callback = callback;
}

var commPrototype = Communication.prototype;

/**
* Check mandatory properies
*
* @method checkProperties
* @param {Array of String} names Attribute names to check
*/
commPrototype.checkProperties = function( names ){
	var i;
	for ( i=0; i<names.length; i+=1 )
		if( !global._.has( this, names[i]) )
			throw new Error( 'Invalid. The property %s must be present.', names[i] );
};

/**
* Validates the message integrity
*
* @method checkValidity
*/
commPrototype.checkValidity = function() {
	this.checkProperties( ['id', 'originalId', 'flowId', 'date', 'source', 'event'] );
	if( this.error || this.response ){
		if( this.error && this.response )
			throw new Error('Invalid comm: comm has both error and response attributes.');
		if( this.id === this.originalId )
			throw new Error('Invalid comm: originalId and Id must be different in a response.');
	}
};

/**
* Creates a clone of this message object
*
* @method spread
*/
commPrototype.spread = function( ) {
	var comm = new Communication( this.originalId, this.flowId, this.externalId, this.source, this.event, this.params );
	comm.id = this.id;
	comm.date = this.date;
	comm.params = this.params.slice();
	comm.callback = null;
	return comm;
};

/**
* Creates a new response object
*
* @method twist
* @param {String} name Name of the responding entity
* @param {Error} error Error object if occurred
* @param {Object} response Response object if exists
*/
commPrototype.twist = function( name, error, response ) {
	var comm = new Communication( this.id, this.flowId, this.externalId, this.source, this.event, this.params, this.callback,  name, error, response );
	return comm;
};

/**
* Creates a sub-communication object within the same flow
*
* @method burst
* @param {String} name Name of the sending entity
* @param {String} event Name of the event to be sent
* @param {Array of Object} params Array of objects to be sent withing the event
* @param {Function} callback Callback function to deliver the response if exists
*/
commPrototype.burst = function( name, event, params, callback ) {
	var comm = new Communication( null, this.flowId, this.externalId, name, event, params, callback );
	return comm;
};

/**
* Extracts response objects from the response attribute
* @method flattenResponse
*/
commPrototype.flattenResponse = function(){
	if( !this.response ) return null;
	if( Array.isArray( this.response ) ){
		return _.map( this.response, function(comm){ return comm.response; } );
	}
	else{
		return this.response.response;
	}
};

module.exports = Communication;
<|endoftext|>


<commit_before>//	'ws' is a URL with a handler for all chat messages
var pathArray = window.location.pathname.split( '/' );
var ws = new WebSocket( 'ws://' + window.location.host + '/chat/' + pathArray[2] + '/send/' );

ws.onopen = function() {
	ws.send( JSON.stringify({
		type: "name",
		name: $( '#name' ).val(),
	}));
};

//	Starts off as the active window
var isActive = true;

//	Set as active window when focused
window.onfocus = function () {
  isActive = true;
};

//	Unset as active window when unfocused
window.onblur = function () {
  isActive = false;
};

//For up-down picking of previous messages
var sentMessages = [];
var sentMessagesIndex = -1;

//	when ws recieves a message, append some html with the contents of the message
ws.onmessage = function ( event ) {
	//Date calculation into local time
	var serverTimeString = JSON.parse(event.data).time + " GMT";
	var serverTime = new Date(serverTimeString);
	var localTimeString = serverTime.toLocaleTimeString( );

	//Function to derive the rand & nick hue from the randString
	function hueCalc( randString ) {
		var hueNum = 0;
		if ( randString ) {
			hueNum = Math.floor( randString.substr( 3, 5 ) * 359/999 );
		}
		return hueNum;
	}
	//Generate an HSL color from the randstring of this message
	var colorString = 'hsl(' + hueCalc( JSON.parse( event.data ).rand ) + ',60%,40%)';

	//	When a message is recieved, check the type of the message, and handle it accordingly
	switch ( JSON.parse(event.data).type ) {
		//	Server message format
		case "server":
			$( '#chatLog' ).append([
				'
',
					'[Server]: ' +
					'' + JSON.parse(event.data).text + '' ,
				'
',
			].join( "\n" ));
		break;

		//	User message format
		case "user":
			//	If the user left their name blank:
			if ( JSON.parse(event.data).name === "" ) {
				$( '#chatLog' ).append([
					'
',
						'' + JSON.parse(event.data).rand + '' +
						'' + '' + '' +
						'' + JSON.parse(event.data).text + '' +
						'' + localTimeString + '',
					'
',
				].join( "\n" ));
			//	If the user has a name:
			} else {
				$( '#chatLog' ).append([
					'
',
						''  + JSON.parse(event.data).rand + '' +
						''  + '[' + JSON.parse(event.data).name + ']: ' + '' +
						'' + JSON.parse(event.data).text + '' +
						'' + localTimeString + '',
					'
',
				].join( "\n" ));
			};
		break;
		case "userList":

		break;
		case "keepalive":

		break;
		default:

		break;
	};

	//	this makes #chatLog scroll to the bottom after each new message
	$( '#chatLog' ).scrollTop( $( '#chatLog' )[0].scrollHeight );

	if ( !isActive && !!$('#notificationSounds').val() ) {
		document.getElementById('notificationTone').play();
	};
};

function websockSend(message) {

	//	If the outgoing message is blank, don't send
	if ( message == "" ) {
		return;
	};

	//	get a new date
	var date = new Date();
	//	send a JSON of name, text, and time (date) to ws
	ws.send( JSON.stringify({
		name: $( '#name' ).val(),
		text: message,
		time: date.toString(),
		type: "message",
	}));
	sentMessages.unshift( $( '#outgoing' ).val() );

	//	blank the outgoing message field
	$( '#outgoing' ).val( "" );
}

function getBacklog() {

}

//function to change the current message index without going too far in either direction
function changeMessageIndex(increment) {
	sentMessagesIndex += increment;

	if (sentMessagesIndex >= (sentMessages.length-1)) {
		sentMessagesIndex = sentMessages.length-1;
	}
	if (sentMessagesIndex <= 0) {
		sentMessagesIndex = 0;
	}
};

$( document ).ready(function() {
	$( '#outgoing' ).keyup( function( e ) {
		//	run a websockSend on a keypress of Enter (keycode 13)
		switch (e.which) {
			case 13:
				websockSend( $( '#outgoing' ).val() );
				sentMessagesIndex = -1;
				break;
			//	So up/down arrows cycle through message history
			case 38:
				changeMessageIndex(1);
				console.log("Current value of sentMessagesIndex is:",sentMessagesIndex);
				$( '#outgoing' ).val( sentMessages[sentMessagesIndex] );
				break;
			case 40:
				changeMessageIndex(-1);
				$( '#outgoing' ).val( sentMessages[sentMessagesIndex] );
				break;
		}
	});

	//	Run once on load
//	ws.send( JSON.stringify({
//		type: "name",
//		name: $( '#name' ).val(),
//	}));

	//	Then run again every time #name changes
	$( '#name' ).change( function() {
		ws.send( JSON.stringify({
			type: "name",
			name: $( '#name' ).val(),
		}));
	});

	//	Check if the server is alive every second (all clientside)
	var serverStatusCheck = setInterval( function() {
		if ( ws.readyState === undefined || ws.readyState > 1 ) {
			$( '#disconnectOverlay' ).fadeIn( 350 );
			clearInterval( serverStatusCheck );
			clearInterval( keepalivePing );
		}
	}, 1000 );

	//	Ping the server to keep your WS alive every 20 seconds
	var keepalivePing = setInterval( function() {
		ws.send(JSON.stringify({
			type: "keepalive",
		}));
	}, 20000 );
});
<commit_msg>Started function for receiving userList data<commit_after>//	'ws' is a URL with a handler for all chat messages
var pathArray = window.location.pathname.split( '/' );
var ws = new WebSocket( 'ws://' + window.location.host + '/chat/' + pathArray[2] + '/send/' );

ws.onopen = function() {
	ws.send( JSON.stringify({
		type: "name",
		name: $( '#name' ).val(),
	}));
};

//	Starts off as the active window
var isActive = true;

//	Set as active window when focused
window.onfocus = function () {
  isActive = true;
};

//	Unset as active window when unfocused
window.onblur = function () {
  isActive = false;
};

//For up-down picking of previous messages
var sentMessages = [];
var sentMessagesIndex = -1;

//	when ws recieves a message, append some html with the contents of the message
ws.onmessage = function ( event ) {
	//Date calculation into local time
	var serverTimeString = JSON.parse(event.data).time + " GMT";
	var serverTime = new Date(serverTimeString);
	var localTimeString = serverTime.toLocaleTimeString( );

	//Function to derive the rand & nick hue from the randString
	function hueCalc( randString ) {
		var hueNum = 0;
		if ( randString ) {
			hueNum = Math.floor( randString.substr( 3, 5 ) * 359/999 );
		}
		return hueNum;
	}
	//Generate an HSL color from the randstring of this message
	var colorString = 'hsl(' + hueCalc( JSON.parse( event.data ).rand ) + ',60%,40%)';

	//	When a message is recieved, check the type of the message, and handle it accordingly
	switch ( JSON.parse(event.data).type ) {
		//	Server message format
		case "server":
			$( '#chatLog' ).append([
				'
',
					'[Server]: ' +
					'' + JSON.parse(event.data).text + '' ,
				'
',
			].join( "\n" ));
		break;

		//	User message format
		case "user":
			//	If the user left their name blank:
			if ( JSON.parse(event.data).name === "" ) {
				$( '#chatLog' ).append([
					'
',
						'' + JSON.parse(event.data).rand + '' +
						'' + '' + '' +
						'' + JSON.parse(event.data).text + '' +
						'' + localTimeString + '',
					'
',
				].join( "\n" ));
			//	If the user has a name:
			} else {
				$( '#chatLog' ).append([
					'
',
						''  + JSON.parse(event.data).rand + '' +
						''  + '[' + JSON.parse(event.data).name + ']: ' + '' +
						'' + JSON.parse(event.data).text + '' +
						'' + localTimeString + '',
					'
',
				].join( "\n" ));
			};
		break;
		case "userList":
			$( '#nameList' )value(

			);
		break;
		case "keepalive":

		break;
		default:

		break;
	};

	//	this makes #chatLog scroll to the bottom after each new message
	$( '#chatLog' ).scrollTop( $( '#chatLog' )[0].scrollHeight );

	if ( !isActive && !!$('#notificationSounds').val() ) {
		document.getElementById('notificationTone').play();
	};
};

function websockSend(message) {

	//	If the outgoing message is blank, don't send
	if ( message == "" ) {
		return;
	};

	//	get a new date
	var date = new Date();
	//	send a JSON of name, text, and time (date) to ws
	ws.send( JSON.stringify({
		name: $( '#name' ).val(),
		text: message,
		time: date.toString(),
		type: "message",
	}));
	sentMessages.unshift( $( '#outgoing' ).val() );

	//	blank the outgoing message field
	$( '#outgoing' ).val( "" );
}

function getBacklog() {

}

//function to change the current message index without going too far in either direction
function changeMessageIndex(increment) {
	sentMessagesIndex += increment;

	if (sentMessagesIndex >= (sentMessages.length-1)) {
		sentMessagesIndex = sentMessages.length-1;
	}
	if (sentMessagesIndex <= 0) {
		sentMessagesIndex = 0;
	}
};

$( document ).ready(function() {
	$( '#outgoing' ).keyup( function( e ) {
		//	run a websockSend on a keypress of Enter (keycode 13)
		switch (e.which) {
			case 13:
				websockSend( $( '#outgoing' ).val() );
				sentMessagesIndex = -1;
				break;
			//	So up/down arrows cycle through message history
			case 38:
				changeMessageIndex(1);
				console.log("Current value of sentMessagesIndex is:",sentMessagesIndex);
				$( '#outgoing' ).val( sentMessages[sentMessagesIndex] );
				break;
			case 40:
				changeMessageIndex(-1);
				$( '#outgoing' ).val( sentMessages[sentMessagesIndex] );
				break;
		}
	});

	//	Run once on load
//	ws.send( JSON.stringify({
//		type: "name",
//		name: $( '#name' ).val(),
//	}));

	//	Then run again every time #name changes
	$( '#name' ).change( function() {
		ws.send( JSON.stringify({
			type: "name",
			name: $( '#name' ).val(),
		}));
	});

	//	Check if the server is alive every second (all clientside)
	var serverStatusCheck = setInterval( function() {
		if ( ws.readyState === undefined || ws.readyState > 1 ) {
			$( '#disconnectOverlay' ).fadeIn( 350 );
			clearInterval( serverStatusCheck );
			clearInterval( keepalivePing );
		}
	}, 1000 );

	//	Ping the server to keep your WS alive every 20 seconds
	var keepalivePing = setInterval( function() {
		ws.send(JSON.stringify({
			type: "keepalive",
		}));
	}, 20000 );
});
<|endoftext|>