<commit_before>const SandBox = function (Core, contextElem, componentSelector) {
  'use strict'
  let containerElemContext = contextElem,
    componentID = componentSelector, // the component that this SandBox instance belongs to.
    errStr0 = 'incorrect parameters passed in; from '
  return {
    log: function (severity, msg, color) {
      if (severity && typeof severity === 'number' && msg && typeof msg === 'string') {
        Core.log(severity, msg, color)
      } else {
        Core.log(3, errStr0 + 'SandBox.log')
      }
    },
    message: function (msg) {
      // TODO: Make this work as a component.
      if (msg && typeof msg === 'string') {
        Core.message(msg)
      } else {
        Core.log(3, errStr0 + 'SandBox.message')
      }
    },
    addToHistory: function (data) {
      if (data && typeof data === 'object') {
        Core.addToHistory(data)
      } else {
        Core.log(3, errStr0 + 'SandBox.addToHistory')
      }
    },
    // component
    createDocumentLevelComponent: function (widgetInnerHTMLStr) {
      if (widgetInnerHTMLStr && typeof widgetInnerHTMLStr === 'string') {
        return Core.createDocumentLevelComponent(widgetInnerHTMLStr)
      } else {
        Core.log(3, errStr0 + 'SandBox.createDocumentLevelComponent')
      }
    },
    removeComponentFromDom: function (containerID) {
      if (containerID && typeof containerID === 'string') {
        Core.removeComponentFromDom(containerID)
      } else {
        Core.log(3, errStr0 + 'SandBox.removeComponentFromDom')
      }
    },
    loadComponentAndCallback: function (componentID, callbackFunc) {
      if (componentID && typeof componentID === 'string' && callbackFunc && typeof callbackFunc === 'function') {
        Core.loadComponentAndCallback(componentID, callbackFunc)
      } else {
        Core.log(3, errStr0 + 'SandBox.loadComponentAndCallback')
      }
    },
    loadComponent: function (componentID) {
      if (componentID && typeof componentID === 'string') {
        Core.loadComponent(componentID)
      } else {
        Core.log(3, errStr0 + 'SandBox.loadComponent')
      }
    },
    removeComponent: function (containerID) {
      if (containerID && typeof containerID === 'string') {
        Core.updateElement(containerID, '')
      } else {
        Core.log(3, errStr0 + 'SandBox.removeComponent')
      }
    },
    getComponentObjAndCallback: function (favouritesPageObjDefID, callbackFunc) {
      if (favouritesPageObjDefID && typeof favouritesPageObjDefID === 'string' && callbackFunc && typeof callbackFunc === 'function') {
        Core.getComponentObjAndCallback(favouritesPageObjDefID, callbackFunc)
      } else {
        Core.log(3, errStr0 + 'SandBox.getComponentObjAndCallback')
      }
    },
    loadJSfileFromObjDefAndCallBack: function (fileName, filePath, callbackFunc) {
      if (fileName && typeof fileName === 'string' && filePath && typeof filePath === 'string' && callbackFunc && typeof callbackFunc === 'function') {
        Core.loadJSfileFromObjDefAndCallBack(fileName, filePath, callbackFunc)
      } else {
        Core.log(3, errStr0 + 'SandBox.loadJSfileFromObjDefAndCallBack')
      }
    },
    loadCSSfileFromObjDef: function (fileName, filePath) {
      if (fileName && typeof fileName === 'string' && filePath && typeof filePath === 'string') {
        Core.loadCSSfileFromObjDef(fileName, filePath)
      } else {
        Core.log(3, errStr0 + 'SandBox.loadCSSfileFromObjDef')
      }
    },
    loadPageDefinitionsFileAndCallBack: function (callbackFunc) {
      if (callbackFunc && typeof callbackFunc === 'function') {
        Core.loadPageDefinitionsFileAndCallBack(callbackFunc)
      } else {
        Core.log(3, errStr0 + 'SandBox.loadPageDefinitionsFileAndCallBack')
      }
    },
    loadPageDefinitions: function () {
      Core.loadPageDefinitions()
    },
    loadPage: function (url) {
      if (url && typeof url === 'string') {
        Core.loadPage(url)
      } else {
        Core.log(3, errStr0 + 'SandBox.loadPage')
      }
    },
    loadFile: function (fileName, fileType, filePath) {
      if (fileName && typeof fileName === 'string' && fileType && typeof fileType === 'string' && filePath && typeof filePath === 'string') {
        return Core.loadFile(fileName, fileType, filePath)
      } else {
        Core.log(3, errStr0 + 'SandBox.LoadFile')
      }
    },
    removeFile: function (fileName, fileType) {
      if (fileName && typeof fileName === 'string' && fileType && typeof fileType === 'string') {
        Core.removeFile(fileName, fileType)
      } else {
        Core.log(3, errStr0 + 'SandBox.removeFile')
      }
    },
    // DOM
    applyElementCSSClass: function (elementID, className) {
      if (elementID && typeof elementID === 'string' && className && typeof className === 'string') {
        Core.applyElementCSSClass(elementID, className)
      } else {
        Core.log(3, errStr0 + 'SandBox.applyElementCSSClass')
      }
    },
    getElement: function (elementID) {
      if (elementID && typeof elementID === 'string') {
        return Core.getElement(elementID)
      } else {
        Core.log(3, errStr0 + 'SandBox.getElement')
      }
    },
    setElement: function (containerID, element) {
      if (containerID && typeof containerID === 'string' && element && typeof element === 'object') {
        Core.setElement(containerID, element)
      } else {
        Core.log(3, errStr0 + 'SandBox.setElement')
      }
    },
    getElementInContext: function (elementID) {
      if (elementID && typeof elementID === 'string') {
        return Core.getChildOfParentByID(containerElemContext, elementID)
      } else {
        Core.log(3, errStr0 + 'SandBox.getElementInContext')
      }
    },
    getChildOfParent: function (parentElem, childID) {
      if (parentElem && childID && typeof childID === 'string') {
        return Core.getChildOfParent(parentElem, childID)
      } else {
        Core.log(3, errStr0 + 'SandBox.getChildOfParent')
      }
    },
    getParentNode: function (elem) {
      if (elem && typeof elem === 'object') {
        return Core.getParentNode(elem)
      } else {
        Core.log(3, 'incorrect parameter passed in; from SandBox.getParentNode')
      }
    },
    setElementContext: function (elemID) {
      if (elemID && typeof elemID === 'string') {
        containerElemContext = Core.getElement(elemID)
      } else {
        Core.log(3, errStr0 + 'SandBox.setElementContext')
      }
    },
    updateElement: function (elementID, newStructure) {
      if (elementID && (typeof elementID === 'string' || typeof elementID === 'object') && newStructure && typeof newStructure === 'string') {
        Core.updateElement(elementID, newStructure)
      } else {
        Core.log(3, errStr0 + 'SandBox.updateElement')
      }
    },
    // events
    addEventHandlerToElement: function (elementID, event, func) {
      if (elementID && typeof elementID === 'string' && event && typeof event === 'string' && func && typeof func === 'function') {
        // we do this so we don't traverse the whole DOM, thus increasing performance
        let childElem = Core.getChildOfParentByID(containerElemContext, elementID)
        Core.addEventHandlerToElement(childElem, event, func)
      } else {
        Core.log(3, errStr0 + 'SandBox.addEventHandlerToElement')
      }
    },
    removeEventHandlerFromElement: function (elementID, event, func) {
      if (elementID && typeof elementID === 'string' && event && typeof event === 'string' && func && typeof func === 'function') {
        // we do this so we don't traverse the whole DOM, thus increasing performance
        let childElem = Core.getChildOfParentByID(containerElemContext, elementID)
        Core.removeEventHandlerFromElement(childElem, event, func)
      } else {
        Core.log(3, errStr0 + 'SandBox.removeEventHandlerFromElement')
      }
    },
    addEventHandlerToParent: function (event, func) {
      // since we don't have the parent of the parent, then we just do the normal event handling attachment
      if (event && typeof event === 'string' && func && typeof func === 'function') {
        Core.addEventHandlerToElement(containerElemContext, event, func)
      } else {
        Core.log(3, errStr0 + 'SandBox.addEventHandlerToParent')
      }
    },
    removeEventHandlerFromParent: function (event, func) {
      if (event && typeof event === 'string' && func && typeof func === 'function') {
        Core.removeEventHandlerFromElement(containerElemContext, event, func)
      } else {
        Core.log(3, errStr0 + 'SandBox.removeEventHandlerFromParent')
      }
    },
    registerForCustomEvents: function (eventsObj) {
      if (eventsObj && typeof eventsObj === 'object') {
        Core.registerForCustomEvents(componentID, eventsObj)
      } else {
        Core.log(3, 'incorrect parameter passed in; from SandBox.registerForCustomEvents')
      }
    },
    unregisterCustomEvent: function (eventType) {
      if (eventType && typeof eventType === 'string') {
        Core.unregisterCustomEvent(componentID, eventType)
      } else {
        Core.log(3, 'incorrect parameter passed in; from SandBox.unregisterCustomEvent')
      }
    },
    unregisterAllCustomEvents: function () {
      if (Core.unregisterAllCustomEvents(componentID)) {
        Core.log(1, 'All events for component ' + componentID + ' have been removed; from SandBox.unregisterAllCustomEvents', 'green')
      } else {
        Core.log(2, 'No custom events found for ' + componentID + ' component; from SandBox.unregisterAllCustomEvents')
      }
    },
    publishCustomEvent: function (eventObj) {
      if (eventObj && typeof eventObj === 'object') {
        Core.publishCustomEvent(eventObj)
      } else {
        Core.log(3, 'incorrect parameter passed in; from SandBox.publishCustomEvent')
      }
    },
    // cookies and storage
    getValueAsArrayFromCookie: function (cookieName) {
      if (cookieName && typeof cookieName === 'string') {
        return Core.getCookieValueAsArray(cookieName)
      } else {
        Core.log(3, errStr0 + 'SandBox.getValueAsArrayFromCookie')
      }
    },
    populateCookie: function (cookieName, value) {
      if (cookieName && typeof cookieName === 'string') {
        Core.CookieHandler.populateCookie(cookieName, value)
        Core.populateCookie(cookieName, value)
      } else {
        Core.log(3, errStr0 + 'SandBox.populateCookie')
      }
    },
    removeValueFromCookie: function (cookieName, value) {
      if (cookieName && typeof cookieName === 'string' && value) {
        Core.removeValueByValueFromCookie(cookieName, value)
      } else {
        Core.log(3, errStr0 + 'SandBox.removeValueFromCookie')
      }
    },
    getValueForKeyAsObjectFromStorage: function (key, decode) {
      if (key && typeof key === 'string') {
        return Core.getValueForKeyAsObjectFromStorage(key, decode)
      } else {
        Core.log(3, errStr0 + 'SandBox.getValueForKeyAsObjectFromStorage')
      }
    },
    // ajax
    makeAjaxCall: function (apiURL, queryStr, method, callbackFunc) {
      if (apiURL && typeof apiURL === 'string' && queryStr && typeof queryStr === 'string' && callbackFunc && typeof callbackFunc === 'function') {
        Core.makeAjaxCall(apiURL, queryStr, method, callbackFunc)
      } else {
        Core.log(3, errStr0 + 'SandBox.makeAjaxCall')
      }
    },
    loadPageByAjax: function (apiURL, queryStr, callbackFunc, page, method) {
      if (apiURL && typeof apiURL === 'string' && queryStr && typeof queryStr === 'string' && callbackFunc && typeof callbackFunc === 'function') {
        Core.loadPageByAjax(apiURL, queryStr, callbackFunc, page, method)
      } else {
        Core.log(3, errStr0 + 'SandBox.loadPageByAjax')
      }
    },
    getJSONObj: function (apiURL, callbackFunc) {
      if (apiURL && typeof apiURL === 'string' && callbackFunc && typeof callbackFunc === 'function') {
        Core.getJSONObj(apiURL, callbackFunc)
      } else {
        Core.log(3, errStr0 + 'SandBox.getJSONObj')
      }
    },
    // openlayers
    getMap: function () {
      return Core.getMap()
    },
    getView: function () {
      return Core.getView()
    },
    setMap: function (map) {
      if (map && typeof map === 'object') {
        Core.setMap(map)
      } else {
        Core.log(3, errStr0 + 'SandBox.setMap')
      }
    },
    addControl: function (control) {
      if (control && typeof control === 'object') {
        Core.addControl(control)
      } else {
        Core.log(3, errStr0 + 'SandBox.addMapControl')
      }
    },
    getMouseProjection: function () {
      return Core.getMouseProjection()
    },
    setMouseProjection: function (proj) {
      if (proj && typeof proj === 'string') {
        Core.setMouseProjection(proj)
      } else {
        Core.log(3, errStr0 + 'SandBox.setMouseProjection')
      }
    },
    getMousePrecision: function () {
      return Core.getMousePrecision()
    },
    setMousePrecision: function () {
      Core.setMousePrecision()
    },
    getFormat: function (format) {
      if (format && typeof format === 'string') {
        return Core.getFormat(format)
      } else {
        Core.log(3, errStr0 + 'SandBox.getFormat')
      }
    },
    getLoadingStrategy: function (strategy) {
      return Core.getLoadingStrategy(strategy)
    },
    getSource: function (source, opt) {
      return Core.getSource(source, opt)
    },
    getLayer: function (layer, opt) {
      return Core.getLayer(layer, opt)
    },
    addLayer: function (layer) {
      Core.addLayer(layer)
    },
    selectLayer: function (layer) {
      if (layer && typeof layer === 'object') {
        return Core.selectLayer(layer)
      } else {
        Core.log(3, errStr0 + 'SandBox.selectLayer')
      }
    },
    getSelectedLayer: function () {
      return Core.getSelectedLayer()
    },
    deselectLayer: function () {
      return Core.deselectLayer()
    }
  }
}

export default SandBox
<commit_msg>start converting SandBox to typescript<commit_after>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SandBox = function (Core, contextElem, componentSelector) {
    'use strict';
    var containerElemContext = contextElem, componentID = componentSelector, // the component that this SandBox instance belongs to.
    errStr0 = 'incorrect parameters passed in; from ';
    return {
        log: function (severity, msg, color) {
            Core.log(severity, msg, color);
        },
        message: function (msg) {
            // TODO: Make this work as a component.
            Core.message(msg);
        },
        addToHistory: function (data) {
            if (data && typeof data === 'object') {
                Core.addToHistory(data);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.addToHistory');
            }
        },
        // component
        createDocumentLevelComponent: function (widgetInnerHTMLStr) {
            return Core.createDocumentLevelComponent(widgetInnerHTMLStr);
        },
        removeComponentFromDom: function (containerID) {
            Core.removeComponentFromDom(containerID);
        },
        loadComponentAndCallback: function (componentID, callbackFunc) {
            if (callbackFunc && typeof callbackFunc === 'function') {
                Core.loadComponentAndCallback(componentID, callbackFunc);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.loadComponentAndCallback');
            }
        },
        loadComponent: function (componentID) {
            Core.loadComponent(componentID);
        },
        removeComponent: function (containerID) {
            Core.updateElement(containerID, '');
        },
        loadPageDefinitionFromStorageAndCallBack: function (favouritesPageObjDefID, callbackFunc) {
            if (callbackFunc && typeof callbackFunc === 'function') {
                Core.loadPageDefinitionFromStorageAndCallBack(favouritesPageObjDefID, callbackFunc);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.loadPageDefinitionFromStorageAndCallBack');
            }
        },
        loadJSfileFromObjDefAndCallBack: function (fileName, filePath, callbackFunc) {
            if (callbackFunc && typeof callbackFunc === 'function') {
                Core.loadJSfileFromObjDefAndCallBack(fileName, filePath, callbackFunc);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.loadJSfileFromObjDefAndCallBack');
            }
        },
        loadCSSfileFromObjDef: function (fileName, filePath) {
            Core.loadCSSfileFromObjDef(fileName, filePath);
        },
        loadPageDefinitionsFileAndCallBack: function (callbackFunc) {
            if (callbackFunc && typeof callbackFunc === 'function') {
                Core.loadPageDefinitionsFileAndCallBack(callbackFunc);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.loadPageDefinitionsFileAndCallBack');
            }
        },
        loadPageDefinitions: function () {
            Core.loadPageDefinitions();
        },
        loadPage: function (url) {
            Core.loadPage(url);
        },
        loadFile: function (fileName, fileType, filePath) {
            return Core.loadFile(fileName, fileType, filePath);
        },
        removeFile: function (fileName, fileType) {
            Core.removeFile(fileName, fileType);
        },
        // DOM
        applyElementCSSClass: function (elementID, className) {
            Core.applyElementCSSClass(elementID, className);
        },
        getElement: function (elementID) {
            return Core.getElement(elementID);
        },
        setElement: function (containerID, element) {
            if (element && typeof element === 'object') {
                Core.setElement(containerID, element);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.setElement');
            }
        },
        getElementInContext: function (elementID) {
            return Core.getChildOfParentByID(containerElemContext, elementID);
        },
        getChildOfParent: function (parentElem, childID) {
            if (parentElem && childID && typeof childID === 'string') {
                return Core.getChildOfParent(parentElem, childID);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.getChildOfParent');
            }
        },
        getParentNode: function (elem) {
            if (elem && typeof elem === 'object') {
                return Core.getParentNode(elem);
            }
            else {
                Core.log(3, 'incorrect parameter passed in; from SandBox.getParentNode');
            }
        },
        setElementContext: function (elemID) {
            containerElemContext = Core.getElement(elemID);
        },
        updateElement: function (elementID, newStructure) {
            if (elementID && (typeof elementID === 'string' || typeof elementID === 'object') && newStructure && typeof newStructure === 'string') {
                Core.updateElement(elementID, newStructure);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.updateElement');
            }
        },
        // events
        addEventHandlerToElement: function (elementID, event, func) {
            if (func && typeof func === 'function') {
                // we do this so we don't traverse the whole DOM, thus increasing performance
                var childElem = Core.getChildOfParentByID(containerElemContext, elementID);
                Core.addEventHandlerToElement(childElem, event, func);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.addEventHandlerToElement');
            }
        },
        removeEventHandlerFromElement: function (elementID, event, func) {
            if (func && typeof func === 'function') {
                // we do this so we don't traverse the whole DOM, thus increasing performance
                var childElem = Core.getChildOfParentByID(containerElemContext, elementID);
                Core.removeEventHandlerFromElement(childElem, event, func);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.removeEventHandlerFromElement');
            }
        },
        addEventHandlerToParent: function (event, func) {
            // since we don't have the parent of the parent, then we just do the normal event handling attachment
            if (func && typeof func === 'function') {
                Core.addEventHandlerToElement(containerElemContext, event, func);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.addEventHandlerToParent');
            }
        },
        removeEventHandlerFromParent: function (event, func) {
            if (func && typeof func === 'function') {
                Core.removeEventHandlerFromElement(containerElemContext, event, func);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.removeEventHandlerFromParent');
            }
        },
        registerForCustomEvents: function (eventsObj) {
            if (eventsObj && typeof eventsObj === 'object') {
                Core.registerForCustomEvents(componentID, eventsObj);
            }
            else {
                Core.log(3, 'incorrect parameter passed in; from SandBox.registerForCustomEvents');
            }
        },
        unregisterCustomEvent: function (eventType) {
            Core.unregisterCustomEvent(componentID, eventType);
        },
        unregisterAllCustomEvents: function () {
            if (Core.unregisterAllCustomEvents(componentID)) {
                Core.log(1, 'All events for component ' + componentID + ' have been removed; from SandBox.unregisterAllCustomEvents', 'green');
            }
            else {
                Core.log(2, 'No custom events found for ' + componentID + ' component; from SandBox.unregisterAllCustomEvents');
            }
        },
        publishCustomEvent: function (eventObj) {
            if (eventObj && typeof eventObj === 'object') {
                Core.publishCustomEvent(eventObj);
            }
            else {
                Core.log(3, 'incorrect parameter passed in; from SandBox.publishCustomEvent');
            }
        },
        // cookies and storage
        getValueAsArrayFromCookie: function (cookieName) {
            return Core.getCookieValueAsArray(cookieName);
        },
        populateCookie: function (cookieName, value) {
            Core.CookieHandler.populateCookie(cookieName, value);
            Core.populateCookie(cookieName, value);
        },
        removeValueFromCookie: function (cookieName, value) {
            if (value) {
                Core.removeValueByValueFromCookie(cookieName, value);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.removeValueFromCookie');
            }
        },
        getValueForKeyAsObjectFromStorage: function (key, decode) {
            return Core.getValueForKeyAsObjectFromStorage(key, decode);
        },
        // ajax
        makeAjaxCall: function (apiURL, queryStr, method, callbackFunc) {
            if (callbackFunc && typeof callbackFunc === 'function') {
                Core.makeAjaxCall(apiURL, queryStr, method, callbackFunc);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.makeAjaxCall');
            }
        },
        loadPageByAjax: function (apiURL, queryStr, callbackFunc, page, method) {
            if (callbackFunc && typeof callbackFunc === 'function') {
                Core.loadPageByAjax(apiURL, queryStr, callbackFunc, page, method);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.loadPageByAjax');
            }
        },
        getJSONObj: function (apiURL, callbackFunc) {
            if (callbackFunc && typeof callbackFunc === 'function') {
                Core.getJSONObj(apiURL, callbackFunc);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.getJSONObj');
            }
        },
        // openlayers
        getMap: function () {
            return Core.getMap();
        },
        getView: function () {
            return Core.getView();
        },
        setMap: function (map) {
            if (map && typeof map === 'object') {
                Core.setMap(map);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.setMap');
            }
        },
        addControl: function (control) {
            if (control && typeof control === 'object') {
                Core.addControl(control);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.addMapControl');
            }
        },
        getMouseProjection: function () {
            return Core.getMouseProjection();
        },
        setMouseProjection: function (proj) {
            Core.setMouseProjection(proj);
        },
        getMousePrecision: function () {
            return Core.getMousePrecision();
        },
        setMousePrecision: function () {
            Core.setMousePrecision();
        },
        getFormat: function (format) {
            return Core.getFormat(format);
        },
        getLoadingStrategy: function (strategy) {
            return Core.getLoadingStrategy(strategy);
        },
        getSource: function (source, opt) {
            return Core.getSource(source, opt);
        },
        getLayer: function (layer, opt) {
            return Core.getLayer(layer, opt);
        },
        addLayer: function (layer) {
            Core.addLayer(layer);
        },
        selectLayer: function (layer) {
            if (layer && typeof layer === 'object') {
                return Core.selectLayer(layer);
            }
            else {
                Core.log(3, errStr0 + 'SandBox.selectLayer');
            }
        },
        getSelectedLayer: function () {
            return Core.getSelectedLayer();
        },
        deselectLayer: function () {
            return Core.deselectLayer();
        }
    };
};
exports.default = SandBox;
//# sourceMappingURL=SandBox.js.map<|endoftext|>


<commit_before>
$('#ssn').keyup(function() {
    var val = this.value.replace(/\D/g, '');
    var newVal = '';
    var sizes = [3, 2, 4];

    for (var i in sizes) {
      if (val.length > sizes[i]) {
        newVal += val.substr(0, sizes[i]) + '-';
        val = val.substr(sizes[i]);
      }
      else
        break;
    }

    newVal += val;
    this.value = newVal;
});

var myApp = angular.module('myApp',[]);

myApp.controller('myController', function($scope) {

    $scope.myssn;
    $scope.ssnWithoutHyphen;

    $scope.showSSN = function(){
        console.log("Show SSN Called");
        $scope.ssnWithoutHyphen = $scope.myssn.replace(/[\W\s\._\-]+/g, '');
    }

});<commit_msg>Delete script.js<commit_after><|endoftext|>


<commit_before>(function() {
  angular
    .module('viewpoint.routes')
    .config(viewpointRoutes);

  viewpointRoutes.$inject = ["$stateProvider", "$urlRouterProvider"];

  function viewpointRoutes($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/home");

    $stateProvider
      .state("home", {
        url: "/home",
        templateUrl: "/views/home.html",
        controller: "homeCtrl",
        controllerAs: "vm",
        bindToController: true
      })
      .state("signup", {
        url: "/cadastre-se",
        templateUrl: "/views/signup.html",
        controller: "signupCtrl",
        controllerAs: "vm",
        bindToController: true
      })
      .state("signin", {
        url: "/entrar",
        templateUrl: "/views/signin.html",
        controller: "signinCtrl",
        controllerAs: "vm",
        bindToController: true
      })
      .state("passwordRecovery", {
        url: "/recuperar-senha",
        templateUrl: "/views/password-recovery.html",
        controller: "passwordRecoveryCtrl",
        controllerAs: "vm",
        bindToController: true
      })
      .state("passwordUpdate", {
        url: "/alterar-senha",
        templateUrl: "/views/password-update.html",
        controller: "passwordUpdateCtrl",
        controllerAs: "vm",
        bindToController: true
      });
  };
})();
<commit_msg>Define rota par dashboard<commit_after>(function () {
  angular
    .module('viewpoint.routes')
    .config(viewpointRoutes);

  viewpointRoutes.$inject = ["$stateProvider", "$urlRouterProvider"];

  function viewpointRoutes($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/home");

    $stateProvider
      .state("home", {
        url: "/home",
        templateUrl: "/views/home.html",
        controller: "homeCtrl",
        controllerAs: "vm",
        bindToController: true
      })
      .state("signup", {
        url: "/cadastre-se",
        templateUrl: "/views/signup.html",
        controller: "signupCtrl",
        controllerAs: "vm",
        bindToController: true
      })
      .state("signin", {
        url: "/entrar",
        templateUrl: "/views/signin.html",
        controller: "signinCtrl",
        controllerAs: "vm",
        bindToController: true
      })
      .state("passwordRecovery", {
        url: "/recuperar-senha",
        templateUrl: "/views/password-recovery.html",
        controller: "passwordRecoveryCtrl",
        controllerAs: "vm",
        bindToController: true
      })
      .state("passwordUpdate", {
        url: "/alterar-senha",
        templateUrl: "/views/password-update.html",
        controller: "passwordUpdateCtrl",
        controllerAs: "vm",
        bindToController: true
      })
      .state("dashboard", {
        url: "/dashboard",
        templateUrl: "/views/dashboard.html",
        controller: "dashboardCtrl",
        controllerAs: "vm",
        bindToController: true
      });
  };
})();
<|endoftext|>


<commit_before>'use strict';

angular.module('copayApp.services').factory('ongoingProcess', function($log, $timeout, $filter, lodash, $ionicLoading, gettext, platformInfo) {
  var root = {};
  var isCordova = platformInfo.isCordova;
  var isWindowsPhoneApp = platformInfo.isCordova && platformInfo.isWP;

  var ongoingProcess = {};

  var processNames = {
    'broadcastingTx': gettext('Broadcasting transaction'),
    'calculatingFee': gettext('Calculating fee'),
    'connectingCoinbase': gettext('Connecting to Coinbase...'),
    'connectingGlidera': gettext('Connecting to Glidera...'),
    'connectingledger': gettext('Waiting for Ledger...'),
    'connectingShapeshift': gettext('Connecting to Shapeshift...'),
    'connectingtrezor': gettext('Waiting for Trezor...'),
    'creatingTx': gettext('Creating transaction'),
    'creatingWallet': gettext('Creating Wallet...'),
    'deletingWallet': gettext('Deleting Wallet...'),
    'extractingWalletInfo': gettext('Extracting Wallet information...'),
    'fetchingPayPro': gettext('Fetching payment information'),
    'generatingCSV': gettext('Generating .csv file...'),
    'gettingFeeLevels': gettext('Getting fee levels...'),
    'importingWallet': gettext('Importing Wallet...'),
    'joiningWallet': gettext('Joining Wallet...'),
    'recreating': gettext('Recreating Wallet...'),
    'rejectTx': gettext('Rejecting payment proposal'),
    'removeTx': gettext('Deleting payment proposal'),
    'retrievingInputs': gettext('Retrieving inputs information'),
    'scanning': gettext('Scanning Wallet funds...'),
    'sendingTx': gettext('Sending transaction'),
    'signingTx': gettext('Signing transaction'),
    'sweepingWallet': gettext('Sweeping Wallet...'),
    'validatingWords': gettext('Validating recovery phrase...'),
    'loadingTxInfo': gettext('Loading transaction info...'),
    'sendingFeedback': gettext('Sending feedback...'),
    'generatingNewAddress': gettext('Generating new address...'),
    'sendingByEmail': gettext('Preparing addresses...'),
    'sending2faCode': gettext('Sending 2FA code...'),
    'buyingBitcoin': gettext('Buying Bitcoin...'),
    'sellingBitcoin': gettext('Selling Bitcoin...'),
    'fetchingBitPayAccount': gettext('Fetching BitPay Account...'),
    'updatingGiftCards': 'Updating Gift Cards...',
    'updatingGiftCard': 'Updating Gift Card...',
    'cancelingGiftCard': 'Canceling Gift Card...',
    'creatingGiftCard': 'Creating Gift Card...',
    'buyingGiftCard': 'Buying Gift Card...',
    'topup': gettext('Top up in progress...'),
    'duplicatingWallet': gettext('Duplicating wallet...'),
  };

  root.clear = function() {
    ongoingProcess = {};
    if (isCordova && !isWindowsPhoneApp) {
      window.plugins.spinnerDialog.hide();
    } else {
      $ionicLoading.hide();
    }
  };

  root.get = function(processName) {
    return ongoingProcess[processName];
  };

  root.set = function(processName, isOn, customHandler) {
    $log.debug('ongoingProcess', processName, isOn);
    root[processName] = isOn;
    ongoingProcess[processName] = isOn;

    var name;
    root.any = lodash.any(ongoingProcess, function(isOn, processName) {
      if (isOn)
        name = name || processName;
      return isOn;
    });
    // The first one
    root.onGoingProcessName = name;

    var showName = $filter('translate')(processNames[name] || name);

    if (customHandler) {
      customHandler(processName, showName, isOn);
    } else if (root.onGoingProcessName) {
      if (isCordova && !isWindowsPhoneApp) {
        window.plugins.spinnerDialog.show(null, showName, root.clear);
      } else {

        var tmpl;
        if (isWindowsPhoneApp) tmpl = '
' + showName + '
';
        else tmpl = '
' + showName + '<ion-spinner class="spinner-stable" icon="lines"></ion-spinner>
';
        $ionicLoading.show({
          template: tmpl
        });
      }
    } else {
      if (isCordova && !isWindowsPhoneApp) {
        window.plugins.spinnerDialog.hide();
      } else {
        $ionicLoading.hide();
      }
    }
  };

  return root;
});
<commit_msg>using ionicModal for all devices<commit_after>'use strict';

angular.module('copayApp.services').factory('ongoingProcess', function($log, $timeout, $filter, lodash, $ionicLoading, gettext, platformInfo) {
  var root = {};
  var isCordova = platformInfo.isCordova;
  var isWindowsPhoneApp = platformInfo.isCordova && platformInfo.isWP;

  var ongoingProcess = {};

  var processNames = {
    'broadcastingTx': gettext('Broadcasting transaction'),
    'calculatingFee': gettext('Calculating fee'),
    'connectingCoinbase': gettext('Connecting to Coinbase...'),
    'connectingGlidera': gettext('Connecting to Glidera...'),
    'connectingledger': gettext('Waiting for Ledger...'),
    'connectingShapeshift': gettext('Connecting to Shapeshift...'),
    'connectingtrezor': gettext('Waiting for Trezor...'),
    'creatingTx': gettext('Creating transaction'),
    'creatingWallet': gettext('Creating Wallet...'),
    'deletingWallet': gettext('Deleting Wallet...'),
    'extractingWalletInfo': gettext('Extracting Wallet information...'),
    'fetchingPayPro': gettext('Fetching payment information'),
    'generatingCSV': gettext('Generating .csv file...'),
    'gettingFeeLevels': gettext('Getting fee levels...'),
    'importingWallet': gettext('Importing Wallet...'),
    'joiningWallet': gettext('Joining Wallet...'),
    'recreating': gettext('Recreating Wallet...'),
    'rejectTx': gettext('Rejecting payment proposal'),
    'removeTx': gettext('Deleting payment proposal'),
    'retrievingInputs': gettext('Retrieving inputs information'),
    'scanning': gettext('Scanning Wallet funds...'),
    'sendingTx': gettext('Sending transaction'),
    'signingTx': gettext('Signing transaction'),
    'sweepingWallet': gettext('Sweeping Wallet...'),
    'validatingWords': gettext('Validating recovery phrase...'),
    'loadingTxInfo': gettext('Loading transaction info...'),
    'sendingFeedback': gettext('Sending feedback...'),
    'generatingNewAddress': gettext('Generating new address...'),
    'sendingByEmail': gettext('Preparing addresses...'),
    'sending2faCode': gettext('Sending 2FA code...'),
    'buyingBitcoin': gettext('Buying Bitcoin...'),
    'sellingBitcoin': gettext('Selling Bitcoin...'),
    'fetchingBitPayAccount': gettext('Fetching BitPay Account...'),
    'updatingGiftCards': 'Updating Gift Cards...',
    'updatingGiftCard': 'Updating Gift Card...',
    'cancelingGiftCard': 'Canceling Gift Card...',
    'creatingGiftCard': 'Creating Gift Card...',
    'buyingGiftCard': 'Buying Gift Card...',
    'topup': gettext('Top up in progress...'),
    'duplicatingWallet': gettext('Duplicating wallet...'),
  };

  root.clear = function() {
    ongoingProcess = {};
    if (isCordova && !isWindowsPhoneApp) {
      window.plugins.spinnerDialog.hide();
    } else {
      $ionicLoading.hide();
    }
  };

  root.get = function(processName) {
    return ongoingProcess[processName];
  };

  root.set = function(processName, isOn, customHandler) {
    $log.debug('ongoingProcess', processName, isOn);
    root[processName] = isOn;
    ongoingProcess[processName] = isOn;

    var name;
    root.any = lodash.any(ongoingProcess, function(isOn, processName) {
      if (isOn)
        name = name || processName;
      return isOn;
    });
    // The first one
    root.onGoingProcessName = name;

    var showName = $filter('translate')(processNames[name] || name);

    if (customHandler) {
      customHandler(processName, showName, isOn);
    } else if (root.onGoingProcessName) {
      var tmpl;
      if (isWindowsPhoneApp) tmpl = '
' + showName + '
';
      else tmpl = '
' + showName + '<ion-spinner class="spinner-stable" icon="lines"></ion-spinner>
';
      $ionicLoading.show({
        template: tmpl,
      });
    } else {
      if (isCordova && !isWindowsPhoneApp) {
        window.plugins.spinnerDialog.hide();
      } else {
        $ionicLoading.hide();
      }
    }
  };

  return root;
});
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var nlp = require("./nlp");
var newBot = require("./newBot");
var push = require("./push");
var logConv = require("./log").logConversation;
//var findSession = require("./sessionsearch");

const scriptRules = require('./script.json');

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello!  I\'m A16, the Agile2016 EventBot Concierge.  To find out what I can help you with type MENU for options or KEY for Keywords.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {

            console.log("- bot message ", message);
            console.log("processID", process.pid);

            //exit right away
//            if (message.mediaType) {
//              return bot.say("I'm sorry I don't know how to respond to media yet.  😳   Type MENU or KEY for a list of things I can help you with.")
//                .then(() => 'speak');
//            }

            let upperText = message.text.trim().toUpperCase();

            //This is in case a user uses the bots name in a request
            //console.log("before a16 search ", upperText.indexOf("A16"), upperText.length);
            if ((upperText.indexOf(process.env.BOT_NAME)  > -1)  && (upperText.length > 4)) {
              upperText = upperText.replace(process.env.BOT_NAME, "");
            }

            var msgLog = {
                smoochId: '',
                received: '',
                usermessage: '',
                role: '',
                message_id: '',
                sourcetype: '',
                receivedtime: '',
                responsemessage: '',
                responsetype: '',
                responsetime: ''
              };

            //create message log to pesist in db
            msgLog.smoochId = bot.userId;
            msgLog.received = message.received;
            msgLog.usermessage = message.text;
            msgLog.role = message.role;
            msgLog.message_id = message._id;
            msgLog.receivedtime = new Date;
            if (typeof message.message !== "undefined") {
              //postback
              msgLog.sourcetype = message.action.type;
            } else {
              // This is appUser - which means it is a message typed in by the user
              msgLog.sourcetype = message.source.type;
            }

            //SK_ACCESS is a heroku config var that has the list of user/platform
            //smoochids for users to send ad hoc push conversations
            if (upperText.substr(0,4) == '/SK ') {
              adhocMsg();
            }

            function adhocMsg() {
              var authUsers = process.env.SK_ACCESS;
              //For ad hoc messages - scheduled messages are done differently in checkItems
              //-1 indicates that a user is not authorized to send broadcast messages
              if (authUsers.indexOf(bot.userId) !== -1) {
                upperText = upperText.substr(0,3);
                newBot('adhoc',process.env.ADHOC_PREFIX + message.text.substr(4));
                console.log("- ad hoc msg: ",message.text," authUser:  ",authUsers);
                msgLog.responsemessage = upperText;
                msgLog.responsetype = "adhoc msg";
                //return jResponse();
              } else {
                upperText = "NO_SK";
              }
            }

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        //console.log('- Special Case: CONNECT ME'); //turns off bot
                        return bot.setProp("silent", true);
                    case "/NOTIFY":
                        //console.log('- Special Case: /NOTIFY'); //turns off bot
                        bot.say("I have notified the Agile2016 human team that you have requested help. They usually respond in less than 5 minutes during conference hours. You are now in live support mode and when you are ready to chat with me again tap the button or type /A16. %[Return](postback:/A16)").then(() => 'speak');
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        //console.log('- Special Case: DISCONNECT'); //turns bot back on
                        return bot.setProp("silent", false);
                    case "/A16":
                        //console.log('- Special Case: /A16'); //turns bot back on
                        bot.say("A16 is back! I hope my human colleagues were able to help you.").then(() => 'speak');
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            function getSilent() {
                return bot.getProp("silent");
            }

            function apiMessage() {
              //prepare to send to API.ai
              console.log("in apiMessage");
              var promises = [];
              var source;
              var fulfillmentSpeech;
              var simplified;
              //To better pass to API.AI does not deal with '/' well
              if (upperText.match(/7\/2[456789]/g)) {
                upperText = upperText.replace("/", " ");
              }

              promises.push(nlp(upperText, bot.userId));

              Q.all(promises).then(function(responses) {
                responses.forEach(function(response) {
                  console.log("- In Q.all");
                  console.log("- Received result from API.ai",response);
                  source = response.result.source;
                  msgLog.responsemessage = response.result.fulfillment.speech;

                  if (source === 'domains') {
                    console.log("apiMessage - domains");
                    console.log("- In domains, switch default");
                    //console.log("what is simplified", response.result.parameters.simplified);
                    //if (response.result.parameters.simplified = "hello") {
                    //  console.log("are you here?");
                    //  upperText = "HELLO"
                    //  return jResponse();
                    //}
                    msgLog.responsetype = 'API.ai domains';
                    logConv(msgLog);
                    console.log("- in domains msg logged", msgLog.responsemessage);
                    return bot.say(msgLog.responsemessage).then(() => 'speak');
                  } else if (msgLog.responsemessage) {
                    console.log("- In agent,",simplified);
                    upperText = response.result.action;
                    msgLog.responsetype = 'API.ai agent';
                    return jResponse();
                  } else {
                    msgLog.responsetype = 'No match';
                    logConv(msgLog);
                    return bot.say(`I'm sorry that is not something I know.  😳   Type MENU or KEY for a list of things I can help you with.`).then(() => 'speak');
                  }
                });
              }, function(error) {
                  console.log("- Q.all error: ", error);
              });
            }

            function processMessage(isSilent){
                if (isSilent) {
                    return Promise.resolve("speak");
                }
                if (!_.has(scriptRules, upperText))
                {
                  console.log("ProcessMessage no ", upperText);
                  apiMessage();
                } else {
                  console.log("processMessage has rule");
                  msgLog.responsetype = 'JSON';
                  jResponse();
                }
            }

            function jResponse() {
                var response = scriptRules[upperText];
                var lines = response.split('\n');
                console.log("=== msgLog  obj",msgLog);

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log("- p line",line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });
                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage)
                .then(msgLog.responsetime = new Date)
                .then(logConv(msgLog));
;
        }
    }
});
<commit_msg>date change<commit_after>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var nlp = require("./nlp");
var newBot = require("./newBot");
var push = require("./push");
var logConv = require("./log").logConversation;
//var findSession = require("./sessionsearch");

const scriptRules = require('./script.json');

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello!  I\'m A16, the Agile2016 EventBot Concierge.  To find out what I can help you with type MENU for options or KEY for Keywords.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {

            console.log("- bot message ", message);
            console.log("processID", process.pid);

            //exit right away
//            if (message.mediaType) {
//              return bot.say("I'm sorry I don't know how to respond to media yet.  😳   Type MENU or KEY for a list of things I can help you with.")
//                .then(() => 'speak');
//            }

            let upperText = message.text.trim().toUpperCase();

            //This is in case a user uses the bots name in a request
            //console.log("before a16 search ", upperText.indexOf("A16"), upperText.length);
            if ((upperText.indexOf(process.env.BOT_NAME)  > -1)  && (upperText.length > 4)) {
              upperText = upperText.replace(process.env.BOT_NAME, "");
            }

            var msgLog = {
                smoochId: '',
                received: '',
                usermessage: '',
                role: '',
                message_id: '',
                sourcetype: '',
                receivedtime: '',
                responsemessage: '',
                responsetype: '',
                responsetime: ''
              };

            //create message log to pesist in db
            msgLog.smoochId = bot.userId;
            msgLog.received = message.received;
            msgLog.usermessage = message.text;
            msgLog.role = message.role;
            msgLog.message_id = message._id;
            msgLog.receivedtime = new Date();
            if (typeof message.message !== "undefined") {
              //postback
              msgLog.sourcetype = message.action.type;
            } else {
              // This is appUser - which means it is a message typed in by the user
              msgLog.sourcetype = message.source.type;
            }

            //SK_ACCESS is a heroku config var that has the list of user/platform
            //smoochids for users to send ad hoc push conversations
            if (upperText.substr(0,4) == '/SK ') {
              adhocMsg();
            }

            function adhocMsg() {
              var authUsers = process.env.SK_ACCESS;
              //For ad hoc messages - scheduled messages are done differently in checkItems
              //-1 indicates that a user is not authorized to send broadcast messages
              if (authUsers.indexOf(bot.userId) !== -1) {
                upperText = upperText.substr(0,3);
                newBot('adhoc',process.env.ADHOC_PREFIX + message.text.substr(4));
                console.log("- ad hoc msg: ",message.text," authUser:  ",authUsers);
                msgLog.responsemessage = upperText;
                msgLog.responsetype = "adhoc msg";
                //return jResponse();
              } else {
                upperText = "NO_SK";
              }
            }

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        //console.log('- Special Case: CONNECT ME'); //turns off bot
                        return bot.setProp("silent", true);
                    case "/NOTIFY":
                        //console.log('- Special Case: /NOTIFY'); //turns off bot
                        bot.say("I have notified the Agile2016 human team that you have requested help. They usually respond in less than 5 minutes during conference hours. You are now in live support mode and when you are ready to chat with me again tap the button or type /A16. %[Return](postback:/A16)").then(() => 'speak');
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        //console.log('- Special Case: DISCONNECT'); //turns bot back on
                        return bot.setProp("silent", false);
                    case "/A16":
                        //console.log('- Special Case: /A16'); //turns bot back on
                        bot.say("A16 is back! I hope my human colleagues were able to help you.").then(() => 'speak');
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            function getSilent() {
                return bot.getProp("silent");
            }

            function apiMessage() {
              //prepare to send to API.ai
              console.log("in apiMessage");
              var promises = [];
              var source;
              var fulfillmentSpeech;
              var simplified;
              //To better pass to API.AI does not deal with '/' well
              if (upperText.match(/7\/2[456789]/g)) {
                upperText = upperText.replace("/", " ");
              }

              promises.push(nlp(upperText, bot.userId));

              Q.all(promises).then(function(responses) {
                responses.forEach(function(response) {
                  console.log("- In Q.all");
                  console.log("- Received result from API.ai",response);
                  source = response.result.source;
                  msgLog.responsemessage = response.result.fulfillment.speech;

                  if (source === 'domains') {
                    console.log("apiMessage - domains");
                    console.log("- In domains, switch default");
                    //console.log("what is simplified", response.result.parameters.simplified);
                    //if (response.result.parameters.simplified = "hello") {
                    //  console.log("are you here?");
                    //  upperText = "HELLO"
                    //  return jResponse();
                    //}
                    msgLog.responsetype = 'API.ai domains';
                    logConv(msgLog);
                    console.log("- in domains msg logged", msgLog.responsemessage);
                    return bot.say(msgLog.responsemessage).then(() => 'speak');
                  } else if (msgLog.responsemessage) {
                    console.log("- In agent,",simplified);
                    upperText = response.result.action;
                    msgLog.responsetype = 'API.ai agent';
                    return jResponse();
                  } else {
                    msgLog.responsetype = 'No match';
                    logConv(msgLog);
                    return bot.say(`I'm sorry that is not something I know.  😳   Type MENU or KEY for a list of things I can help you with.`).then(() => 'speak');
                  }
                });
              }, function(error) {
                  console.log("- Q.all error: ", error);
              });
            }

            function processMessage(isSilent){
                if (isSilent) {
                    return Promise.resolve("speak");
                }
                if (!_.has(scriptRules, upperText))
                {
                  console.log("ProcessMessage no ", upperText);
                  apiMessage();
                } else {
                  console.log("processMessage has rule");
                  msgLog.responsetype = 'JSON';
                  jResponse();
                }
            }

            function jResponse() {
                var response = scriptRules[upperText];
                var lines = response.split('\n');
                console.log("=== msgLog  obj",msgLog);

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log("- p line",line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });
                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage)
                .then(msgLog.responsetime = new Date())
                .then(logConv(msgLog));
;
        }
    }
});
<|endoftext|>


<commit_before>/**
 * qUnitScraper object
 */
var qUnitScraper = {
    /**
     * Start here!
     * This is the first method to invoke to call other method.
     * Currently it can only does the call to other methods and doesn't do any processing here.
     * It then should return all the failed modules in object format back to caller.
     *
     * @params : none
     * @return : (object) the object listing all the failed modules along with their information
     */
    init: function() {
        // validate page here

        var results = this._readResults();
        return( results );
    },
    /**
     * _readResults create a jQuery object, selecting output listing.
     * Currently it's looking only for the failed modules, but could be
     * extended to specify which to look for.
     * It calls other methods to get the information it needs and returns an object
     * listing each method indexed by the method number as displayed to user.
     *
     * @params : none
     * @return : (object) listing all the failed modules along with their information.
     */
    _readResults: function( ) {
        var modules = jQuery("#qunit-tests .fail[id^=qunit-test-output]");
        var moduleResults = [];

        var numModules = modules.length;
        for( var moduleNumber=0; moduleNumber < numModules; moduleNumber++ )
        {
            var thisModule = modules[moduleNumber];
            moduleResults["module " + this._getModuleNumber(jQuery(thisModule))] = this._readModule( thisModule );
        }

        return moduleResults;
    },
    /**
     * This method takes jQuery object of the modules we want to read.
     * It then searches for the assert list result, currently the failed ones.
     * Like _readResults, it could be extended.
     * The method puts together the list found, builds an object including the name, message and source
     * and returns it.
     *
     * @params : (object) jQuery object of the module we want to read
     * @return : (object) an object with 2 properties, name of test and another object listing the tests
     */
    _readModule: function( module ) {
        var tests   = jQuery(".qunit-assert-list .fail", module);
        var testResults = {
            "name" : jQuery(".module-name", module).html() + ": " + jQuery(".test-name", module).html(),
            "tests": []
        };

        var numTests = tests.length;
        for( var testNumber=0; testNumber < numTests; testNumber++ ) {
            var thisTest = tests[testNumber];
            testResults["tests"].push({
                "message": jQuery(".test-message", thisTest).html(),
                "source" : jQuery(".test-source pre", thisTest).html()
            });
        }

        return testResults;
    },
    /**
     * This one takes a jQuery object of the module we want to find the number.
     * Performs a regex match over the id of the DOM which includes an index at the very end.
     * Lastly, we add 1 to the number since the ID is 0-indexed vs the list display to user is 1-indexed.
     *
     * @params : (object) jQuery object of the module element
     * @return : (int) module number as display to users
     */
    _getModuleNumber: function( module ) {
        var id = module.attr( "id" );
        var match = id.match( /\d+$/ )[0];
        return parseInt( match ) + 1 ;
    }
}<commit_msg>Change the module listing from array to object<commit_after>/**
 * qUnitScraper object
 */
var qUnitScraper = {
    /**
     * Start here!
     * This is the first method to invoke to call other method.
     * Currently it can only does the call to other methods and doesn't do any processing here.
     * It then should return all the failed modules in object format back to caller.
     *
     * @params : none
     * @return : (object) the object listing all the failed modules along with their information
     */
    init: function() {
        // validate page here

        var results = this._readResults();
        return( results );
    },
    /**
     * _readResults create a jQuery object, selecting output listing.
     * Currently it's looking only for the failed modules, but could be
     * extended to specify which to look for.
     * It calls other methods to get the information it needs and returns an object
     * listing each method indexed by the method number as displayed to user.
     *
     * @params : none
     * @return : (object) listing all the failed modules along with their information.
     */
    _readResults: function( ) {
        var modules = jQuery("#qunit-tests .fail[id^=qunit-test-output]");
        var moduleResults = {};

        var numModules = modules.length;
        for( var moduleNumber=0; moduleNumber < numModules; moduleNumber++ )
        {
            var thisModule = modules[moduleNumber];
            moduleResults["module " + this._getModuleNumber(jQuery(thisModule))] = this._readModule( thisModule );
        }

        return moduleResults;
    },
    /**
     * This method takes jQuery object of the modules we want to read.
     * It then searches for the assert list result, currently the failed ones.
     * Like _readResults, it could be extended.
     * The method puts together the list found, builds an object including the name, message and source
     * and returns it.
     *
     * @params : (object) jQuery object of the module we want to read
     * @return : (object) an object with 2 properties, name of test and another object listing the tests
     */
    _readModule: function( module ) {
        var tests   = jQuery(".qunit-assert-list .fail", module);
        var testResults = {
            "name" : jQuery(".module-name", module).html() + ": " + jQuery(".test-name", module).html(),
            "tests": []
        };

        var numTests = tests.length;
        for( var testNumber=0; testNumber < numTests; testNumber++ ) {
            var thisTest = tests[testNumber];
            testResults["tests"].push({
                "message": jQuery(".test-message", thisTest).html(),
                "source" : jQuery(".test-source pre", thisTest).html()
            });
        }

        return testResults;
    },
    /**
     * This one takes a jQuery object of the module we want to find the number.
     * Performs a regex match over the id of the DOM which includes an index at the very end.
     * Lastly, we add 1 to the number since the ID is 0-indexed vs the list display to user is 1-indexed.
     *
     * @params : (object) jQuery object of the module element
     * @return : (int) module number as display to users
     */
    _getModuleNumber: function( module ) {
        var id = module.attr( "id" );
        var match = id.match( /\d+$/ )[0];
        return parseInt( match ) + 1 ;
    }
}<|endoftext|>


<commit_before>window.onload = function() {
  'use strict';

  // create a scene
  var scn = new DivSugar.Scene().setSize(800, 600).setImage('#004000').appendTo(document.body);

  // maximize the scene size
  window.onresize = function() { scn.adjustLayout(window.innerWidth, window.innerHeight, 'contain'); };
  window.onresize();

  //
  // create a parent node used as the center of rotation
  var node1 = new DivSugar.Node().setPosition(400, 300, 0).appendTo(scn);

  // create a child node which renders an image and a text
  var node2 = new DivSugar.Node().setSize(300, 300).setPosition(-150, -150, 0).setImage('../assets/kitten.jpg').appendTo(node1);

  // TBD
  var task = new DivSugar.Task().appendTo(DivSugar.rootTask);
  var curX, curY, lastX, lastY, rotX, rotY;
  var pos = new DivSugar.Vector();
  var mat = new DivSugar.Matrix();
  var origin = new DivSugar.Matrix();

  var vec = new DivSugar.Vector();

  task.onUpdate = function() {
    if (DivSugar.getMouseState('pressed')) {
      lastX = DivSugar.getMouseX();
      lastY = DivSugar.getMouseY();
    }

    if (DivSugar.getMouseState('on')) {
      curX = DivSugar.getMouseX();
      curY = DivSugar.getMouseY();

      rotX = -(curY - lastY) * this.deltaTime * 0.04;
      rotY = (curX - lastX) * this.deltaTime * 0.04;

      node1.rotateAround(DivSugar.Vector.X_UNIT, rotX);
      node1.rotateAround(DivSugar.Vector.Y_UNIT, rotY);

      lastX = curX;
      lastY = curY;

      scn.getLocalPosition(curX, curY, vec);
    }

    if (DivSugar.getMouseState('released')) {
    }
  };
};
<commit_msg>Adapted to the new API<commit_after>window.onload = function() {
  'use strict';

  // create a scene
  var scn = new DivSugar.Scene().setSize(800, 600).setImage('#004000').appendTo(document.body);

  // maximize the scene size
  window.onresize = function() { scn.adjustLayout(window.innerWidth, window.innerHeight, 'contain'); };
  window.onresize();

  //
  // create a parent node used as the center of rotation
  var node1 = new DivSugar.Node().setPosition(400, 300, 0).appendTo(scn);

  // create a child node which renders an image and a text
  var node2 = new DivSugar.Node().setSize(300, 300).setPosition(-150, -150, 0).setImage('../assets/kitten.jpg').appendTo(node1);

  // TBD
  var task = new DivSugar.Task().appendTo(DivSugar.rootTask);
  var curX, curY, lastX, lastY, rotX, rotY;
  var pos = new DivSugar.Vector();
  var mat = new DivSugar.Matrix();
  var origin = new DivSugar.Matrix();

  var vec = new DivSugar.Vector();

  task.onUpdate = function() {
    if (DivSugar.getMouseState(0, 'pressed')) {
      lastX = DivSugar.getMouseX();
      lastY = DivSugar.getMouseY();
    }

    if (DivSugar.getMouseState(0, 'on')) {
      curX = DivSugar.getMouseX();
      curY = DivSugar.getMouseY();

      rotX = -(curY - lastY) * this.deltaTime * 0.04;
      rotY = (curX - lastX) * this.deltaTime * 0.04;

      node1.rotateAround(DivSugar.Vector.X_UNIT, rotX);
      node1.rotateAround(DivSugar.Vector.Y_UNIT, rotY);

      lastX = curX;
      lastY = curY;

      scn.getLocalPosition(curX, curY, vec);
    }

    if (DivSugar.getMouseState(0, 'released')) {
    }
  };
};
<|endoftext|>


<commit_before>//See README.md for a full description.

var xmlhttp = new XMLHttpRequest();
var url = "news.json";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var json = JSON.parse(xmlhttp.responseText);
        displayNews(json);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

$(document).ready(function() {
    function displayNews(news) {
        $('.news').html('
' + news[0].title + '
');
    }
});<commit_msg>JavaScript update.<commit_after>//See README.md for a full description.

$(document).ready(function() {
    var xmlhttp = new XMLHttpRequest();
    var url = "news.json";

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var json = JSON.parse(xmlhttp.responseText);
            displayNews(json);
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();

    function displayNews(news) {
        $('.news').html('
' + news[0].title + '
');
    }
});<|endoftext|>


<commit_before>$(function() {
  // build navigation
  var $navRoot = $('#sidebar'), $navParent = null;
  $('content > section, content > section > section').each(function(i, $el) {
    if ($el.id) {
      var $titleEl = $('h2,h3', $el).eq(0);
      var $li = $('<li />').append(
        $('<a />').attr('href', '#' + $el.id).text($titleEl.text())
      );
      var $parent;

      if ($titleEl.is('h2')) {
        $parent = $navRoot;
        $navParent = $li;
      } else {
        if ($navParent.is('li')) {
          var $ul = $('<ul />').attr('class', 'nav nav-stacked');
          $navParent.append($ul);
          $navParent = $ul;
        }

        $parent = $navParent;
      }

      $parent.append($li);
    }
  });
  $('body').scrollspy({
    target: '.navsidebar',
    offset: 40
  });

  // build packet table of contents
  var rows = [];
  $('#packet-types section > section').each(function(i, $el) {
    if ($el.id) {
      var $titleEl = $('h3', $el).eq(0);
      var $props = $('.pkt-props', $el);
      var $types = $props.children('code');
      var whoFrom = $props.children('span').text();
      var mainType = $types.eq(0).text();

      var $link = $('<a />').attr('href', '#' + $el.id).text($titleEl.text());
      if ($titleEl.hasClass('removed')) $link.addClass('removed');

      var $row = $('<tr />').append(
        $('<td />').append($link),
        $('<td />').text(whoFrom),
        $('<td />').append(
          $('<code />').text(mainType)
        )
      );

      if ($types.length > 1) {
        var $subTypeCode = $('<code />').text($types.eq(1).text());
        $row.append(
          $('<td />').append($subTypeCode)
        );

        if ($types.length > 2) {
          $subTypeCode.after('-',
            $('<code />').text($types.eq(2).text())
          );
        }
      } else $row.append('<td />');

      rows.push($row);
    }
  });

  // sort packet list by (direction, major, minor)
  rows.sort(function(a, b) {
    var text_a = a[0].cells[1].innerText + a[0].cells[2].innerText + a[0].cells[3].innerText;
    var text_b = b[0].cells[1].innerText + b[0].cells[2].innerText + b[0].cells[3].innerText;
    return text_a.localeCompare(text_b);
  });

  // add sorted packet list to body
  var $packetTable = $('#packet-table tbody');
  $(rows).each(function(i, el) {
    $packetTable.append(el);
  });
});
<commit_msg>Updated script for internal type names<commit_after>$(function() {
  var INTERNAL_NAMES = {
    '0351a5ac': 'valueFloat',
    '077e9f3c': 'shipSystemSync',
    '19c6e2d4': 'clientConsoles',
    '26faacb9': 'gmButton',
    '3de66711': 'startGame',
    '4c821d3c': 'valueInt',
    '574c4c4b': 'commsMessage',
    '69cc01d9': 'valueFourInts',
    '6aadc57f': 'controlMessage',
    '6d04b3da': 'plainTextGreeting',
    '80803df9': 'objectBitStream',
    '809305a7': 'gmText',
    '902f0b1a': 'bigMess',
    '9ad1f23b': 'carrierRecord',
    'ae88e058': 'incomingMessage',
    'b83fd2c4': 'attack',
    'c2bee72e': 'beamRequest',
    'cc5a3e30': 'objectDelete',
    'd672c35f': 'commText',
    'e548e74a': 'connected',
    'ee665279': 'objectText',
    'f5821226': 'heartbeat',
    'f754c8fe': 'simpleEvent'
  };
  // build navigation
  var $navRoot = $('#sidebar'), $navParent = null;
  $('content > section, content > section > section').each(function(i, $el) {
    if ($el.id) {
      var $titleEl = $('h2,h3', $el).eq(0);
      var $li = $('<li />').append(
        $('<a />').attr('href', '#' + $el.id).text($titleEl.text())
      );
      var $parent;

      if ($titleEl.is('h2')) {
        $parent = $navRoot;
        $navParent = $li;
      } else {
        if ($navParent.is('li')) {
          var $ul = $('<ul />').attr('class', 'nav nav-stacked');
          $navParent.append($ul);
          $navParent = $ul;
        }

        $parent = $navParent;
      }

      $parent.append($li);
    }
  });
  $('body').scrollspy({
    target: '.navsidebar',
    offset: 40
  });

  // build packet table of contents
  var rows = [];
  $('#packet-types section > section').each(function(i, $el) {
    if ($el.id) {
      var $titleEl = $('h3', $el).eq(0);
      var $props = $('.pkt-props', $el);
      var $types = $props.children('code');
      var whoFrom = $props.children('span').text();
      var mainType = $types.eq(0).text();

      var $link = $('<a />').attr('href', '#' + $el.id).text($titleEl.text());
      if ($titleEl.hasClass('removed')) $link.addClass('removed');

      var $row = $('<tr />').append(
        $('<td />').append($link),
        $('<td />').text(whoFrom),
        $('<td />').append(
          $('<code />').text(mainType)
        ),
        $('<td />').append(
          $('<code />').text(INTERNAL_NAMES[mainType.substr(2)])
        ),
      );

      if ($types.length > 1) {
        var $subTypeCode = $('<code />').text($types.eq(1).text());
        $row.append(
          $('<td />').append($subTypeCode)
        );

        if ($types.length > 2) {
          $subTypeCode.after('-',
            $('<code />').text($types.eq(2).text())
          );
        }
      } else $row.append('<td />');

      rows.push($row);
    }
  });

  // sort packet list by (direction, major, minor)
  rows.sort(function(a, b) {
    var text_a = a[0].cells[1].innerText + a[0].cells[2].innerText + a[0].cells[3].innerText;
    var text_b = b[0].cells[1].innerText + b[0].cells[2].innerText + b[0].cells[3].innerText;
    return text_a.localeCompare(text_b);
  });

  // add sorted packet list to body
  var $packetTable = $('#packet-table tbody');
  $(rows).each(function(i, el) {
    $packetTable.append(el);
  });
});
<|endoftext|>


<commit_before>(function() {
var
	main = document.querySelector("main"),
	itemsPocket = document.querySelector("#items #items-pockets"),
	itemsAround = document.querySelector("#items #items-around"),

	type_timeout,
	startDelay = 2500,
	scrollCheckerDelay = 5000,

	typeVariability = 3,
	speedUp = 0.5,

	errorCharProbability = 0.01,
	longChar = 500,
	mediumChar = 200,
	shortChar = 50,
$;

/**
 * Shorthand function for XMLHttpRequest.
 */
function x(method, command, obj, callback) {
	var
		xhr = new XMLHttpRequest(),
		url = command + ".php",
	$;

	xhr.open(method, url, true);
	xhr.addEventListener("load", callback);

	xhr.setRequestHeader("Accept", "application/json");
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

	xhr.send(obj);
}

function newParagraph() {
	var p = document.createElement("p");
	p.classList.add("stale");
	main.appendChild(p);

	return p;
}

function scrollChecker() {
	var
		p = main.lastChild,
		y = p.offsetTop + p.offsetHeight - main.scrollTop,
	$;
	// Check that the paragraph is nearing the bottom of the screen.
	if(y > window.innerHeight * 0.6) {
		scrollMain();
	}
	else {
		setTimeout(scrollChecker, scrollCheckerDelay);
	}
}

function scrollMain(dt) {
	var
		currentScroll = main.scrollTop++,
	$;

	if(main.scrollTop != currentScroll) {
		requestAnimationFrame(scrollMain);
	}
}

/**
 * Self-invoking function used to initiate typing a message to the main output.
 */
function type(msg, addTo, delay) {
	var
		chars = (msg instanceof Array)
			? msg
			: msg.split(""),
		c,
		t,
	$;

	if(!addTo) {
		addTo = newParagraph();
	}

	if(delay) {
		type_timeout = setTimeout(function() {
			type(msg, addTo);
		}, delay);

		return;
	}

	if(chars[0]
	&& chars[0].charCodeAt(0) >= 97
	&& chars[0].charCodeAt(0) <= 97 + 26) {
		if(Math.random() <= errorCharProbability) {
			addTo.innerHTML += String.fromCharCode(
				Math.round(97 + (Math.random() * 26))
			);

			setTimeout(function() {
				addTo.innerHTML = addTo.innerHTML.substring(0,
					addTo.innerHTML.length - 1);

				setTimeout(function() {
					type(chars, addTo);
				}, mediumChar);
			}, mediumChar)
			return;
		}
	}

	c = chars.shift();

	if(!c) {
		addTo.classList.add("stale");
		update();
		return;
	}

	addTo.innerHTML += c;

	switch(c) {
	case "\n":
		addTo = newParagraph();
		t = mediumChar;
		break;

	case "*":
		addTo = emphasise(addTo, "strong");
		break;

	case "_":
		addTo = emphasise(addTo, "em");
		break;

	case ".":
	case "!":
	case "?":
		addTo.classList.add("stale");
		t = longChar;
		break;

	case ",":
	case ":":
	case ";":
		addTo.classList.add("stale");
		t = mediumChar;
		break;

	default:
		addTo.classList.remove("stale");
		t = shortChar;
		break;
	}

	t = t * (Math.random() * typeVariability);
	t = t * speedUp;

	type_timeout = setTimeout(function() {
		type_timeout = null;
		type(chars, addTo);
	}, t);
}

function emphasise(el, tagName) {
	var
		returnEl = el,
	$;

	el.innerHTML = el.innerHTML.substring(0, el.innerHTML.length - 1);

	if(el.tagName == "P") {
		el = document.createElement(tagName);
		returnEl.appendChild(el);
		returnEl = el;
	}
	else {
		returnEl = el.parentNode;
	}

	return returnEl;
}

/**
 * Return text of a random element of nodeList and remove all elements from
 * their parent.
 */
function randPara(nodeList) {
	var
		i = ~~(Math.random() * nodeList.length),
		t = nodeList[i].innerHTML,
		p = nodeList[0].parentNode,
	$;

	while(p.firstChild) {
		p.removeChild(p.firstChild);
	}

	return t;
}

/**
 * Constructs the 5x5 navigation grid.
 */
function buildNav() {
	var
		x,
		y,
		max = 5,

		ol,
		li,
		button,

		nav = document.querySelector("form nav"),
	$;

	for(y = 1; y <= max; y++) {
		ol = document.createElement("ol");
		nav.appendChild(ol);

		for(x = 1; x <= max; x++) {
			li = document.createElement("li");
			button = document.createElement("button")
			button.disabled = true;
			button.name = "position";
			button.value = (x - 3) + "/" + (y - 3);

			if(x == 3 && y == 3) {
				button.textContent = "Here";
			}

			li.appendChild(button);
			ol.appendChild(li);
		}
	}
}

/**
 * Puts an item or items into your pockets, or in the area around you.
 */
function item_add(name, list, quantity) {
	var
		idName = name.replace(/\s+/g, '-', "-").toLowerCase(),
		li,
		input,
		label,
		id,
	$;

	if(!list) {
		list = itemsPocket;
	}

	id = "item-"
		+ list.getAttribute("data-container")
		+ "-"
		+ idName;

	// Find existing item in the list:
	input = list.querySelector("#" + id)
	if(input) {
		li = input.parentNode;
		label = li.querySelector("label");

		if(!quantity) {
			quantity = 1;
		}
		if(li.hasAttribute("data-quantity")) {
			quantity += +li.getAttribute("data-quantity");
		}

		li.setAttribute("data-quantity", quantity);
	}
	else {
		li = document.createElement("li");
		input = document.createElement("input");
		label = document.createElement("label");

		label.textContent = name;

		li.appendChild(input);
		li.appendChild(label);

		input.id = id;
		input.name = "item-"
			+ list.getAttribute("data-container")
			+ "[]";
		input.value = idName;
		input.type = "checkbox";
		label.setAttribute("for", id);

		if(quantity) {
			li.setAttribute("data-quantity", quantity);
		}

		list.appendChild(li);
	}
}

/**
 * Empties the list of items around.
 */
function items_around_remove() {
	while(itemsAround.firstChild) {
		itemsAround.removeChild(ul.firstChild);
	}
}

/**
 * Converts mousewheel scrolls to horizontal.
 */
function e_scroll_horizontal(e) {
	e.preventDefault();
	this.scrollLeft -= e.wheelDeltaY;
}

function save(callback) {
	x("head", "save", {}, function() {
		save_callback(callback);
	});
}

function save_callback(callback) {
	console.log("Game saved...");

	if(callback) {
		callback();
	}
}

function update(e) {
	if(e) {
		e.preventDefault();
	}

	var
		obj = {},
		method = "get",
	$;

	if(e) {
		method = "post";
		// TODO: Build up obj.
	}

	x(method, "game", obj, update_callback);
}

function update_callback() {
	var
		obj = JSON.parse(this.responseText),
	$;
	console.log(obj);

	if(!localStorage["save-game"]
	|| localStorage["save-game"] < (+new Date) - (1000 * 60) ) {
		localStorage["save-game"] = +new Date;
		save();
	}
}

// On page load, while the first request is being made, a random quote is typed.
type(randPara(main.querySelectorAll("p")), null, startDelay);
buildNav();

itemsPocket.addEventListener("mousewheel", e_scroll_horizontal);
itemsAround.addEventListener("mousewheel", e_scroll_horizontal);
document.forms[0].addEventListener("submit", update);

save();
setTimeout(scrollChecker, scrollCheckerDelay);

})();<commit_msg>Allow user to cancel auto scroller naturally<commit_after>(function() {
var
	main = document.querySelector("main"),
	itemsPocket = document.querySelector("#items #items-pockets"),
	itemsAround = document.querySelector("#items #items-around"),

	type_timeout,
	startDelay = 2500,
	scrollCheckerDelay = 5000,

	typeVariability = 3,
	speedUp = 0.5,

	errorCharProbability = 0.01,
	longChar = 500,
	mediumChar = 200,
	shortChar = 50,
$;

/**
 * Shorthand function for XMLHttpRequest.
 */
function x(method, command, obj, callback) {
	var
		xhr = new XMLHttpRequest(),
		url = command + ".php",
	$;

	xhr.open(method, url, true);
	xhr.addEventListener("load", callback);

	xhr.setRequestHeader("Accept", "application/json");
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

	xhr.send(obj);
}

function newParagraph() {
	var p = document.createElement("p");
	p.classList.add("stale");
	main.appendChild(p);

	return p;
}

function scrollChecker() {
	var
		p = main.lastChild,
		y = p.offsetTop + p.offsetHeight - main.scrollTop,
	$;
	// Check that the paragraph is nearing the bottom of the screen.
	if(y > window.innerHeight * 0.6) {
		scrollMain();
	}
	else {
		setTimeout(scrollChecker, scrollCheckerDelay);
	}
}

function scrollMain(dt) {
	var
		currentScroll = main.scrollTop++,
	$;

	// Disable auto scroller if user has moved the scroll up.
	if(main.hasAttribute("data-scroll")) {
		if(main.scrollTop < main.getAttribute("data-scroll")) {
			setTimeout(scrollChecker, scrollCheckerDelay);
			return;
		}
	}

	if(main.scrollTop != currentScroll) {
		main.setAttribute("data-scroll", main.scrollTop);
		requestAnimationFrame(scrollMain);
	}
	else {
		setTimeout(scrollChecker, scrollCheckerDelay);
	}
}

/**
 * Self-invoking function used to initiate typing a message to the main output.
 */
function type(msg, addTo, delay) {
	var
		chars = (msg instanceof Array)
			? msg
			: msg.split(""),
		c,
		t,
	$;

	if(!addTo) {
		addTo = newParagraph();
	}

	if(delay) {
		type_timeout = setTimeout(function() {
			type(msg, addTo);
		}, delay);

		return;
	}

	if(chars[0]
	&& chars[0].charCodeAt(0) >= 97
	&& chars[0].charCodeAt(0) <= 97 + 26) {
		if(Math.random() <= errorCharProbability) {
			addTo.innerHTML += String.fromCharCode(
				Math.round(97 + (Math.random() * 26))
			);

			setTimeout(function() {
				addTo.innerHTML = addTo.innerHTML.substring(0,
					addTo.innerHTML.length - 1);

				setTimeout(function() {
					type(chars, addTo);
				}, mediumChar);
			}, mediumChar)
			return;
		}
	}

	c = chars.shift();

	if(!c) {
		addTo.classList.add("stale");
		update();
		return;
	}

	addTo.innerHTML += c;

	switch(c) {
	case "\n":
		addTo = newParagraph();
		t = mediumChar;
		break;

	case "*":
		addTo = emphasise(addTo, "strong");
		break;

	case "_":
		addTo = emphasise(addTo, "em");
		break;

	case ".":
	case "!":
	case "?":
		addTo.classList.add("stale");
		t = longChar;
		break;

	case ",":
	case ":":
	case ";":
		addTo.classList.add("stale");
		t = mediumChar;
		break;

	default:
		addTo.classList.remove("stale");
		t = shortChar;
		break;
	}

	t = t * (Math.random() * typeVariability);
	t = t * speedUp;

	type_timeout = setTimeout(function() {
		type_timeout = null;
		type(chars, addTo);
	}, t);
}

function emphasise(el, tagName) {
	var
		returnEl = el,
	$;

	el.innerHTML = el.innerHTML.substring(0, el.innerHTML.length - 1);

	if(el.tagName == "P") {
		el = document.createElement(tagName);
		returnEl.appendChild(el);
		returnEl = el;
	}
	else {
		returnEl = el.parentNode;
	}

	return returnEl;
}

/**
 * Return text of a random element of nodeList and remove all elements from
 * their parent.
 */
function randPara(nodeList) {
	var
		i = ~~(Math.random() * nodeList.length),
		t = nodeList[i].innerHTML,
		p = nodeList[0].parentNode,
	$;

	while(p.firstChild) {
		p.removeChild(p.firstChild);
	}

	return t;
}

/**
 * Constructs the 5x5 navigation grid.
 */
function buildNav() {
	var
		x,
		y,
		max = 5,

		ol,
		li,
		button,

		nav = document.querySelector("form nav"),
	$;

	for(y = 1; y <= max; y++) {
		ol = document.createElement("ol");
		nav.appendChild(ol);

		for(x = 1; x <= max; x++) {
			li = document.createElement("li");
			button = document.createElement("button")
			button.disabled = true;
			button.name = "position";
			button.value = (x - 3) + "/" + (y - 3);

			if(x == 3 && y == 3) {
				button.textContent = "Here";
			}

			li.appendChild(button);
			ol.appendChild(li);
		}
	}
}

/**
 * Puts an item or items into your pockets, or in the area around you.
 */
function item_add(name, list, quantity) {
	var
		idName = name.replace(/\s+/g, '-', "-").toLowerCase(),
		li,
		input,
		label,
		id,
	$;

	if(!list) {
		list = itemsPocket;
	}

	id = "item-"
		+ list.getAttribute("data-container")
		+ "-"
		+ idName;

	// Find existing item in the list:
	input = list.querySelector("#" + id)
	if(input) {
		li = input.parentNode;
		label = li.querySelector("label");

		if(!quantity) {
			quantity = 1;
		}
		if(li.hasAttribute("data-quantity")) {
			quantity += +li.getAttribute("data-quantity");
		}

		li.setAttribute("data-quantity", quantity);
	}
	else {
		li = document.createElement("li");
		input = document.createElement("input");
		label = document.createElement("label");

		label.textContent = name;

		li.appendChild(input);
		li.appendChild(label);

		input.id = id;
		input.name = "item-"
			+ list.getAttribute("data-container")
			+ "[]";
		input.value = idName;
		input.type = "checkbox";
		label.setAttribute("for", id);

		if(quantity) {
			li.setAttribute("data-quantity", quantity);
		}

		list.appendChild(li);
	}
}

/**
 * Empties the list of items around.
 */
function items_around_remove() {
	while(itemsAround.firstChild) {
		itemsAround.removeChild(ul.firstChild);
	}
}

/**
 * Converts mousewheel scrolls to horizontal.
 */
function e_scroll_horizontal(e) {
	e.preventDefault();
	this.scrollLeft -= e.wheelDeltaY;
}

function save(callback) {
	x("head", "save", {}, function() {
		save_callback(callback);
	});
}

function save_callback(callback) {
	console.log("Game saved...");

	if(callback) {
		callback();
	}
}

function update(e) {
	if(e) {
		e.preventDefault();
	}

	var
		obj = {},
		method = "get",
	$;

	if(e) {
		method = "post";
		// TODO: Build up obj.
	}

	x(method, "game", obj, update_callback);
}

function update_callback() {
	var
		obj = JSON.parse(this.responseText),
	$;
	console.log(obj);

	if(!localStorage["save-game"]
	|| localStorage["save-game"] < (+new Date) - (1000 * 60) ) {
		localStorage["save-game"] = +new Date;
		save();
	}
}

// On page load, while the first request is being made, a random quote is typed.
type(randPara(main.querySelectorAll("p")), null, startDelay);
buildNav();

itemsPocket.addEventListener("mousewheel", e_scroll_horizontal);
itemsAround.addEventListener("mousewheel", e_scroll_horizontal);
document.forms[0].addEventListener("submit", update);

save();
setTimeout(scrollChecker, scrollCheckerDelay);

})();<|endoftext|>


<commit_before>/**
 * @preserve EventEmitter v3.0.0
 *
 * Copyright 2011, Oliver Caldwell (olivercaldwell.co.uk)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * https://github.com/Wolfy87/EventEmitter
 */

function EventEmitter() {
	// Initialise the listeners object
	this.listeners = {};
}

/**
 * Event class
 * Contains Event methods and property storage
 *
 * @param {String} type Event type name
 * @param {Function} listener Function to be called when the event is fired
 * @param {Object} scope Object that this should be set to when the listener is called
 * @param {Boolean} once If true then the listener will be removed after the first call
 * @param {Object} instance The parent EventEmitter instance
 */
EventEmitter.prototype.Event = function(type, listener, scope, once, instance) {
	// Store arguments
	this.type = type;
	this.listener = listener;
	this.scope = scope;
	this.once = once;
	this.instance = instance;
};

/**
 * Executes the listener
 *
 * @param {Array} args List of arguments to pass to the listener
 * @return {Boolean} If false then it was a once event
 */
EventEmitter.prototype.Event.prototype.fire = function(args) {
	this.listener.apply(this.scope || this, args || []);

	// Remove the listener if this is a once only listener
	if(this.once) {
		this.instance.removeListener(this.type, this.listener);
		return false;
	}
};

/**
 * Passes every listener for a specified event to a function one at a time
 *
 * @param {String} type Event type name
 * @param {Function} callback Function to pass each listener to
 */
EventEmitter.prototype.eachListener = function(type, callback) {
	// Initialise variables
	var i = null,
		possibleListeners = null;

	// Only loop if the type exists
	if(listeners.hasOwnProperty(type)) {
		possibleListeners = listeners[type];

		for(i = 0; i < possibleListeners.length; i += 1) {
			if(callback.call(instance, possibleListeners[i], i) === false) {
				i -= 1;
			}
		}
	}
};

/**
 * Adds an event listener for the specified event
 *
 * @param {String} type Event type name
 * @param {Function} listener Function to be called when the event is fired
 * @param {Object} scope Object that this should be set to when the listener is called
 * @param {Boolean} once If true then the listener will be removed after the first call
 * @return {Object} The current EventEmitter instance to allow chaining
 */
EventEmitter.prototype.addListener = function(type, listener, scope, once) {
	// Create the listener array if it does not exist yet
	if(!listeners.hasOwnProperty(type)) {
		listeners[type] = [];
	}

	// Push the new event to the array
	listeners[type].push(new instance.Event(type, listener, scope, once));

	// Emit the new listener event
	instance.emit('newListener', type, listener, scope, once);

	// Return the instance to allow chaining
	return instance;
};

/**
 * Alias of the addListener method
 *
 * @param {String} type Event type name
 * @param {Function} listener Function to be called when the event is fired
 * @param {Object} scope Object that this should be set to when the listener is called
 * @param {Boolean} once If true then the listener will be removed after the first call
 */
EventEmitter.prototype.on = EventEmitter.prototype.addListener;

/**
 * Alias of the addListener method but will remove the event after the first use
 *
 * @param {String} type Event type name
 * @param {Function} listener Function to be called when the event is fired
 * @param {Object} scope Object that this should be set to when the listener is called
 * @return {Object} The current EventEmitter instance to allow chaining
 */
EventEmitter.prototype.once = function(type, listener, scope) {
	return instance.addListener(type, listener, scope, true);
};

/**
 * Removes the a listener for the specified event
 *
 * @param {String} type Event type name the listener must have for the event to be removed
 * @param {Function} listener Listener the event must have to be removed
 * @return {Object} The current EventEmitter instance to allow chaining
 */
EventEmitter.prototype.removeListener = function(type, listener) {
	instance.eachListener(type, function(currentListener, index) {
		// If this is the listener, disable it and break out
		if(currentListener.listener === listener) {
			listeners[type].splice(index, 1);
		}
	});

	// Remove the property if there are no more listeners
	if(listeners[type] && listeners[type].length === 0) {
		delete listeners[type];
	}

	// Return the instance to allow chaining
	return instance;
};

/**
 * Removes all listeners for a specified event
 *
 * @param {String} type Event type name to remove all listeners from
 * @return {Object} The current EventEmitter instance to allow chaining
 */
EventEmitter.prototype.removeAllListeners = function(type) {
	if(listeners.hasOwnProperty(type)) {
		delete listeners[type];
	}

	// Return the instance to allow chaining
	return instance;
};

/**
 * Retrieves the array of listeners for a specified event
 *
 * @param {String} type Event type name to return all listeners from
 * @return {Array | Boolean} Will return either an array of listeners or false if there are none
 */
EventEmitter.prototype.listeners = function(type) {
	// Return the array of listeners of false if it does not exist
	if(listeners.hasOwnProperty(type)) {
		return listeners[type];
	}

	return false;
};

/**
 * Emits an event executing all appropriate listeners
 *
 * @param {String} type Event type name to run all listeners from
 * @param {Array} args List of arguments to pass to the listener
 * @return {Object} The current EventEmitter instance to allow chaining
 */
EventEmitter.prototype.emit = function(type, args) {
	instance.eachListener(type, function(currentListener) {
		return currentListener.fire(args);
	});

	// Return the instance to allow chaining
	return instance;
};

// Check for exports
// If found, the class needs to be added to it
// This allows server side JavaScript to use this script
if(typeof exports !== 'undefined') {
	exports.EventEmitter = EventEmitter;
}<commit_msg>Converted the eachListerner method to proto. #9<commit_after>/**
 * @preserve EventEmitter v3.0.0
 *
 * Copyright 2011, Oliver Caldwell (olivercaldwell.co.uk)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * https://github.com/Wolfy87/EventEmitter
 */

function EventEmitter() {
	// Initialise the listeners object
	this.listeners = {};
}

/**
 * Event class
 * Contains Event methods and property storage
 *
 * @param {String} type Event type name
 * @param {Function} listener Function to be called when the event is fired
 * @param {Object} scope Object that this should be set to when the listener is called
 * @param {Boolean} once If true then the listener will be removed after the first call
 * @param {Object} instance The parent EventEmitter instance
 */
EventEmitter.prototype.Event = function(type, listener, scope, once, instance) {
	// Store arguments
	this.type = type;
	this.listener = listener;
	this.scope = scope;
	this.once = once;
	this.instance = instance;
};

/**
 * Executes the listener
 *
 * @param {Array} args List of arguments to pass to the listener
 * @return {Boolean} If false then it was a once event
 */
EventEmitter.prototype.Event.prototype.fire = function(args) {
	this.listener.apply(this.scope || this, args || []);

	// Remove the listener if this is a once only listener
	if(this.once) {
		this.instance.removeListener(this.type, this.listener);
		return false;
	}
};

/**
 * Passes every listener for a specified event to a function one at a time
 *
 * @param {String} type Event type name
 * @param {Function} callback Function to pass each listener to
 */
EventEmitter.prototype.eachListener = function(type, callback) {
	// Initialise variables
	var i = null,
		possibleListeners = null;

	// Only loop if the type exists
	if(this.listeners.hasOwnProperty(type)) {
		possibleListeners = this.listeners[type];

		for(i = 0; i < possibleListeners.length; i += 1) {
			if(callback.call(this, possibleListeners[i], i) === false) {
				i -= 1;
			}
		}
	}
};

/**
 * Adds an event listener for the specified event
 *
 * @param {String} type Event type name
 * @param {Function} listener Function to be called when the event is fired
 * @param {Object} scope Object that this should be set to when the listener is called
 * @param {Boolean} once If true then the listener will be removed after the first call
 * @return {Object} The current EventEmitter instance to allow chaining
 */
EventEmitter.prototype.addListener = function(type, listener, scope, once) {
	// Create the listener array if it does not exist yet
	if(!listeners.hasOwnProperty(type)) {
		listeners[type] = [];
	}

	// Push the new event to the array
	listeners[type].push(new instance.Event(type, listener, scope, once));

	// Emit the new listener event
	instance.emit('newListener', type, listener, scope, once);

	// Return the instance to allow chaining
	return instance;
};

/**
 * Alias of the addListener method
 *
 * @param {String} type Event type name
 * @param {Function} listener Function to be called when the event is fired
 * @param {Object} scope Object that this should be set to when the listener is called
 * @param {Boolean} once If true then the listener will be removed after the first call
 */
EventEmitter.prototype.on = EventEmitter.prototype.addListener;

/**
 * Alias of the addListener method but will remove the event after the first use
 *
 * @param {String} type Event type name
 * @param {Function} listener Function to be called when the event is fired
 * @param {Object} scope Object that this should be set to when the listener is called
 * @return {Object} The current EventEmitter instance to allow chaining
 */
EventEmitter.prototype.once = function(type, listener, scope) {
	return instance.addListener(type, listener, scope, true);
};

/**
 * Removes the a listener for the specified event
 *
 * @param {String} type Event type name the listener must have for the event to be removed
 * @param {Function} listener Listener the event must have to be removed
 * @return {Object} The current EventEmitter instance to allow chaining
 */
EventEmitter.prototype.removeListener = function(type, listener) {
	instance.eachListener(type, function(currentListener, index) {
		// If this is the listener, disable it and break out
		if(currentListener.listener === listener) {
			listeners[type].splice(index, 1);
		}
	});

	// Remove the property if there are no more listeners
	if(listeners[type] && listeners[type].length === 0) {
		delete listeners[type];
	}

	// Return the instance to allow chaining
	return instance;
};

/**
 * Removes all listeners for a specified event
 *
 * @param {String} type Event type name to remove all listeners from
 * @return {Object} The current EventEmitter instance to allow chaining
 */
EventEmitter.prototype.removeAllListeners = function(type) {
	if(listeners.hasOwnProperty(type)) {
		delete listeners[type];
	}

	// Return the instance to allow chaining
	return instance;
};

/**
 * Retrieves the array of listeners for a specified event
 *
 * @param {String} type Event type name to return all listeners from
 * @return {Array | Boolean} Will return either an array of listeners or false if there are none
 */
EventEmitter.prototype.listeners = function(type) {
	// Return the array of listeners of false if it does not exist
	if(listeners.hasOwnProperty(type)) {
		return listeners[type];
	}

	return false;
};

/**
 * Emits an event executing all appropriate listeners
 *
 * @param {String} type Event type name to run all listeners from
 * @param {Array} args List of arguments to pass to the listener
 * @return {Object} The current EventEmitter instance to allow chaining
 */
EventEmitter.prototype.emit = function(type, args) {
	instance.eachListener(type, function(currentListener) {
		return currentListener.fire(args);
	});

	// Return the instance to allow chaining
	return instance;
};

// Check for exports
// If found, the class needs to be added to it
// This allows server side JavaScript to use this script
if(typeof exports !== 'undefined') {
	exports.EventEmitter = EventEmitter;
}<|endoftext|>