(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["ivprogCore"] = factory();
	else
		root["ivprogCore"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = "./js/main.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./grammar/en/ivprog.g4":
/*!******************************!*\
  !*** ./grammar/en/ivprog.g4 ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

// Generated from /tmp/tmp-33441apdS61dR4Pv/ivprog.g4 by ANTLR 4.7
// jshint ignore: start
var antlr4 = __webpack_require__(2);


var serializedATN = ["\u0003\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964",
    "\u0002/\u01d1\b\u0001\u0004\u0002\t\u0002\u0004\u0003\t\u0003\u0004",
    "\u0004\t\u0004\u0004\u0005\t\u0005\u0004\u0006\t\u0006\u0004\u0007\t",
    "\u0007\u0004\b\t\b\u0004\t\t\t\u0004\n\t\n\u0004\u000b\t\u000b\u0004",
    "\f\t\f\u0004\r\t\r\u0004\u000e\t\u000e\u0004\u000f\t\u000f\u0004\u0010",
    "\t\u0010\u0004\u0011\t\u0011\u0004\u0012\t\u0012\u0004\u0013\t\u0013",
    "\u0004\u0014\t\u0014\u0004\u0015\t\u0015\u0004\u0016\t\u0016\u0004\u0017",
    "\t\u0017\u0004\u0018\t\u0018\u0004\u0019\t\u0019\u0004\u001a\t\u001a",
    "\u0004\u001b\t\u001b\u0004\u001c\t\u001c\u0004\u001d\t\u001d\u0004\u001e",
    "\t\u001e\u0004\u001f\t\u001f\u0004 \t \u0004!\t!\u0004\"\t\"\u0004#",
    "\t#\u0004$\t$\u0004%\t%\u0004&\t&\u0004\'\t\'\u0004(\t(\u0004)\t)\u0004",
    "*\t*\u0004+\t+\u0004,\t,\u0004-\t-\u0004.\t.\u0004/\t/\u00040\t0\u0004",
    "1\t1\u00042\t2\u00043\t3\u00044\t4\u00045\t5\u00046\t6\u00047\t7\u0004",
    "8\t8\u00049\t9\u0003\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003",
    "\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003\u0003\u0003\u0003\u0003",
    "\u0003\u0003\u0003\u0003\u0003\u0003\u0004\u0003\u0004\u0003\u0004\u0003",
    "\u0004\u0003\u0004\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003",
    "\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0006\u0003\u0006\u0003",
    "\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0007\u0003",
    "\u0007\u0003\u0007\u0003\u0007\u0003\u0007\u0003\u0007\u0003\u0007\u0003",
    "\u0007\u0003\b\u0003\b\u0003\b\u0003\b\u0003\b\u0003\b\u0003\b\u0003",
    "\b\u0003\b\u0003\b\u0003\t\u0003\t\u0003\t\u0003\t\u0003\t\u0003\t\u0003",
    "\t\u0003\n\u0003\n\u0003\n\u0003\n\u0003\n\u0003\u000b\u0003\u000b\u0003",
    "\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003",
    "\u000b\u0003\u000b\u0003\f\u0003\f\u0003\f\u0003\f\u0003\f\u0003\f\u0003",
    "\r\u0003\r\u0003\r\u0003\r\u0003\r\u0003\r\u0003\r\u0003\r\u0003\r\u0003",
    "\u000e\u0003\u000e\u0003\u000e\u0003\u000e\u0003\u000e\u0003\u000e\u0003",
    "\u000e\u0003\u000f\u0003\u000f\u0003\u000f\u0003\u000f\u0003\u0010\u0003",
    "\u0010\u0003\u0010\u0003\u0010\u0003\u0010\u0003\u0010\u0003\u0011\u0003",
    "\u0011\u0003\u0011\u0003\u0012\u0003\u0012\u0003\u0012\u0003\u0012\u0003",
    "\u0012\u0003\u0012\u0003\u0013\u0003\u0013\u0003\u0013\u0003\u0014\u0003",
    "\u0014\u0003\u0014\u0003\u0014\u0003\u0014\u0003\u0015\u0003\u0015\u0003",
    "\u0015\u0003\u0015\u0003\u0015\u0003\u0015\u0003\u0016\u0003\u0016\u0003",
    "\u0016\u0003\u0016\u0003\u0016\u0003\u0017\u0003\u0017\u0003\u0017\u0003",
    "\u0017\u0003\u0018\u0003\u0018\u0003\u0018\u0003\u0018\u0003\u0019\u0003",
    "\u0019\u0003\u0019\u0003\u001a\u0003\u001a\u0003\u001b\u0003\u001b\u0003",
    "\u001c\u0003\u001c\u0003\u001d\u0003\u001d\u0003\u001e\u0003\u001e\u0003",
    "\u001f\u0003\u001f\u0003 \u0003 \u0003!\u0003!\u0003\"\u0003\"\u0003",
    "#\u0003#\u0003$\u0003$\u0003%\u0003%\u0003&\u0003&\u0003&\u0003&\u0003",
    "&\u0003&\u0003&\u0003&\u0003&\u0005&\u0125\n&\u0003\'\u0003\'\u0003",
    "(\u0003(\u0003)\u0003)\u0007)\u012d\n)\f)\u000e)\u0130\u000b)\u0003",
    "*\u0003*\u0003*\u0003*\u0003+\u0006+\u0137\n+\r+\u000e+\u0138\u0003",
    "+\u0003+\u0003+\u0003+\u0005+\u013f\n+\u0003+\u0006+\u0142\n+\r+\u000e",
    "+\u0143\u0003+\u0003+\u0003+\u0003+\u0005+\u014a\n+\u0003+\u0006+\u014d",
    "\n+\r+\u000e+\u014e\u0005+\u0151\n+\u0003,\u0006,\u0154\n,\r,\u000e",
    ",\u0155\u0003,\u0003,\u0006,\u015a\n,\r,\u000e,\u015b\u0003,\u0006,",
    "\u015f\n,\r,\u000e,\u0160\u0003,\u0003,\u0007,\u0165\n,\f,\u000e,\u0168",
    "\u000b,\u0003,\u0005,\u016b\n,\u0003-\u0003-\u0005-\u016f\n-\u0003-",
    "\u0006-\u0172\n-\r-\u000e-\u0173\u0003.\u0003.\u0007.\u0178\n.\f.\u000e",
    ".\u017b\u000b.\u0003.\u0003.\u0003/\u0003/\u0005/\u0181\n/\u00030\u0003",
    "0\u00030\u00050\u0186\n0\u00030\u00030\u00031\u00031\u00031\u00031\u0003",
    "2\u00032\u00033\u00063\u0191\n3\r3\u000e3\u0192\u00033\u00053\u0196",
    "\n3\u00034\u00034\u00035\u00035\u00036\u00036\u00036\u00036\u00056\u01a0",
    "\n6\u00037\u00037\u00037\u00037\u00037\u00037\u00037\u00037\u00037\u0003",
    "7\u00037\u00057\u01ad\n7\u00038\u00038\u00038\u00038\u00038\u00038\u0003",
    "8\u00039\u00039\u00039\u00039\u00079\u01ba\n9\f9\u000e9\u01bd\u000b",
    "9\u00039\u00059\u01c0\n9\u00039\u00039\u00039\u00039\u00039\u00079\u01c7",
    "\n9\f9\u000e9\u01ca\u000b9\u00039\u00039\u00059\u01ce\n9\u00039\u0003",
    "9\u0003\u01c8\u0002:\u0003\u0003\u0005\u0004\u0007\u0005\t\u0006\u000b",
    "\u0007\r\b\u000f\t\u0011\n\u0013\u000b\u0015\f\u0017\r\u0019\u000e\u001b",
    "\u000f\u001d\u0010\u001f\u0011!\u0012#\u0013%\u0014\'\u0015)\u0016+",
    "\u0017-\u0002/\u00021\u00023\u00185\u00197\u001a9\u001b;\u001c=\u001d",
    "?\u001eA\u001fC E!G\"I#K$M%O&Q\'S(U)W*Y\u0002[+]\u0002_,a-c\u0002e.",
    "g\u0002i\u0002k\u0002m\u0002o\u0002q/\u0003\u0002\u0012\u0004\u0002",
    "--//\u0005\u0002\'\',,11\u0004\u0002>>@@\u0005\u0002C\\aac|\u0006\u0002",
    "2;C\\aac|\u0003\u00022;\u0003\u000223\u0004\u0002GGgg\u0006\u0002\f",
    "\f\u000f\u000f$$^^\u0006\u0002\f\f\u000f\u000f))^^\u0004\u0002\u000b",
    "\u000b\"\"\u0004\u0002\f\f\u000f\u000f\u0005\u00022;CHch\u0003\u0002",
    "29\n\u0002$$))^^ddhhppttvv\u0003\u000225\u0002\u01e5\u0002\u0003\u0003",
    "\u0002\u0002\u0002\u0002\u0005\u0003\u0002\u0002\u0002\u0002\u0007\u0003",
    "\u0002\u0002\u0002\u0002\t\u0003\u0002\u0002\u0002\u0002\u000b\u0003",
    "\u0002\u0002\u0002\u0002\r\u0003\u0002\u0002\u0002\u0002\u000f\u0003",
    "\u0002\u0002\u0002\u0002\u0011\u0003\u0002\u0002\u0002\u0002\u0013\u0003",
    "\u0002\u0002\u0002\u0002\u0015\u0003\u0002\u0002\u0002\u0002\u0017\u0003",
    "\u0002\u0002\u0002\u0002\u0019\u0003\u0002\u0002\u0002\u0002\u001b\u0003",
    "\u0002\u0002\u0002\u0002\u001d\u0003\u0002\u0002\u0002\u0002\u001f\u0003",
    "\u0002\u0002\u0002\u0002!\u0003\u0002\u0002\u0002\u0002#\u0003\u0002",
    "\u0002\u0002\u0002%\u0003\u0002\u0002\u0002\u0002\'\u0003\u0002\u0002",
    "\u0002\u0002)\u0003\u0002\u0002\u0002\u0002+\u0003\u0002\u0002\u0002",
    "\u00023\u0003\u0002\u0002\u0002\u00025\u0003\u0002\u0002\u0002\u0002",
    "7\u0003\u0002\u0002\u0002\u00029\u0003\u0002\u0002\u0002\u0002;\u0003",
    "\u0002\u0002\u0002\u0002=\u0003\u0002\u0002\u0002\u0002?\u0003\u0002",
    "\u0002\u0002\u0002A\u0003\u0002\u0002\u0002\u0002C\u0003\u0002\u0002",
    "\u0002\u0002E\u0003\u0002\u0002\u0002\u0002G\u0003\u0002\u0002\u0002",
    "\u0002I\u0003\u0002\u0002\u0002\u0002K\u0003\u0002\u0002\u0002\u0002",
    "M\u0003\u0002\u0002\u0002\u0002O\u0003\u0002\u0002\u0002\u0002Q\u0003",
    "\u0002\u0002\u0002\u0002S\u0003\u0002\u0002\u0002\u0002U\u0003\u0002",
    "\u0002\u0002\u0002W\u0003\u0002\u0002\u0002\u0002[\u0003\u0002\u0002",
    "\u0002\u0002_\u0003\u0002\u0002\u0002\u0002a\u0003\u0002\u0002\u0002",
    "\u0002e\u0003\u0002\u0002\u0002\u0002q\u0003\u0002\u0002\u0002\u0003",
    "s\u0003\u0002\u0002\u0002\u0005{\u0003\u0002\u0002\u0002\u0007\u0080",
    "\u0003\u0002\u0002\u0002\t\u0085\u0003\u0002\u0002\u0002\u000b\u008d",
    "\u0003\u0002\u0002\u0002\r\u0094\u0003\u0002\u0002\u0002\u000f\u009c",
    "\u0003\u0002\u0002\u0002\u0011\u00a6\u0003\u0002\u0002\u0002\u0013\u00ad",
    "\u0003\u0002\u0002\u0002\u0015\u00b2\u0003\u0002\u0002\u0002\u0017\u00bc",
    "\u0003\u0002\u0002\u0002\u0019\u00c2\u0003\u0002\u0002\u0002\u001b\u00cb",
    "\u0003\u0002\u0002\u0002\u001d\u00d2\u0003\u0002\u0002\u0002\u001f\u00d6",
    "\u0003\u0002\u0002\u0002!\u00dc\u0003\u0002\u0002\u0002#\u00df\u0003",
    "\u0002\u0002\u0002%\u00e5\u0003\u0002\u0002\u0002\'\u00e8\u0003\u0002",
    "\u0002\u0002)\u00ed\u0003\u0002\u0002\u0002+\u00f3\u0003\u0002\u0002",
    "\u0002-\u00f8\u0003\u0002\u0002\u0002/\u00fc\u0003\u0002\u0002\u0002",
    "1\u0100\u0003\u0002\u0002\u00023\u0103\u0003\u0002\u0002\u00025\u0105",
    "\u0003\u0002\u0002\u00027\u0107\u0003\u0002\u0002\u00029\u0109\u0003",
    "\u0002\u0002\u0002;\u010b\u0003\u0002\u0002\u0002=\u010d\u0003\u0002",
    "\u0002\u0002?\u010f\u0003\u0002\u0002\u0002A\u0111\u0003\u0002\u0002",
    "\u0002C\u0113\u0003\u0002\u0002\u0002E\u0115\u0003\u0002\u0002\u0002",
    "G\u0117\u0003\u0002\u0002\u0002I\u0119\u0003\u0002\u0002\u0002K\u0124",
    "\u0003\u0002\u0002\u0002M\u0126\u0003\u0002\u0002\u0002O\u0128\u0003",
    "\u0002\u0002\u0002Q\u012a\u0003\u0002\u0002\u0002S\u0131\u0003\u0002",
    "\u0002\u0002U\u0150\u0003\u0002\u0002\u0002W\u016a\u0003\u0002\u0002",
    "\u0002Y\u016c\u0003\u0002\u0002\u0002[\u0175\u0003\u0002\u0002\u0002",
    "]\u0180\u0003\u0002\u0002\u0002_\u0182\u0003\u0002\u0002\u0002a\u0189",
    "\u0003\u0002\u0002\u0002c\u018d\u0003\u0002\u0002\u0002e\u0195\u0003",
    "\u0002\u0002\u0002g\u0197\u0003\u0002\u0002\u0002i\u0199\u0003\u0002",
    "\u0002\u0002k\u019f\u0003\u0002\u0002\u0002m\u01ac\u0003\u0002\u0002",
    "\u0002o\u01ae\u0003\u0002\u0002\u0002q\u01cd\u0003\u0002\u0002\u0002",
    "st\u0007r\u0002\u0002tu\u0007t\u0002\u0002uv\u0007q\u0002\u0002vw\u0007",
    "i\u0002\u0002wx\u0007t\u0002\u0002xy\u0007c\u0002\u0002yz\u0007o\u0002",
    "\u0002z\u0004\u0003\u0002\u0002\u0002{|\u0007t\u0002\u0002|}\u0007g",
    "\u0002\u0002}~\u0007c\u0002\u0002~\u007f\u0007n\u0002\u0002\u007f\u0006",
    "\u0003\u0002\u0002\u0002\u0080\u0081\u0007x\u0002\u0002\u0081\u0082",
    "\u0007q\u0002\u0002\u0082\u0083\u0007k\u0002\u0002\u0083\u0084\u0007",
    "f\u0002\u0002\u0084\b\u0003\u0002\u0002\u0002\u0085\u0086\u0007d\u0002",
    "\u0002\u0086\u0087\u0007q\u0002\u0002\u0087\u0088\u0007q\u0002\u0002",
    "\u0088\u0089\u0007n\u0002\u0002\u0089\u008a\u0007g\u0002\u0002\u008a",
    "\u008b\u0007c\u0002\u0002\u008b\u008c\u0007p\u0002\u0002\u008c\n\u0003",
    "\u0002\u0002\u0002\u008d\u008e\u0007u\u0002\u0002\u008e\u008f\u0007",
    "v\u0002\u0002\u008f\u0090\u0007t\u0002\u0002\u0090\u0091\u0007k\u0002",
    "\u0002\u0091\u0092\u0007p\u0002\u0002\u0092\u0093\u0007i\u0002\u0002",
    "\u0093\f\u0003\u0002\u0002\u0002\u0094\u0095\u0007k\u0002\u0002\u0095",
    "\u0096\u0007p\u0002\u0002\u0096\u0097\u0007v\u0002\u0002\u0097\u0098",
    "\u0007g\u0002\u0002\u0098\u0099\u0007i\u0002\u0002\u0099\u009a\u0007",
    "g\u0002\u0002\u009a\u009b\u0007t\u0002\u0002\u009b\u000e\u0003\u0002",
    "\u0002\u0002\u009c\u009d\u0007e\u0002\u0002\u009d\u009e\u0007j\u0002",
    "\u0002\u009e\u009f\u0007c\u0002\u0002\u009f\u00a0\u0007t\u0002\u0002",
    "\u00a0\u00a1\u0007c\u0002\u0002\u00a1\u00a2\u0007e\u0002\u0002\u00a2",
    "\u00a3\u0007v\u0002\u0002\u00a3\u00a4\u0007g\u0002\u0002\u00a4\u00a5",
    "\u0007t\u0002\u0002\u00a5\u0010\u0003\u0002\u0002\u0002\u00a6\u00a7",
    "\u0007u\u0002\u0002\u00a7\u00a8\u0007y\u0002\u0002\u00a8\u00a9\u0007",
    "k\u0002\u0002\u00a9\u00aa\u0007v\u0002\u0002\u00aa\u00ab\u0007e\u0002",
    "\u0002\u00ab\u00ac\u0007j\u0002\u0002\u00ac\u0012\u0003\u0002\u0002",
    "\u0002\u00ad\u00ae\u0007e\u0002\u0002\u00ae\u00af\u0007c\u0002\u0002",
    "\u00af\u00b0\u0007u\u0002\u0002\u00b0\u00b1\u0007g\u0002\u0002\u00b1",
    "\u0014\u0003\u0002\u0002\u0002\u00b2\u00b3\u0007q\u0002\u0002\u00b3",
    "\u00b4\u0007v\u0002\u0002\u00b4\u00b5\u0007j\u0002\u0002\u00b5\u00b6",
    "\u0007g\u0002\u0002\u00b6\u00b7\u0007t\u0002\u0002\u00b7\u00b8\u0007",
    "y\u0002\u0002\u00b8\u00b9\u0007k\u0002\u0002\u00b9\u00ba\u0007u\u0002",
    "\u0002\u00ba\u00bb\u0007g\u0002\u0002\u00bb\u0016\u0003\u0002\u0002",
    "\u0002\u00bc\u00bd\u0007e\u0002\u0002\u00bd\u00be\u0007q\u0002\u0002",
    "\u00be\u00bf\u0007p\u0002\u0002\u00bf\u00c0\u0007u\u0002\u0002\u00c0",
    "\u00c1\u0007v\u0002\u0002\u00c1\u0018\u0003\u0002\u0002\u0002\u00c2",
    "\u00c3\u0007h\u0002\u0002\u00c3\u00c4\u0007w\u0002\u0002\u00c4\u00c5",
    "\u0007p\u0002\u0002\u00c5\u00c6\u0007e\u0002\u0002\u00c6\u00c7\u0007",
    "v\u0002\u0002\u00c7\u00c8\u0007k\u0002\u0002\u00c8\u00c9\u0007q\u0002",
    "\u0002\u00c9\u00ca\u0007p\u0002\u0002\u00ca\u001a\u0003\u0002\u0002",
    "\u0002\u00cb\u00cc\u0007t\u0002\u0002\u00cc\u00cd\u0007g\u0002\u0002",
    "\u00cd\u00ce\u0007v\u0002\u0002\u00ce\u00cf\u0007w\u0002\u0002\u00cf",
    "\u00d0\u0007t\u0002\u0002\u00d0\u00d1\u0007p\u0002\u0002\u00d1\u001c",
    "\u0003\u0002\u0002\u0002\u00d2\u00d3\u0007h\u0002\u0002\u00d3\u00d4",
    "\u0007q\u0002\u0002\u00d4\u00d5\u0007t\u0002\u0002\u00d5\u001e\u0003",
    "\u0002\u0002\u0002\u00d6\u00d7\u0007d\u0002\u0002\u00d7\u00d8\u0007",
    "t\u0002\u0002\u00d8\u00d9\u0007g\u0002\u0002\u00d9\u00da\u0007c\u0002",
    "\u0002\u00da\u00db\u0007m\u0002\u0002\u00db \u0003\u0002\u0002\u0002",
    "\u00dc\u00dd\u0007f\u0002\u0002\u00dd\u00de\u0007q\u0002\u0002\u00de",
    "\"\u0003\u0002\u0002\u0002\u00df\u00e0\u0007y\u0002\u0002\u00e0\u00e1",
    "\u0007j\u0002\u0002\u00e1\u00e2\u0007k\u0002\u0002\u00e2\u00e3\u0007",
    "n\u0002\u0002\u00e3\u00e4\u0007g\u0002\u0002\u00e4$\u0003\u0002\u0002",
    "\u0002\u00e5\u00e6\u0007k\u0002\u0002\u00e6\u00e7\u0007h\u0002\u0002",
    "\u00e7&\u0003\u0002\u0002\u0002\u00e8\u00e9\u0007g\u0002\u0002\u00e9",
    "\u00ea\u0007n\u0002\u0002\u00ea\u00eb\u0007u\u0002\u0002\u00eb\u00ec",
    "\u0007g\u0002\u0002\u00ec(\u0003\u0002\u0002\u0002\u00ed\u00ee\u0007",
    "h\u0002\u0002\u00ee\u00ef\u0007c\u0002\u0002\u00ef\u00f0\u0007n\u0002",
    "\u0002\u00f0\u00f1\u0007u\u0002\u0002\u00f1\u00f2\u0007g\u0002\u0002",
    "\u00f2*\u0003\u0002\u0002\u0002\u00f3\u00f4\u0007v\u0002\u0002\u00f4",
    "\u00f5\u0007t\u0002\u0002\u00f5\u00f6\u0007w\u0002\u0002\u00f6\u00f7",
    "\u0007g\u0002\u0002\u00f7,\u0003\u0002\u0002\u0002\u00f8\u00f9\u0007",
    "p\u0002\u0002\u00f9\u00fa\u0007q\u0002\u0002\u00fa\u00fb\u0007v\u0002",
    "\u0002\u00fb.\u0003\u0002\u0002\u0002\u00fc\u00fd\u0007C\u0002\u0002",
    "\u00fd\u00fe\u0007P\u0002\u0002\u00fe\u00ff\u0007F\u0002\u0002\u00ff",
    "0\u0003\u0002\u0002\u0002\u0100\u0101\u0007Q\u0002\u0002\u0101\u0102",
    "\u0007T\u0002\u0002\u01022\u0003\u0002\u0002\u0002\u0103\u0104\u0007",
    "*\u0002\u0002\u01044\u0003\u0002\u0002\u0002\u0105\u0106\u0007+\u0002",
    "\u0002\u01066\u0003\u0002\u0002\u0002\u0107\u0108\u0007]\u0002\u0002",
    "\u01088\u0003\u0002\u0002\u0002\u0109\u010a\u0007_\u0002\u0002\u010a",
    ":\u0003\u0002\u0002\u0002\u010b\u010c\u0007}\u0002\u0002\u010c<\u0003",
    "\u0002\u0002\u0002\u010d\u010e\u0007\u007f\u0002\u0002\u010e>\u0003",
    "\u0002\u0002\u0002\u010f\u0110\u0007.\u0002\u0002\u0110@\u0003\u0002",
    "\u0002\u0002\u0111\u0112\u0007?\u0002\u0002\u0112B\u0003\u0002\u0002",
    "\u0002\u0113\u0114\t\u0002\u0002\u0002\u0114D\u0003\u0002\u0002\u0002",
    "\u0115\u0116\t\u0003\u0002\u0002\u0116F\u0003\u0002\u0002\u0002\u0117",
    "\u0118\u0005/\u0018\u0002\u0118H\u0003\u0002\u0002\u0002\u0119\u011a",
    "\u00051\u0019\u0002\u011aJ\u0003\u0002\u0002\u0002\u011b\u011c\u0007",
    "@\u0002\u0002\u011c\u0125\u0007?\u0002\u0002\u011d\u011e\u0007?\u0002",
    "\u0002\u011e\u0125\u0007?\u0002\u0002\u011f\u0120\u0007>\u0002\u0002",
    "\u0120\u0125\u0007?\u0002\u0002\u0121\u0125\t\u0004\u0002\u0002\u0122",
    "\u0123\u0007#\u0002\u0002\u0123\u0125\u0007?\u0002\u0002\u0124\u011b",
    "\u0003\u0002\u0002\u0002\u0124\u011d\u0003\u0002\u0002\u0002\u0124\u011f",
    "\u0003\u0002\u0002\u0002\u0124\u0121\u0003\u0002\u0002\u0002\u0124\u0122",
    "\u0003\u0002\u0002\u0002\u0125L\u0003\u0002\u0002\u0002\u0126\u0127",
    "\u0007<\u0002\u0002\u0127N\u0003\u0002\u0002\u0002\u0128\u0129\u0005",
    "-\u0017\u0002\u0129P\u0003\u0002\u0002\u0002\u012a\u012e\t\u0005\u0002",
    "\u0002\u012b\u012d\t\u0006\u0002\u0002\u012c\u012b\u0003\u0002\u0002",
    "\u0002\u012d\u0130\u0003\u0002\u0002\u0002\u012e\u012c\u0003\u0002\u0002",
    "\u0002\u012e\u012f\u0003\u0002\u0002\u0002\u012fR\u0003\u0002\u0002",
    "\u0002\u0130\u012e\u0003\u0002\u0002\u0002\u0131\u0132\u0005Q)\u0002",
    "\u0132\u0133\u00070\u0002\u0002\u0133\u0134\u0005Q)\u0002\u0134T\u0003",
    "\u0002\u0002\u0002\u0135\u0137\t\u0007\u0002\u0002\u0136\u0135\u0003",
    "\u0002\u0002\u0002\u0137\u0138\u0003\u0002\u0002\u0002\u0138\u0136\u0003",
    "\u0002\u0002\u0002\u0138\u0139\u0003\u0002\u0002\u0002\u0139\u0151\u0003",
    "\u0002\u0002\u0002\u013a\u013b\u00072\u0002\u0002\u013b\u013f\u0007",
    "z\u0002\u0002\u013c\u013d\u00072\u0002\u0002\u013d\u013f\u0007Z\u0002",
    "\u0002\u013e\u013a\u0003\u0002\u0002\u0002\u013e\u013c\u0003\u0002\u0002",
    "\u0002\u013f\u0141\u0003\u0002\u0002\u0002\u0140\u0142\u0005g4\u0002",
    "\u0141\u0140\u0003\u0002\u0002\u0002\u0142\u0143\u0003\u0002\u0002\u0002",
    "\u0143\u0141\u0003\u0002\u0002\u0002\u0143\u0144\u0003\u0002\u0002\u0002",
    "\u0144\u0151\u0003\u0002\u0002\u0002\u0145\u0146\u00072\u0002\u0002",
    "\u0146\u014a\u0007d\u0002\u0002\u0147\u0148\u00072\u0002\u0002\u0148",
    "\u014a\u0007D\u0002\u0002\u0149\u0145\u0003\u0002\u0002\u0002\u0149",
    "\u0147\u0003\u0002\u0002\u0002\u014a\u014c\u0003\u0002\u0002\u0002\u014b",
    "\u014d\t\b\u0002\u0002\u014c\u014b\u0003\u0002\u0002\u0002\u014d\u014e",
    "\u0003\u0002\u0002\u0002\u014e\u014c\u0003\u0002\u0002\u0002\u014e\u014f",
    "\u0003\u0002\u0002\u0002\u014f\u0151\u0003\u0002\u0002\u0002\u0150\u0136",
    "\u0003\u0002\u0002\u0002\u0150\u013e\u0003\u0002\u0002\u0002\u0150\u0149",
    "\u0003\u0002\u0002\u0002\u0151V\u0003\u0002\u0002\u0002\u0152\u0154",
    "\t\u0007\u0002\u0002\u0153\u0152\u0003\u0002\u0002\u0002\u0154\u0155",
    "\u0003\u0002\u0002\u0002\u0155\u0153\u0003\u0002\u0002\u0002\u0155\u0156",
    "\u0003\u0002\u0002\u0002\u0156\u0157\u0003\u0002\u0002\u0002\u0157\u0159",
    "\u00070\u0002\u0002\u0158\u015a\t\u0007\u0002\u0002\u0159\u0158\u0003",
    "\u0002\u0002\u0002\u015a\u015b\u0003\u0002\u0002\u0002\u015b\u0159\u0003",
    "\u0002\u0002\u0002\u015b\u015c\u0003\u0002\u0002\u0002\u015c\u016b\u0003",
    "\u0002\u0002\u0002\u015d\u015f\t\u0007\u0002\u0002\u015e\u015d\u0003",
    "\u0002\u0002\u0002\u015f\u0160\u0003\u0002\u0002\u0002\u0160\u015e\u0003",
    "\u0002\u0002\u0002\u0160\u0161\u0003\u0002\u0002\u0002\u0161\u0162\u0003",
    "\u0002\u0002\u0002\u0162\u0166\u00070\u0002\u0002\u0163\u0165\t\u0007",
    "\u0002\u0002\u0164\u0163\u0003\u0002\u0002\u0002\u0165\u0168\u0003\u0002",
    "\u0002\u0002\u0166\u0164\u0003\u0002\u0002\u0002\u0166\u0167\u0003\u0002",
    "\u0002\u0002\u0167\u0169\u0003\u0002\u0002\u0002\u0168\u0166\u0003\u0002",
    "\u0002\u0002\u0169\u016b\u0005Y-\u0002\u016a\u0153\u0003\u0002\u0002",
    "\u0002\u016a\u015e\u0003\u0002\u0002\u0002\u016bX\u0003\u0002\u0002",
    "\u0002\u016c\u016e\t\t\u0002\u0002\u016d\u016f\t\u0002\u0002\u0002\u016e",
    "\u016d\u0003\u0002\u0002\u0002\u016e\u016f\u0003\u0002\u0002\u0002\u016f",
    "\u0171\u0003\u0002\u0002\u0002\u0170\u0172\t\u0007\u0002\u0002\u0171",
    "\u0170\u0003\u0002\u0002\u0002\u0172\u0173\u0003\u0002\u0002\u0002\u0173",
    "\u0171\u0003\u0002\u0002\u0002\u0173\u0174\u0003\u0002\u0002\u0002\u0174",
    "Z\u0003\u0002\u0002\u0002\u0175\u0179\u0007$\u0002\u0002\u0176\u0178",
    "\u0005]/\u0002\u0177\u0176\u0003\u0002\u0002\u0002\u0178\u017b\u0003",
    "\u0002\u0002\u0002\u0179\u0177\u0003\u0002\u0002\u0002\u0179\u017a\u0003",
    "\u0002\u0002\u0002\u017a\u017c\u0003\u0002\u0002\u0002\u017b\u0179\u0003",
    "\u0002\u0002\u0002\u017c\u017d\u0007$\u0002\u0002\u017d\\\u0003\u0002",
    "\u0002\u0002\u017e\u0181\n\n\u0002\u0002\u017f\u0181\u0005k6\u0002\u0180",
    "\u017e\u0003\u0002\u0002\u0002\u0180\u017f\u0003\u0002\u0002\u0002\u0181",
    "^\u0003\u0002\u0002\u0002\u0182\u0185\u0007)\u0002\u0002\u0183\u0186",
    "\u0005k6\u0002\u0184\u0186\n\u000b\u0002\u0002\u0185\u0183\u0003\u0002",
    "\u0002\u0002\u0185\u0184\u0003\u0002\u0002\u0002\u0186\u0187\u0003\u0002",
    "\u0002\u0002\u0187\u0188\u0007)\u0002\u0002\u0188`\u0003\u0002\u0002",
    "\u0002\u0189\u018a\t\f\u0002\u0002\u018a\u018b\u0003\u0002\u0002\u0002",
    "\u018b\u018c\b1\u0002\u0002\u018cb\u0003\u0002\u0002\u0002\u018d\u018e",
    "\u0007=\u0002\u0002\u018ed\u0003\u0002\u0002\u0002\u018f\u0191\t\r\u0002",
    "\u0002\u0190\u018f\u0003\u0002\u0002\u0002\u0191\u0192\u0003\u0002\u0002",
    "\u0002\u0192\u0190\u0003\u0002\u0002\u0002\u0192\u0193\u0003\u0002\u0002",
    "\u0002\u0193\u0196\u0003\u0002\u0002\u0002\u0194\u0196\u0005c2\u0002",
    "\u0195\u0190\u0003\u0002\u0002\u0002\u0195\u0194\u0003\u0002\u0002\u0002",
    "\u0196f\u0003\u0002\u0002\u0002\u0197\u0198\t\u000e\u0002\u0002\u0198",
    "h\u0003\u0002\u0002\u0002\u0199\u019a\t\u000f\u0002\u0002\u019aj\u0003",
    "\u0002\u0002\u0002\u019b\u019c\u0007^\u0002\u0002\u019c\u01a0\t\u0010",
    "\u0002\u0002\u019d\u01a0\u0005o8\u0002\u019e\u01a0\u0005m7\u0002\u019f",
    "\u019b\u0003\u0002\u0002\u0002\u019f\u019d\u0003\u0002\u0002\u0002\u019f",
    "\u019e\u0003\u0002\u0002\u0002\u01a0l\u0003\u0002\u0002\u0002\u01a1",
    "\u01a2\u0007^\u0002\u0002\u01a2\u01a3\t\u0011\u0002\u0002\u01a3\u01a4",
    "\u0005i5\u0002\u01a4\u01a5\u0005i5\u0002\u01a5\u01ad\u0003\u0002\u0002",
    "\u0002\u01a6\u01a7\u0007^\u0002\u0002\u01a7\u01a8\u0005i5\u0002\u01a8",
    "\u01a9\u0005i5\u0002\u01a9\u01ad\u0003\u0002\u0002\u0002\u01aa\u01ab",
    "\u0007^\u0002\u0002\u01ab\u01ad\u0005i5\u0002\u01ac\u01a1\u0003\u0002",
    "\u0002\u0002\u01ac\u01a6\u0003\u0002\u0002\u0002\u01ac\u01aa\u0003\u0002",
    "\u0002\u0002\u01adn\u0003\u0002\u0002\u0002\u01ae\u01af\u0007^\u0002",
    "\u0002\u01af\u01b0\u0007w\u0002\u0002\u01b0\u01b1\u0005g4\u0002\u01b1",
    "\u01b2\u0005g4\u0002\u01b2\u01b3\u0005g4\u0002\u01b3\u01b4\u0005g4\u0002",
    "\u01b4p\u0003\u0002\u0002\u0002\u01b5\u01b6\u00071\u0002\u0002\u01b6",
    "\u01b7\u00071\u0002\u0002\u01b7\u01bb\u0003\u0002\u0002\u0002\u01b8",
    "\u01ba\n\r\u0002\u0002\u01b9\u01b8\u0003\u0002\u0002\u0002\u01ba\u01bd",
    "\u0003\u0002\u0002\u0002\u01bb\u01b9\u0003\u0002\u0002\u0002\u01bb\u01bc",
    "\u0003\u0002\u0002\u0002\u01bc\u01bf\u0003\u0002\u0002\u0002\u01bd\u01bb",
    "\u0003\u0002\u0002\u0002\u01be\u01c0\u0007\u000f\u0002\u0002\u01bf\u01be",
    "\u0003\u0002\u0002\u0002\u01bf\u01c0\u0003\u0002\u0002\u0002\u01c0\u01c1",
    "\u0003\u0002\u0002\u0002\u01c1\u01ce\u0007\f\u0002\u0002\u01c2\u01c3",
    "\u00071\u0002\u0002\u01c3\u01c4\u0007,\u0002\u0002\u01c4\u01c8\u0003",
    "\u0002\u0002\u0002\u01c5\u01c7\u000b\u0002\u0002\u0002\u01c6\u01c5\u0003",
    "\u0002\u0002\u0002\u01c7\u01ca\u0003\u0002\u0002\u0002\u01c8\u01c9\u0003",
    "\u0002\u0002\u0002\u01c8\u01c6\u0003\u0002\u0002\u0002\u01c9\u01cb\u0003",
    "\u0002\u0002\u0002\u01ca\u01c8\u0003\u0002\u0002\u0002\u01cb\u01cc\u0007",
    ",\u0002\u0002\u01cc\u01ce\u00071\u0002\u0002\u01cd\u01b5\u0003\u0002",
    "\u0002\u0002\u01cd\u01c2\u0003\u0002\u0002\u0002\u01ce\u01cf\u0003\u0002",
    "\u0002\u0002\u01cf\u01d0\b9\u0003\u0002\u01d0r\u0003\u0002\u0002\u0002",
    "\u001d\u0002\u0124\u012e\u0138\u013e\u0143\u0149\u014e\u0150\u0155\u015b",
    "\u0160\u0166\u016a\u016e\u0173\u0179\u0180\u0185\u0192\u0195\u019f\u01ac",
    "\u01bb\u01bf\u01c8\u01cd\u0004\b\u0002\u0002\u0002\u0003\u0002"].join("");


var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);

var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); });

function ivprog(input) {
	antlr4.Lexer.call(this, input);
    this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.PredictionContextCache());
    return this;
}

ivprog.prototype = Object.create(antlr4.Lexer.prototype);
ivprog.prototype.constructor = ivprog;

ivprog.EOF = antlr4.Token.EOF;
ivprog.RK_PROGRAM = 1;
ivprog.RK_REAL = 2;
ivprog.RK_VOID = 3;
ivprog.RK_BOOLEAN = 4;
ivprog.RK_STRING = 5;
ivprog.RK_INTEGER = 6;
ivprog.RK_CHARACTER = 7;
ivprog.RK_SWITCH = 8;
ivprog.RK_CASE = 9;
ivprog.RK_DEFAULT = 10;
ivprog.RK_CONST = 11;
ivprog.RK_FUNCTION = 12;
ivprog.RK_RETURN = 13;
ivprog.RK_FOR = 14;
ivprog.RK_BREAK = 15;
ivprog.RK_DO = 16;
ivprog.RK_WHILE = 17;
ivprog.RK_IF = 18;
ivprog.RK_ELSE = 19;
ivprog.RK_FALSE = 20;
ivprog.RK_TRUE = 21;
ivprog.OPEN_PARENTHESIS = 22;
ivprog.CLOSE_PARENTHESIS = 23;
ivprog.OPEN_BRACE = 24;
ivprog.CLOSE_BRACE = 25;
ivprog.OPEN_CURLY = 26;
ivprog.CLOSE_CURLY = 27;
ivprog.COMMA = 28;
ivprog.EQUAL = 29;
ivprog.SUM_OP = 30;
ivprog.MULTI_OP = 31;
ivprog.AND_OPERATOR = 32;
ivprog.OR_OPERATOR = 33;
ivprog.RELATIONAL_OPERATOR = 34;
ivprog.COLON = 35;
ivprog.NOT_OPERATOR = 36;
ivprog.ID = 37;
ivprog.LIB_ID = 38;
ivprog.INTEGER = 39;
ivprog.REAL = 40;
ivprog.STRING = 41;
ivprog.CHARACTER = 42;
ivprog.WHITESPACE = 43;
ivprog.EOS = 44;
ivprog.COMMENTS = 45;

ivprog.prototype.channelNames = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN" ];

ivprog.prototype.modeNames = [ "DEFAULT_MODE" ];

ivprog.prototype.literalNames = [ null, "'program'", "'real'", "'void'", 
                                  "'boolean'", "'string'", "'integer'", 
                                  "'character'", "'switch'", "'case'", "'otherwise'", 
                                  "'const'", "'function'", "'return'", "'for'", 
                                  "'break'", "'do'", "'while'", "'if'", 
                                  "'else'", "'false'", "'true'", "'('", 
                                  "')'", "'['", "']'", "'{'", "'}'", "','", 
                                  "'='", null, null, null, null, null, "':'" ];

ivprog.prototype.symbolicNames = [ null, "RK_PROGRAM", "RK_REAL", "RK_VOID", 
                                   "RK_BOOLEAN", "RK_STRING", "RK_INTEGER", 
                                   "RK_CHARACTER", "RK_SWITCH", "RK_CASE", 
                                   "RK_DEFAULT", "RK_CONST", "RK_FUNCTION", 
                                   "RK_RETURN", "RK_FOR", "RK_BREAK", "RK_DO", 
                                   "RK_WHILE", "RK_IF", "RK_ELSE", "RK_FALSE", 
                                   "RK_TRUE", "OPEN_PARENTHESIS", "CLOSE_PARENTHESIS", 
                                   "OPEN_BRACE", "CLOSE_BRACE", "OPEN_CURLY", 
                                   "CLOSE_CURLY", "COMMA", "EQUAL", "SUM_OP", 
                                   "MULTI_OP", "AND_OPERATOR", "OR_OPERATOR", 
                                   "RELATIONAL_OPERATOR", "COLON", "NOT_OPERATOR", 
                                   "ID", "LIB_ID", "INTEGER", "REAL", "STRING", 
                                   "CHARACTER", "WHITESPACE", "EOS", "COMMENTS" ];

ivprog.prototype.ruleNames = [ "RK_PROGRAM", "RK_REAL", "RK_VOID", "RK_BOOLEAN", 
                               "RK_STRING", "RK_INTEGER", "RK_CHARACTER", 
                               "RK_SWITCH", "RK_CASE", "RK_DEFAULT", "RK_CONST", 
                               "RK_FUNCTION", "RK_RETURN", "RK_FOR", "RK_BREAK", 
                               "RK_DO", "RK_WHILE", "RK_IF", "RK_ELSE", 
                               "RK_FALSE", "RK_TRUE", "RK_LOGICAL_NOT", 
                               "RK_LOGICAL_AND", "RK_LOGICAL_OR", "OPEN_PARENTHESIS", 
                               "CLOSE_PARENTHESIS", "OPEN_BRACE", "CLOSE_BRACE", 
                               "OPEN_CURLY", "CLOSE_CURLY", "COMMA", "EQUAL", 
                               "SUM_OP", "MULTI_OP", "AND_OPERATOR", "OR_OPERATOR", 
                               "RELATIONAL_OPERATOR", "COLON", "NOT_OPERATOR", 
                               "ID", "LIB_ID", "INTEGER", "REAL", "ExponentPart", 
                               "STRING", "STRING_CHARACTER", "CHARACTER", 
                               "WHITESPACE", "SEMICOLON", "EOS", "HEX_DIGIT", 
                               "OCTAL_DIGIT", "ESC_SEQ", "ESC_OCTAL", "ESC_UNICODE", 
                               "COMMENTS" ];

ivprog.prototype.grammarFileName = "ivprog.g4";



exports.ivprog = ivprog;



/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = {
ivprog: __webpack_require__(0).ivprog
};


/***/ }),
/* 2 */
/***/ (function(module, exports) {

module.exports = __webpack_require__(/*! antlr4/index */ "./node_modules/antlr4/index.js");

/***/ })
/******/ ]);

/***/ }),

/***/ "./grammar/en/langFunctions.js":
/*!*************************************!*\
  !*** ./grammar/en/langFunctions.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/* This is a dictionary of the language defined functions
**/
exports.default = {
  main_function: "start",
  $read: "read",
  $write: "write",
  $numElements: "total_of_elements",
  $matrixLines: "total_of_lines",
  $matrixColumns: "total_of_columns",
  $substring: "subcadeia",
  $length: "comprimento",
  $uppercase: "caixa_alta",
  $lowercase: "caixa_baixa",
  $charAt: "char_at",
  $isReal: "is_real",
  $isInt: "is_integer",
  $isBool: "is_logic",
  $castReal: "to_real",
  $castInt: "to_integer",
  $castBool: "to_logic",
  $castString: "to_string",
  $sin: "sin",
  $cos: "cos",
  $tan: "tan",
  $sqrt: "sqrt",
  $pow: "pow",
  $log: "log",
  $abs: "abs",
  $negate: "negate",
  $invert: "invert",
  $max: "maximum",
  $min: "minimum"

};

/***/ }),

/***/ "./grammar/en/langLibs.js":
/*!********************************!*\
  !*** ./grammar/en/langLibs.js ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * This is the dictionary of the language defined libraries
 */
exports.default = {
  $mathLib: "Mathematic",
  $ioLib: "ES",
  $strLib: "Texto",
  $arrayLib: "Arranjo",
  $langLib: "Conversion"
};

/***/ }),

/***/ "./grammar/es/ivprog.g4":
/*!******************************!*\
  !*** ./grammar/es/ivprog.g4 ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

// Generated from /tmp/tmp-3344Sc0xK8I4xxzw/ivprog.g4 by ANTLR 4.7
// jshint ignore: start
var antlr4 = __webpack_require__(2);


var serializedATN = ["\u0003\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964",
    "\u0002/\u01dc\b\u0001\u0004\u0002\t\u0002\u0004\u0003\t\u0003\u0004",
    "\u0004\t\u0004\u0004\u0005\t\u0005\u0004\u0006\t\u0006\u0004\u0007\t",
    "\u0007\u0004\b\t\b\u0004\t\t\t\u0004\n\t\n\u0004\u000b\t\u000b\u0004",
    "\f\t\f\u0004\r\t\r\u0004\u000e\t\u000e\u0004\u000f\t\u000f\u0004\u0010",
    "\t\u0010\u0004\u0011\t\u0011\u0004\u0012\t\u0012\u0004\u0013\t\u0013",
    "\u0004\u0014\t\u0014\u0004\u0015\t\u0015\u0004\u0016\t\u0016\u0004\u0017",
    "\t\u0017\u0004\u0018\t\u0018\u0004\u0019\t\u0019\u0004\u001a\t\u001a",
    "\u0004\u001b\t\u001b\u0004\u001c\t\u001c\u0004\u001d\t\u001d\u0004\u001e",
    "\t\u001e\u0004\u001f\t\u001f\u0004 \t \u0004!\t!\u0004\"\t\"\u0004#",
    "\t#\u0004$\t$\u0004%\t%\u0004&\t&\u0004\'\t\'\u0004(\t(\u0004)\t)\u0004",
    "*\t*\u0004+\t+\u0004,\t,\u0004-\t-\u0004.\t.\u0004/\t/\u00040\t0\u0004",
    "1\t1\u00042\t2\u00043\t3\u00044\t4\u00045\t5\u00046\t6\u00047\t7\u0004",
    "8\t8\u00049\t9\u0003\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003",
    "\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003\u0003\u0003",
    "\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0004\u0003\u0004\u0003",
    "\u0004\u0003\u0004\u0003\u0004\u0003\u0004\u0003\u0005\u0003\u0005\u0003",
    "\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0006\u0003",
    "\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003",
    "\u0007\u0003\u0007\u0003\u0007\u0003\u0007\u0003\u0007\u0003\u0007\u0003",
    "\u0007\u0003\u0007\u0003\b\u0003\b\u0003\b\u0003\b\u0003\b\u0003\b\u0003",
    "\b\u0003\b\u0003\b\u0003\b\u0003\t\u0003\t\u0003\t\u0003\t\u0003\t\u0003",
    "\t\u0003\t\u0003\t\u0003\n\u0003\n\u0003\n\u0003\n\u0003\n\u0003\u000b",
    "\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b",
    "\u0003\u000b\u0003\u000b\u0003\u000b\u0003\f\u0003\f\u0003\f\u0003\f",
    "\u0003\f\u0003\f\u0003\r\u0003\r\u0003\r\u0003\r\u0003\r\u0003\r\u0003",
    "\r\u0003\u000e\u0003\u000e\u0003\u000e\u0003\u000e\u0003\u000e\u0003",
    "\u000e\u0003\u000e\u0003\u000e\u0003\u000f\u0003\u000f\u0003\u000f\u0003",
    "\u000f\u0003\u000f\u0003\u0010\u0003\u0010\u0003\u0010\u0003\u0010\u0003",
    "\u0010\u0003\u0011\u0003\u0011\u0003\u0011\u0003\u0011\u0003\u0011\u0003",
    "\u0012\u0003\u0012\u0003\u0012\u0003\u0012\u0003\u0012\u0003\u0012\u0003",
    "\u0012\u0003\u0012\u0003\u0012\u0003\u0013\u0003\u0013\u0003\u0013\u0003",
    "\u0014\u0003\u0014\u0003\u0014\u0003\u0014\u0003\u0014\u0003\u0014\u0003",
    "\u0015\u0003\u0015\u0003\u0015\u0003\u0015\u0003\u0015\u0003\u0015\u0003",
    "\u0016\u0003\u0016\u0003\u0016\u0003\u0016\u0003\u0016\u0003\u0016\u0003",
    "\u0016\u0003\u0016\u0003\u0016\u0003\u0016\u0003\u0016\u0003\u0017\u0003",
    "\u0017\u0003\u0017\u0003\u0017\u0003\u0018\u0003\u0018\u0003\u0019\u0003",
    "\u0019\u0003\u0019\u0003\u001a\u0003\u001a\u0003\u001b\u0003\u001b\u0003",
    "\u001c\u0003\u001c\u0003\u001d\u0003\u001d\u0003\u001e\u0003\u001e\u0003",
    "\u001f\u0003\u001f\u0003 \u0003 \u0003!\u0003!\u0003\"\u0003\"\u0003",
    "#\u0003#\u0003$\u0003$\u0003%\u0003%\u0003&\u0003&\u0003&\u0003&\u0003",
    "&\u0003&\u0003&\u0003&\u0003&\u0005&\u0130\n&\u0003\'\u0003\'\u0003",
    "(\u0003(\u0003)\u0003)\u0007)\u0138\n)\f)\u000e)\u013b\u000b)\u0003",
    "*\u0003*\u0003*\u0003*\u0003+\u0006+\u0142\n+\r+\u000e+\u0143\u0003",
    "+\u0003+\u0003+\u0003+\u0005+\u014a\n+\u0003+\u0006+\u014d\n+\r+\u000e",
    "+\u014e\u0003+\u0003+\u0003+\u0003+\u0005+\u0155\n+\u0003+\u0006+\u0158",
    "\n+\r+\u000e+\u0159\u0005+\u015c\n+\u0003,\u0006,\u015f\n,\r,\u000e",
    ",\u0160\u0003,\u0003,\u0006,\u0165\n,\r,\u000e,\u0166\u0003,\u0006,",
    "\u016a\n,\r,\u000e,\u016b\u0003,\u0003,\u0007,\u0170\n,\f,\u000e,\u0173",
    "\u000b,\u0003,\u0005,\u0176\n,\u0003-\u0003-\u0005-\u017a\n-\u0003-",
    "\u0006-\u017d\n-\r-\u000e-\u017e\u0003.\u0003.\u0007.\u0183\n.\f.\u000e",
    ".\u0186\u000b.\u0003.\u0003.\u0003/\u0003/\u0005/\u018c\n/\u00030\u0003",
    "0\u00030\u00050\u0191\n0\u00030\u00030\u00031\u00031\u00031\u00031\u0003",
    "2\u00032\u00033\u00063\u019c\n3\r3\u000e3\u019d\u00033\u00053\u01a1",
    "\n3\u00034\u00034\u00035\u00035\u00036\u00036\u00036\u00036\u00056\u01ab",
    "\n6\u00037\u00037\u00037\u00037\u00037\u00037\u00037\u00037\u00037\u0003",
    "7\u00037\u00057\u01b8\n7\u00038\u00038\u00038\u00038\u00038\u00038\u0003",
    "8\u00039\u00039\u00039\u00039\u00079\u01c5\n9\f9\u000e9\u01c8\u000b",
    "9\u00039\u00059\u01cb\n9\u00039\u00039\u00039\u00039\u00039\u00079\u01d2",
    "\n9\f9\u000e9\u01d5\u000b9\u00039\u00039\u00059\u01d9\n9\u00039\u0003",
    "9\u0003\u01d3\u0002:\u0003\u0003\u0005\u0004\u0007\u0005\t\u0006\u000b",
    "\u0007\r\b\u000f\t\u0011\n\u0013\u000b\u0015\f\u0017\r\u0019\u000e\u001b",
    "\u000f\u001d\u0010\u001f\u0011!\u0012#\u0013%\u0014\'\u0015)\u0016+",
    "\u0017-\u0002/\u00021\u00023\u00185\u00197\u001a9\u001b;\u001c=\u001d",
    "?\u001eA\u001fC E!G\"I#K$M%O&Q\'S(U)W*Y\u0002[+]\u0002_,a-c\u0002e.",
    "g\u0002i\u0002k\u0002m\u0002o\u0002q/\u0003\u0002\u0012\u0004\u0002",
    "--//\u0005\u0002\'\',,11\u0004\u0002>>@@\u0005\u0002C\\aac|\u0006\u0002",
    "2;C\\aac|\u0003\u00022;\u0003\u000223\u0004\u0002GGgg\u0006\u0002\f",
    "\f\u000f\u000f$$^^\u0006\u0002\f\f\u000f\u000f))^^\u0004\u0002\u000b",
    "\u000b\"\"\u0004\u0002\f\f\u000f\u000f\u0005\u00022;CHch\u0003\u0002",
    "29\n\u0002$$))^^ddhhppttvv\u0003\u000225\u0002\u01f0\u0002\u0003\u0003",
    "\u0002\u0002\u0002\u0002\u0005\u0003\u0002\u0002\u0002\u0002\u0007\u0003",
    "\u0002\u0002\u0002\u0002\t\u0003\u0002\u0002\u0002\u0002\u000b\u0003",
    "\u0002\u0002\u0002\u0002\r\u0003\u0002\u0002\u0002\u0002\u000f\u0003",
    "\u0002\u0002\u0002\u0002\u0011\u0003\u0002\u0002\u0002\u0002\u0013\u0003",
    "\u0002\u0002\u0002\u0002\u0015\u0003\u0002\u0002\u0002\u0002\u0017\u0003",
    "\u0002\u0002\u0002\u0002\u0019\u0003\u0002\u0002\u0002\u0002\u001b\u0003",
    "\u0002\u0002\u0002\u0002\u001d\u0003\u0002\u0002\u0002\u0002\u001f\u0003",
    "\u0002\u0002\u0002\u0002!\u0003\u0002\u0002\u0002\u0002#\u0003\u0002",
    "\u0002\u0002\u0002%\u0003\u0002\u0002\u0002\u0002\'\u0003\u0002\u0002",
    "\u0002\u0002)\u0003\u0002\u0002\u0002\u0002+\u0003\u0002\u0002\u0002",
    "\u00023\u0003\u0002\u0002\u0002\u00025\u0003\u0002\u0002\u0002\u0002",
    "7\u0003\u0002\u0002\u0002\u00029\u0003\u0002\u0002\u0002\u0002;\u0003",
    "\u0002\u0002\u0002\u0002=\u0003\u0002\u0002\u0002\u0002?\u0003\u0002",
    "\u0002\u0002\u0002A\u0003\u0002\u0002\u0002\u0002C\u0003\u0002\u0002",
    "\u0002\u0002E\u0003\u0002\u0002\u0002\u0002G\u0003\u0002\u0002\u0002",
    "\u0002I\u0003\u0002\u0002\u0002\u0002K\u0003\u0002\u0002\u0002\u0002",
    "M\u0003\u0002\u0002\u0002\u0002O\u0003\u0002\u0002\u0002\u0002Q\u0003",
    "\u0002\u0002\u0002\u0002S\u0003\u0002\u0002\u0002\u0002U\u0003\u0002",
    "\u0002\u0002\u0002W\u0003\u0002\u0002\u0002\u0002[\u0003\u0002\u0002",
    "\u0002\u0002_\u0003\u0002\u0002\u0002\u0002a\u0003\u0002\u0002\u0002",
    "\u0002e\u0003\u0002\u0002\u0002\u0002q\u0003\u0002\u0002\u0002\u0003",
    "s\u0003\u0002\u0002\u0002\u0005|\u0003\u0002\u0002\u0002\u0007\u0081",
    "\u0003\u0002\u0002\u0002\t\u0087\u0003\u0002\u0002\u0002\u000b\u008e",
    "\u0003\u0002\u0002\u0002\r\u0095\u0003\u0002\u0002\u0002\u000f\u009d",
    "\u0003\u0002\u0002\u0002\u0011\u00a7\u0003\u0002\u0002\u0002\u0013\u00af",
    "\u0003\u0002\u0002\u0002\u0015\u00b4\u0003\u0002\u0002\u0002\u0017\u00be",
    "\u0003\u0002\u0002\u0002\u0019\u00c4\u0003\u0002\u0002\u0002\u001b\u00cb",
    "\u0003\u0002\u0002\u0002\u001d\u00d3\u0003\u0002\u0002\u0002\u001f\u00d8",
    "\u0003\u0002\u0002\u0002!\u00dd\u0003\u0002\u0002\u0002#\u00e2\u0003",
    "\u0002\u0002\u0002%\u00eb\u0003\u0002\u0002\u0002\'\u00ee\u0003\u0002",
    "\u0002\u0002)\u00f4\u0003\u0002\u0002\u0002+\u00fa\u0003\u0002\u0002",
    "\u0002-\u0105\u0003\u0002\u0002\u0002/\u0109\u0003\u0002\u0002\u0002",
    "1\u010b\u0003\u0002\u0002\u00023\u010e\u0003\u0002\u0002\u00025\u0110",
    "\u0003\u0002\u0002\u00027\u0112\u0003\u0002\u0002\u00029\u0114\u0003",
    "\u0002\u0002\u0002;\u0116\u0003\u0002\u0002\u0002=\u0118\u0003\u0002",
    "\u0002\u0002?\u011a\u0003\u0002\u0002\u0002A\u011c\u0003\u0002\u0002",
    "\u0002C\u011e\u0003\u0002\u0002\u0002E\u0120\u0003\u0002\u0002\u0002",
    "G\u0122\u0003\u0002\u0002\u0002I\u0124\u0003\u0002\u0002\u0002K\u012f",
    "\u0003\u0002\u0002\u0002M\u0131\u0003\u0002\u0002\u0002O\u0133\u0003",
    "\u0002\u0002\u0002Q\u0135\u0003\u0002\u0002\u0002S\u013c\u0003\u0002",
    "\u0002\u0002U\u015b\u0003\u0002\u0002\u0002W\u0175\u0003\u0002\u0002",
    "\u0002Y\u0177\u0003\u0002\u0002\u0002[\u0180\u0003\u0002\u0002\u0002",
    "]\u018b\u0003\u0002\u0002\u0002_\u018d\u0003\u0002\u0002\u0002a\u0194",
    "\u0003\u0002\u0002\u0002c\u0198\u0003\u0002\u0002\u0002e\u01a0\u0003",
    "\u0002\u0002\u0002g\u01a2\u0003\u0002\u0002\u0002i\u01a4\u0003\u0002",
    "\u0002\u0002k\u01aa\u0003\u0002\u0002\u0002m\u01b7\u0003\u0002\u0002",
    "\u0002o\u01b9\u0003\u0002\u0002\u0002q\u01d8\u0003\u0002\u0002\u0002",
    "st\u0007r\u0002\u0002tu\u0007t\u0002\u0002uv\u0007q\u0002\u0002vw\u0007",
    "i\u0002\u0002wx\u0007t\u0002\u0002xy\u0007c\u0002\u0002yz\u0007o\u0002",
    "\u0002z{\u0007c\u0002\u0002{\u0004\u0003\u0002\u0002\u0002|}\u0007t",
    "\u0002\u0002}~\u0007g\u0002\u0002~\u007f\u0007c\u0002\u0002\u007f\u0080",
    "\u0007n\u0002\u0002\u0080\u0006\u0003\u0002\u0002\u0002\u0081\u0082",
    "\u0007x\u0002\u0002\u0082\u0083\u0007c\u0002\u0002\u0083\u0084\u0007",
    "|\u0002\u0002\u0084\u0085\u0007k\u0002\u0002\u0085\u0086\u0007q\u0002",
    "\u0002\u0086\b\u0003\u0002\u0002\u0002\u0087\u0088\u0007n\u0002\u0002",
    "\u0088\u0089\u0007q\u0002\u0002\u0089\u008a\u0007i\u0002\u0002\u008a",
    "\u008b\u0007k\u0002\u0002\u008b\u008c\u0007e\u0002\u0002\u008c\u008d",
    "\u0007q\u0002\u0002\u008d\n\u0003\u0002\u0002\u0002\u008e\u008f\u0007",
    "e\u0002\u0002\u008f\u0090\u0007c\u0002\u0002\u0090\u0091\u0007f\u0002",
    "\u0002\u0091\u0092\u0007g\u0002\u0002\u0092\u0093\u0007k\u0002\u0002",
    "\u0093\u0094\u0007c\u0002\u0002\u0094\f\u0003\u0002\u0002\u0002\u0095",
    "\u0096\u0007k\u0002\u0002\u0096\u0097\u0007p\u0002\u0002\u0097\u0098",
    "\u0007v\u0002\u0002\u0098\u0099\u0007g\u0002\u0002\u0099\u009a\u0007",
    "k\u0002\u0002\u009a\u009b\u0007t\u0002\u0002\u009b\u009c\u0007q\u0002",
    "\u0002\u009c\u000e\u0003\u0002\u0002\u0002\u009d\u009e\u0007e\u0002",
    "\u0002\u009e\u009f\u0007c\u0002\u0002\u009f\u00a0\u0007t\u0002\u0002",
    "\u00a0\u00a1\u0007c\u0002\u0002\u00a1\u00a2\u0007e\u0002\u0002\u00a2",
    "\u00a3\u0007v\u0002\u0002\u00a3\u00a4\u0007g\u0002\u0002\u00a4\u00a5",
    "\u0007t\u0002\u0002\u00a5\u00a6\u0007g\u0002\u0002\u00a6\u0010\u0003",
    "\u0002\u0002\u0002\u00a7\u00a8\u0007g\u0002\u0002\u00a8\u00a9\u0007",
    "u\u0002\u0002\u00a9\u00aa\u0007e\u0002\u0002\u00aa\u00ab\u0007q\u0002",
    "\u0002\u00ab\u00ac\u0007n\u0002\u0002\u00ac\u00ad\u0007j\u0002\u0002",
    "\u00ad\u00ae\u0007c\u0002\u0002\u00ae\u0012\u0003\u0002\u0002\u0002",
    "\u00af\u00b0\u0007e\u0002\u0002\u00b0\u00b1\u0007c\u0002\u0002\u00b1",
    "\u00b2\u0007u\u0002\u0002\u00b2\u00b3\u0007q\u0002\u0002\u00b3\u0014",
    "\u0003\u0002\u0002\u0002\u00b4\u00b5\u0007e\u0002\u0002\u00b5\u00b6",
    "\u0007q\u0002\u0002\u00b6\u00b7\u0007p\u0002\u0002\u00b7\u00b8\u0007",
    "v\u0002\u0002\u00b8\u00b9\u0007t\u0002\u0002\u00b9\u00ba\u0007c\u0002",
    "\u0002\u00ba\u00bb\u0007t\u0002\u0002\u00bb\u00bc\u0007k\u0002\u0002",
    "\u00bc\u00bd\u0007q\u0002\u0002\u00bd\u0016\u0003\u0002\u0002\u0002",
    "\u00be\u00bf\u0007e\u0002\u0002\u00bf\u00c0\u0007q\u0002\u0002\u00c0",
    "\u00c1\u0007p\u0002\u0002\u00c1\u00c2\u0007u\u0002\u0002\u00c2\u00c3",
    "\u0007v\u0002\u0002\u00c3\u0018\u0003\u0002\u0002\u0002\u00c4\u00c5",
    "\u0007h\u0002\u0002\u00c5\u00c6\u0007w\u0002\u0002\u00c6\u00c7\u0007",
    "p\u0002\u0002\u00c7\u00c8\u0007e\u0002\u0002\u00c8\u00c9\u0007c\u0002",
    "\u0002\u00c9\u00ca\u0007q\u0002\u0002\u00ca\u001a\u0003\u0002\u0002",
    "\u0002\u00cb\u00cc\u0007t\u0002\u0002\u00cc\u00cd\u0007g\u0002\u0002",
    "\u00cd\u00ce\u0007v\u0002\u0002\u00ce\u00cf\u0007q\u0002\u0002\u00cf",
    "\u00d0\u0007t\u0002\u0002\u00d0\u00d1\u0007p\u0002\u0002\u00d1\u00d2",
    "\u0007g\u0002\u0002\u00d2\u001c\u0003\u0002\u0002\u0002\u00d3\u00d4",
    "\u0007r\u0002\u0002\u00d4\u00d5\u0007c\u0002\u0002\u00d5\u00d6\u0007",
    "t\u0002\u0002\u00d6\u00d7\u0007c\u0002\u0002\u00d7\u001e\u0003\u0002",
    "\u0002\u0002\u00d8\u00d9\u0007r\u0002\u0002\u00d9\u00da\u0007c\u0002",
    "\u0002\u00da\u00db\u0007t\u0002\u0002\u00db\u00dc\u0007g\u0002\u0002",
    "\u00dc \u0003\u0002\u0002\u0002\u00dd\u00de\u0007h\u0002\u0002\u00de",
    "\u00df\u0007c\u0002\u0002\u00df\u00e0\u0007e\u0002\u0002\u00e0\u00e1",
    "\u0007c\u0002\u0002\u00e1\"\u0003\u0002\u0002\u0002\u00e2\u00e3\u0007",
    "g\u0002\u0002\u00e3\u00e4\u0007p\u0002\u0002\u00e4\u00e5\u0007s\u0002",
    "\u0002\u00e5\u00e6\u0007w\u0002\u0002\u00e6\u00e7\u0007c\u0002\u0002",
    "\u00e7\u00e8\u0007p\u0002\u0002\u00e8\u00e9\u0007v\u0002\u0002\u00e9",
    "\u00ea\u0007q\u0002\u0002\u00ea$\u0003\u0002\u0002\u0002\u00eb\u00ec",
    "\u0007u\u0002\u0002\u00ec\u00ed\u0007g\u0002\u0002\u00ed&\u0003\u0002",
    "\u0002\u0002\u00ee\u00ef\u0007u\u0002\u0002\u00ef\u00f0\u0007g\u0002",
    "\u0002\u00f0\u00f1\u0007p\u0002\u0002\u00f1\u00f2\u0007c\u0002\u0002",
    "\u00f2\u00f3\u0007q\u0002\u0002\u00f3(\u0003\u0002\u0002\u0002\u00f4",
    "\u00f5\u0007h\u0002\u0002\u00f5\u00f6\u0007c\u0002\u0002\u00f6\u00f7",
    "\u0007n\u0002\u0002\u00f7\u00f8\u0007u\u0002\u0002\u00f8\u00f9\u0007",
    "q\u0002\u0002\u00f9*\u0003\u0002\u0002\u0002\u00fa\u00fb\u0007x\u0002",
    "\u0002\u00fb\u00fc\u0007g\u0002\u0002\u00fc\u00fd\u0007t\u0002\u0002",
    "\u00fd\u00fe\u0007f\u0002\u0002\u00fe\u00ff\u0007c\u0002\u0002\u00ff",
    "\u0100\u0007f\u0002\u0002\u0100\u0101\u0007g\u0002\u0002\u0101\u0102",
    "\u0007k\u0002\u0002\u0102\u0103\u0007t\u0002\u0002\u0103\u0104\u0007",
    "q\u0002\u0002\u0104,\u0003\u0002\u0002\u0002\u0105\u0106\u0007p\u0002",
    "\u0002\u0106\u0107\u0007c\u0002\u0002\u0107\u0108\u0007q\u0002\u0002",
    "\u0108.\u0003\u0002\u0002\u0002\u0109\u010a\u0007G\u0002\u0002\u010a",
    "0\u0003\u0002\u0002\u0002\u010b\u010c\u0007Q\u0002\u0002\u010c\u010d",
    "\u0007W\u0002\u0002\u010d2\u0003\u0002\u0002\u0002\u010e\u010f\u0007",
    "*\u0002\u0002\u010f4\u0003\u0002\u0002\u0002\u0110\u0111\u0007+\u0002",
    "\u0002\u01116\u0003\u0002\u0002\u0002\u0112\u0113\u0007]\u0002\u0002",
    "\u01138\u0003\u0002\u0002\u0002\u0114\u0115\u0007_\u0002\u0002\u0115",
    ":\u0003\u0002\u0002\u0002\u0116\u0117\u0007}\u0002\u0002\u0117<\u0003",
    "\u0002\u0002\u0002\u0118\u0119\u0007\u007f\u0002\u0002\u0119>\u0003",
    "\u0002\u0002\u0002\u011a\u011b\u0007.\u0002\u0002\u011b@\u0003\u0002",
    "\u0002\u0002\u011c\u011d\u0007?\u0002\u0002\u011dB\u0003\u0002\u0002",
    "\u0002\u011e\u011f\t\u0002\u0002\u0002\u011fD\u0003\u0002\u0002\u0002",
    "\u0120\u0121\t\u0003\u0002\u0002\u0121F\u0003\u0002\u0002\u0002\u0122",
    "\u0123\u0005/\u0018\u0002\u0123H\u0003\u0002\u0002\u0002\u0124\u0125",
    "\u00051\u0019\u0002\u0125J\u0003\u0002\u0002\u0002\u0126\u0127\u0007",
    "@\u0002\u0002\u0127\u0130\u0007?\u0002\u0002\u0128\u0129\u0007?\u0002",
    "\u0002\u0129\u0130\u0007?\u0002\u0002\u012a\u012b\u0007>\u0002\u0002",
    "\u012b\u0130\u0007?\u0002\u0002\u012c\u0130\t\u0004\u0002\u0002\u012d",
    "\u012e\u0007#\u0002\u0002\u012e\u0130\u0007?\u0002\u0002\u012f\u0126",
    "\u0003\u0002\u0002\u0002\u012f\u0128\u0003\u0002\u0002\u0002\u012f\u012a",
    "\u0003\u0002\u0002\u0002\u012f\u012c\u0003\u0002\u0002\u0002\u012f\u012d",
    "\u0003\u0002\u0002\u0002\u0130L\u0003\u0002\u0002\u0002\u0131\u0132",
    "\u0007<\u0002\u0002\u0132N\u0003\u0002\u0002\u0002\u0133\u0134\u0005",
    "-\u0017\u0002\u0134P\u0003\u0002\u0002\u0002\u0135\u0139\t\u0005\u0002",
    "\u0002\u0136\u0138\t\u0006\u0002\u0002\u0137\u0136\u0003\u0002\u0002",
    "\u0002\u0138\u013b\u0003\u0002\u0002\u0002\u0139\u0137\u0003\u0002\u0002",
    "\u0002\u0139\u013a\u0003\u0002\u0002\u0002\u013aR\u0003\u0002\u0002",
    "\u0002\u013b\u0139\u0003\u0002\u0002\u0002\u013c\u013d\u0005Q)\u0002",
    "\u013d\u013e\u00070\u0002\u0002\u013e\u013f\u0005Q)\u0002\u013fT\u0003",
    "\u0002\u0002\u0002\u0140\u0142\t\u0007\u0002\u0002\u0141\u0140\u0003",
    "\u0002\u0002\u0002\u0142\u0143\u0003\u0002\u0002\u0002\u0143\u0141\u0003",
    "\u0002\u0002\u0002\u0143\u0144\u0003\u0002\u0002\u0002\u0144\u015c\u0003",
    "\u0002\u0002\u0002\u0145\u0146\u00072\u0002\u0002\u0146\u014a\u0007",
    "z\u0002\u0002\u0147\u0148\u00072\u0002\u0002\u0148\u014a\u0007Z\u0002",
    "\u0002\u0149\u0145\u0003\u0002\u0002\u0002\u0149\u0147\u0003\u0002\u0002",
    "\u0002\u014a\u014c\u0003\u0002\u0002\u0002\u014b\u014d\u0005g4\u0002",
    "\u014c\u014b\u0003\u0002\u0002\u0002\u014d\u014e\u0003\u0002\u0002\u0002",
    "\u014e\u014c\u0003\u0002\u0002\u0002\u014e\u014f\u0003\u0002\u0002\u0002",
    "\u014f\u015c\u0003\u0002\u0002\u0002\u0150\u0151\u00072\u0002\u0002",
    "\u0151\u0155\u0007d\u0002\u0002\u0152\u0153\u00072\u0002\u0002\u0153",
    "\u0155\u0007D\u0002\u0002\u0154\u0150\u0003\u0002\u0002\u0002\u0154",
    "\u0152\u0003\u0002\u0002\u0002\u0155\u0157\u0003\u0002\u0002\u0002\u0156",
    "\u0158\t\b\u0002\u0002\u0157\u0156\u0003\u0002\u0002\u0002\u0158\u0159",
    "\u0003\u0002\u0002\u0002\u0159\u0157\u0003\u0002\u0002\u0002\u0159\u015a",
    "\u0003\u0002\u0002\u0002\u015a\u015c\u0003\u0002\u0002\u0002\u015b\u0141",
    "\u0003\u0002\u0002\u0002\u015b\u0149\u0003\u0002\u0002\u0002\u015b\u0154",
    "\u0003\u0002\u0002\u0002\u015cV\u0003\u0002\u0002\u0002\u015d\u015f",
    "\t\u0007\u0002\u0002\u015e\u015d\u0003\u0002\u0002\u0002\u015f\u0160",
    "\u0003\u0002\u0002\u0002\u0160\u015e\u0003\u0002\u0002\u0002\u0160\u0161",
    "\u0003\u0002\u0002\u0002\u0161\u0162\u0003\u0002\u0002\u0002\u0162\u0164",
    "\u00070\u0002\u0002\u0163\u0165\t\u0007\u0002\u0002\u0164\u0163\u0003",
    "\u0002\u0002\u0002\u0165\u0166\u0003\u0002\u0002\u0002\u0166\u0164\u0003",
    "\u0002\u0002\u0002\u0166\u0167\u0003\u0002\u0002\u0002\u0167\u0176\u0003",
    "\u0002\u0002\u0002\u0168\u016a\t\u0007\u0002\u0002\u0169\u0168\u0003",
    "\u0002\u0002\u0002\u016a\u016b\u0003\u0002\u0002\u0002\u016b\u0169\u0003",
    "\u0002\u0002\u0002\u016b\u016c\u0003\u0002\u0002\u0002\u016c\u016d\u0003",
    "\u0002\u0002\u0002\u016d\u0171\u00070\u0002\u0002\u016e\u0170\t\u0007",
    "\u0002\u0002\u016f\u016e\u0003\u0002\u0002\u0002\u0170\u0173\u0003\u0002",
    "\u0002\u0002\u0171\u016f\u0003\u0002\u0002\u0002\u0171\u0172\u0003\u0002",
    "\u0002\u0002\u0172\u0174\u0003\u0002\u0002\u0002\u0173\u0171\u0003\u0002",
    "\u0002\u0002\u0174\u0176\u0005Y-\u0002\u0175\u015e\u0003\u0002\u0002",
    "\u0002\u0175\u0169\u0003\u0002\u0002\u0002\u0176X\u0003\u0002\u0002",
    "\u0002\u0177\u0179\t\t\u0002\u0002\u0178\u017a\t\u0002\u0002\u0002\u0179",
    "\u0178\u0003\u0002\u0002\u0002\u0179\u017a\u0003\u0002\u0002\u0002\u017a",
    "\u017c\u0003\u0002\u0002\u0002\u017b\u017d\t\u0007\u0002\u0002\u017c",
    "\u017b\u0003\u0002\u0002\u0002\u017d\u017e\u0003\u0002\u0002\u0002\u017e",
    "\u017c\u0003\u0002\u0002\u0002\u017e\u017f\u0003\u0002\u0002\u0002\u017f",
    "Z\u0003\u0002\u0002\u0002\u0180\u0184\u0007$\u0002\u0002\u0181\u0183",
    "\u0005]/\u0002\u0182\u0181\u0003\u0002\u0002\u0002\u0183\u0186\u0003",
    "\u0002\u0002\u0002\u0184\u0182\u0003\u0002\u0002\u0002\u0184\u0185\u0003",
    "\u0002\u0002\u0002\u0185\u0187\u0003\u0002\u0002\u0002\u0186\u0184\u0003",
    "\u0002\u0002\u0002\u0187\u0188\u0007$\u0002\u0002\u0188\\\u0003\u0002",
    "\u0002\u0002\u0189\u018c\n\n\u0002\u0002\u018a\u018c\u0005k6\u0002\u018b",
    "\u0189\u0003\u0002\u0002\u0002\u018b\u018a\u0003\u0002\u0002\u0002\u018c",
    "^\u0003\u0002\u0002\u0002\u018d\u0190\u0007)\u0002\u0002\u018e\u0191",
    "\u0005k6\u0002\u018f\u0191\n\u000b\u0002\u0002\u0190\u018e\u0003\u0002",
    "\u0002\u0002\u0190\u018f\u0003\u0002\u0002\u0002\u0191\u0192\u0003\u0002",
    "\u0002\u0002\u0192\u0193\u0007)\u0002\u0002\u0193`\u0003\u0002\u0002",
    "\u0002\u0194\u0195\t\f\u0002\u0002\u0195\u0196\u0003\u0002\u0002\u0002",
    "\u0196\u0197\b1\u0002\u0002\u0197b\u0003\u0002\u0002\u0002\u0198\u0199",
    "\u0007=\u0002\u0002\u0199d\u0003\u0002\u0002\u0002\u019a\u019c\t\r\u0002",
    "\u0002\u019b\u019a\u0003\u0002\u0002\u0002\u019c\u019d\u0003\u0002\u0002",
    "\u0002\u019d\u019b\u0003\u0002\u0002\u0002\u019d\u019e\u0003\u0002\u0002",
    "\u0002\u019e\u01a1\u0003\u0002\u0002\u0002\u019f\u01a1\u0005c2\u0002",
    "\u01a0\u019b\u0003\u0002\u0002\u0002\u01a0\u019f\u0003\u0002\u0002\u0002",
    "\u01a1f\u0003\u0002\u0002\u0002\u01a2\u01a3\t\u000e\u0002\u0002\u01a3",
    "h\u0003\u0002\u0002\u0002\u01a4\u01a5\t\u000f\u0002\u0002\u01a5j\u0003",
    "\u0002\u0002\u0002\u01a6\u01a7\u0007^\u0002\u0002\u01a7\u01ab\t\u0010",
    "\u0002\u0002\u01a8\u01ab\u0005o8\u0002\u01a9\u01ab\u0005m7\u0002\u01aa",
    "\u01a6\u0003\u0002\u0002\u0002\u01aa\u01a8\u0003\u0002\u0002\u0002\u01aa",
    "\u01a9\u0003\u0002\u0002\u0002\u01abl\u0003\u0002\u0002\u0002\u01ac",
    "\u01ad\u0007^\u0002\u0002\u01ad\u01ae\t\u0011\u0002\u0002\u01ae\u01af",
    "\u0005i5\u0002\u01af\u01b0\u0005i5\u0002\u01b0\u01b8\u0003\u0002\u0002",
    "\u0002\u01b1\u01b2\u0007^\u0002\u0002\u01b2\u01b3\u0005i5\u0002\u01b3",
    "\u01b4\u0005i5\u0002\u01b4\u01b8\u0003\u0002\u0002\u0002\u01b5\u01b6",
    "\u0007^\u0002\u0002\u01b6\u01b8\u0005i5\u0002\u01b7\u01ac\u0003\u0002",
    "\u0002\u0002\u01b7\u01b1\u0003\u0002\u0002\u0002\u01b7\u01b5\u0003\u0002",
    "\u0002\u0002\u01b8n\u0003\u0002\u0002\u0002\u01b9\u01ba\u0007^\u0002",
    "\u0002\u01ba\u01bb\u0007w\u0002\u0002\u01bb\u01bc\u0005g4\u0002\u01bc",
    "\u01bd\u0005g4\u0002\u01bd\u01be\u0005g4\u0002\u01be\u01bf\u0005g4\u0002",
    "\u01bfp\u0003\u0002\u0002\u0002\u01c0\u01c1\u00071\u0002\u0002\u01c1",
    "\u01c2\u00071\u0002\u0002\u01c2\u01c6\u0003\u0002\u0002\u0002\u01c3",
    "\u01c5\n\r\u0002\u0002\u01c4\u01c3\u0003\u0002\u0002\u0002\u01c5\u01c8",
    "\u0003\u0002\u0002\u0002\u01c6\u01c4\u0003\u0002\u0002\u0002\u01c6\u01c7",
    "\u0003\u0002\u0002\u0002\u01c7\u01ca\u0003\u0002\u0002\u0002\u01c8\u01c6",
    "\u0003\u0002\u0002\u0002\u01c9\u01cb\u0007\u000f\u0002\u0002\u01ca\u01c9",
    "\u0003\u0002\u0002\u0002\u01ca\u01cb\u0003\u0002\u0002\u0002\u01cb\u01cc",
    "\u0003\u0002\u0002\u0002\u01cc\u01d9\u0007\f\u0002\u0002\u01cd\u01ce",
    "\u00071\u0002\u0002\u01ce\u01cf\u0007,\u0002\u0002\u01cf\u01d3\u0003",
    "\u0002\u0002\u0002\u01d0\u01d2\u000b\u0002\u0002\u0002\u01d1\u01d0\u0003",
    "\u0002\u0002\u0002\u01d2\u01d5\u0003\u0002\u0002\u0002\u01d3\u01d4\u0003",
    "\u0002\u0002\u0002\u01d3\u01d1\u0003\u0002\u0002\u0002\u01d4\u01d6\u0003",
    "\u0002\u0002\u0002\u01d5\u01d3\u0003\u0002\u0002\u0002\u01d6\u01d7\u0007",
    ",\u0002\u0002\u01d7\u01d9\u00071\u0002\u0002\u01d8\u01c0\u0003\u0002",
    "\u0002\u0002\u01d8\u01cd\u0003\u0002\u0002\u0002\u01d9\u01da\u0003\u0002",
    "\u0002\u0002\u01da\u01db\b9\u0003\u0002\u01dbr\u0003\u0002\u0002\u0002",
    "\u001d\u0002\u012f\u0139\u0143\u0149\u014e\u0154\u0159\u015b\u0160\u0166",
    "\u016b\u0171\u0175\u0179\u017e\u0184\u018b\u0190\u019d\u01a0\u01aa\u01b7",
    "\u01c6\u01ca\u01d3\u01d8\u0004\b\u0002\u0002\u0002\u0003\u0002"].join("");


var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);

var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); });

function ivprog(input) {
	antlr4.Lexer.call(this, input);
    this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.PredictionContextCache());
    return this;
}

ivprog.prototype = Object.create(antlr4.Lexer.prototype);
ivprog.prototype.constructor = ivprog;

ivprog.EOF = antlr4.Token.EOF;
ivprog.RK_PROGRAM = 1;
ivprog.RK_REAL = 2;
ivprog.RK_VOID = 3;
ivprog.RK_BOOLEAN = 4;
ivprog.RK_STRING = 5;
ivprog.RK_INTEGER = 6;
ivprog.RK_CHARACTER = 7;
ivprog.RK_SWITCH = 8;
ivprog.RK_CASE = 9;
ivprog.RK_DEFAULT = 10;
ivprog.RK_CONST = 11;
ivprog.RK_FUNCTION = 12;
ivprog.RK_RETURN = 13;
ivprog.RK_FOR = 14;
ivprog.RK_BREAK = 15;
ivprog.RK_DO = 16;
ivprog.RK_WHILE = 17;
ivprog.RK_IF = 18;
ivprog.RK_ELSE = 19;
ivprog.RK_FALSE = 20;
ivprog.RK_TRUE = 21;
ivprog.OPEN_PARENTHESIS = 22;
ivprog.CLOSE_PARENTHESIS = 23;
ivprog.OPEN_BRACE = 24;
ivprog.CLOSE_BRACE = 25;
ivprog.OPEN_CURLY = 26;
ivprog.CLOSE_CURLY = 27;
ivprog.COMMA = 28;
ivprog.EQUAL = 29;
ivprog.SUM_OP = 30;
ivprog.MULTI_OP = 31;
ivprog.AND_OPERATOR = 32;
ivprog.OR_OPERATOR = 33;
ivprog.RELATIONAL_OPERATOR = 34;
ivprog.COLON = 35;
ivprog.NOT_OPERATOR = 36;
ivprog.ID = 37;
ivprog.LIB_ID = 38;
ivprog.INTEGER = 39;
ivprog.REAL = 40;
ivprog.STRING = 41;
ivprog.CHARACTER = 42;
ivprog.WHITESPACE = 43;
ivprog.EOS = 44;
ivprog.COMMENTS = 45;

ivprog.prototype.channelNames = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN" ];

ivprog.prototype.modeNames = [ "DEFAULT_MODE" ];

ivprog.prototype.literalNames = [ null, "'programa'", "'real'", "'vazio'", 
                                  "'logico'", "'cadeia'", "'inteiro'", "'caractere'", 
                                  "'escolha'", "'caso'", "'contrario'", 
                                  "'const'", "'funcao'", "'retorne'", "'para'", 
                                  "'pare'", "'faca'", "'enquanto'", "'se'", 
                                  "'senao'", "'falso'", "'verdadeiro'", 
                                  "'('", "')'", "'['", "']'", "'{'", "'}'", 
                                  "','", "'='", null, null, null, null, 
                                  null, "':'" ];

ivprog.prototype.symbolicNames = [ null, "RK_PROGRAM", "RK_REAL", "RK_VOID", 
                                   "RK_BOOLEAN", "RK_STRING", "RK_INTEGER", 
                                   "RK_CHARACTER", "RK_SWITCH", "RK_CASE", 
                                   "RK_DEFAULT", "RK_CONST", "RK_FUNCTION", 
                                   "RK_RETURN", "RK_FOR", "RK_BREAK", "RK_DO", 
                                   "RK_WHILE", "RK_IF", "RK_ELSE", "RK_FALSE", 
                                   "RK_TRUE", "OPEN_PARENTHESIS", "CLOSE_PARENTHESIS", 
                                   "OPEN_BRACE", "CLOSE_BRACE", "OPEN_CURLY", 
                                   "CLOSE_CURLY", "COMMA", "EQUAL", "SUM_OP", 
                                   "MULTI_OP", "AND_OPERATOR", "OR_OPERATOR", 
                                   "RELATIONAL_OPERATOR", "COLON", "NOT_OPERATOR", 
                                   "ID", "LIB_ID", "INTEGER", "REAL", "STRING", 
                                   "CHARACTER", "WHITESPACE", "EOS", "COMMENTS" ];

ivprog.prototype.ruleNames = [ "RK_PROGRAM", "RK_REAL", "RK_VOID", "RK_BOOLEAN", 
                               "RK_STRING", "RK_INTEGER", "RK_CHARACTER", 
                               "RK_SWITCH", "RK_CASE", "RK_DEFAULT", "RK_CONST", 
                               "RK_FUNCTION", "RK_RETURN", "RK_FOR", "RK_BREAK", 
                               "RK_DO", "RK_WHILE", "RK_IF", "RK_ELSE", 
                               "RK_FALSE", "RK_TRUE", "RK_LOGICAL_NOT", 
                               "RK_LOGICAL_AND", "RK_LOGICAL_OR", "OPEN_PARENTHESIS", 
                               "CLOSE_PARENTHESIS", "OPEN_BRACE", "CLOSE_BRACE", 
                               "OPEN_CURLY", "CLOSE_CURLY", "COMMA", "EQUAL", 
                               "SUM_OP", "MULTI_OP", "AND_OPERATOR", "OR_OPERATOR", 
                               "RELATIONAL_OPERATOR", "COLON", "NOT_OPERATOR", 
                               "ID", "LIB_ID", "INTEGER", "REAL", "ExponentPart", 
                               "STRING", "STRING_CHARACTER", "CHARACTER", 
                               "WHITESPACE", "SEMICOLON", "EOS", "HEX_DIGIT", 
                               "OCTAL_DIGIT", "ESC_SEQ", "ESC_OCTAL", "ESC_UNICODE", 
                               "COMMENTS" ];

ivprog.prototype.grammarFileName = "ivprog.g4";



exports.ivprog = ivprog;



/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = {
ivprog: __webpack_require__(0).ivprog
};


/***/ }),
/* 2 */
/***/ (function(module, exports) {

module.exports = __webpack_require__(/*! antlr4/index */ "./node_modules/antlr4/index.js");

/***/ })
/******/ ]);

/***/ }),

/***/ "./grammar/es/langFunctions.js":
/*!*************************************!*\
  !*** ./grammar/es/langFunctions.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/* This is a dictionary of the language defined functions
**/
exports.default = {
  main_function: "inicio",
  $read: "leia",
  $write: "escreva",
  $numElements: "total_of_elements",
  $matrixLines: "total_of_lines",
  $matrixColumns: "total_of_columns",
  $substring: "subcadeia",
  $length: "comprimento",
  $uppercase: "caixa_alta",
  $lowercase: "caixa_baixa",
  $charAt: "char_at",
  $isReal: "is_real",
  $isInt: "is_integer",
  $isBool: "is_logic",
  $castReal: "to_real",
  $castInt: "to_integer",
  $castBool: "to_logic",
  $castString: "to_string",
  $sin: "sin",
  $cos: "cos",
  $tan: "tan",
  $sqrt: "sqrt",
  $pow: "pow",
  $log: "log",
  $abs: "abs",
  $negate: "negate",
  $invert: "invert",
  $max: "maximum",
  $min: "minimum"
};

/***/ }),

/***/ "./grammar/es/langLibs.js":
/*!********************************!*\
  !*** ./grammar/es/langLibs.js ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * This is the dictionary of the language defined libraries
 */
exports.default = {
  $mathLib: "Mathematic",
  $ioLib: "ES",
  $strLib: "Texto",
  $arrayLib: "Arranjo",
  $langLib: "Conversion"
};

/***/ }),

/***/ "./grammar/index.js":
/*!**************************!*\
  !*** ./grammar/index.js ***!
  \**************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _ivprog = __webpack_require__(/*! ./pt/ivprog.g4 */ "./grammar/pt/ivprog.g4");

var PT = _interopRequireWildcard(_ivprog);

var _langFunctions = __webpack_require__(/*! ./pt/langFunctions */ "./grammar/pt/langFunctions.js");

var _langFunctions2 = _interopRequireDefault(_langFunctions);

var _langLibs = __webpack_require__(/*! ./pt/langLibs */ "./grammar/pt/langLibs.js");

var _langLibs2 = _interopRequireDefault(_langLibs);

var _ivprog2 = __webpack_require__(/*! ./en/ivprog.g4 */ "./grammar/en/ivprog.g4");

var EN = _interopRequireWildcard(_ivprog2);

var _langFunctions3 = __webpack_require__(/*! ./en/langFunctions */ "./grammar/en/langFunctions.js");

var _langFunctions4 = _interopRequireDefault(_langFunctions3);

var _langLibs3 = __webpack_require__(/*! ./en/langLibs */ "./grammar/en/langLibs.js");

var _langLibs4 = _interopRequireDefault(_langLibs3);

var _ivprog3 = __webpack_require__(/*! ./es/ivprog.g4 */ "./grammar/es/ivprog.g4");

var ES = _interopRequireWildcard(_ivprog3);

var _langFunctions5 = __webpack_require__(/*! ./es/langFunctions */ "./grammar/es/langFunctions.js");

var _langFunctions6 = _interopRequireDefault(_langFunctions5);

var _langLibs5 = __webpack_require__(/*! ./es/langLibs */ "./grammar/es/langLibs.js");

var _langLibs6 = _interopRequireDefault(_langLibs5);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

exports.pt = { lexer: PT.ivprog, langFuncs: _langFunctions2.default, langLibs: _langLibs2.default };
exports.en = { lexer: EN.ivprog, langFuncs: _langFunctions4.default, langLibs: _langLibs4.default };
exports.es = { lexer: ES.ivprog, langFuncs: _langFunctions6.default, langLibs: _langLibs6.default };

/***/ }),

/***/ "./grammar/pt/ivprog.g4":
/*!******************************!*\
  !*** ./grammar/pt/ivprog.g4 ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

// Generated from /tmp/tmp-3344bnRO1NYbtxZu/ivprog.g4 by ANTLR 4.7
// jshint ignore: start
var antlr4 = __webpack_require__(2);


var serializedATN = ["\u0003\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964",
    "\u0002/\u01dc\b\u0001\u0004\u0002\t\u0002\u0004\u0003\t\u0003\u0004",
    "\u0004\t\u0004\u0004\u0005\t\u0005\u0004\u0006\t\u0006\u0004\u0007\t",
    "\u0007\u0004\b\t\b\u0004\t\t\t\u0004\n\t\n\u0004\u000b\t\u000b\u0004",
    "\f\t\f\u0004\r\t\r\u0004\u000e\t\u000e\u0004\u000f\t\u000f\u0004\u0010",
    "\t\u0010\u0004\u0011\t\u0011\u0004\u0012\t\u0012\u0004\u0013\t\u0013",
    "\u0004\u0014\t\u0014\u0004\u0015\t\u0015\u0004\u0016\t\u0016\u0004\u0017",
    "\t\u0017\u0004\u0018\t\u0018\u0004\u0019\t\u0019\u0004\u001a\t\u001a",
    "\u0004\u001b\t\u001b\u0004\u001c\t\u001c\u0004\u001d\t\u001d\u0004\u001e",
    "\t\u001e\u0004\u001f\t\u001f\u0004 \t \u0004!\t!\u0004\"\t\"\u0004#",
    "\t#\u0004$\t$\u0004%\t%\u0004&\t&\u0004\'\t\'\u0004(\t(\u0004)\t)\u0004",
    "*\t*\u0004+\t+\u0004,\t,\u0004-\t-\u0004.\t.\u0004/\t/\u00040\t0\u0004",
    "1\t1\u00042\t2\u00043\t3\u00044\t4\u00045\t5\u00046\t6\u00047\t7\u0004",
    "8\t8\u00049\t9\u0003\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003",
    "\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003\u0003\u0003",
    "\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0004\u0003\u0004\u0003",
    "\u0004\u0003\u0004\u0003\u0004\u0003\u0004\u0003\u0005\u0003\u0005\u0003",
    "\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0006\u0003",
    "\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003",
    "\u0007\u0003\u0007\u0003\u0007\u0003\u0007\u0003\u0007\u0003\u0007\u0003",
    "\u0007\u0003\u0007\u0003\b\u0003\b\u0003\b\u0003\b\u0003\b\u0003\b\u0003",
    "\b\u0003\b\u0003\b\u0003\b\u0003\t\u0003\t\u0003\t\u0003\t\u0003\t\u0003",
    "\t\u0003\t\u0003\t\u0003\n\u0003\n\u0003\n\u0003\n\u0003\n\u0003\u000b",
    "\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b",
    "\u0003\u000b\u0003\u000b\u0003\u000b\u0003\f\u0003\f\u0003\f\u0003\f",
    "\u0003\f\u0003\f\u0003\r\u0003\r\u0003\r\u0003\r\u0003\r\u0003\r\u0003",
    "\r\u0003\u000e\u0003\u000e\u0003\u000e\u0003\u000e\u0003\u000e\u0003",
    "\u000e\u0003\u000e\u0003\u000e\u0003\u000f\u0003\u000f\u0003\u000f\u0003",
    "\u000f\u0003\u000f\u0003\u0010\u0003\u0010\u0003\u0010\u0003\u0010\u0003",
    "\u0010\u0003\u0011\u0003\u0011\u0003\u0011\u0003\u0011\u0003\u0011\u0003",
    "\u0012\u0003\u0012\u0003\u0012\u0003\u0012\u0003\u0012\u0003\u0012\u0003",
    "\u0012\u0003\u0012\u0003\u0012\u0003\u0013\u0003\u0013\u0003\u0013\u0003",
    "\u0014\u0003\u0014\u0003\u0014\u0003\u0014\u0003\u0014\u0003\u0014\u0003",
    "\u0015\u0003\u0015\u0003\u0015\u0003\u0015\u0003\u0015\u0003\u0015\u0003",
    "\u0016\u0003\u0016\u0003\u0016\u0003\u0016\u0003\u0016\u0003\u0016\u0003",
    "\u0016\u0003\u0016\u0003\u0016\u0003\u0016\u0003\u0016\u0003\u0017\u0003",
    "\u0017\u0003\u0017\u0003\u0017\u0003\u0018\u0003\u0018\u0003\u0019\u0003",
    "\u0019\u0003\u0019\u0003\u001a\u0003\u001a\u0003\u001b\u0003\u001b\u0003",
    "\u001c\u0003\u001c\u0003\u001d\u0003\u001d\u0003\u001e\u0003\u001e\u0003",
    "\u001f\u0003\u001f\u0003 \u0003 \u0003!\u0003!\u0003\"\u0003\"\u0003",
    "#\u0003#\u0003$\u0003$\u0003%\u0003%\u0003&\u0003&\u0003&\u0003&\u0003",
    "&\u0003&\u0003&\u0003&\u0003&\u0005&\u0130\n&\u0003\'\u0003\'\u0003",
    "(\u0003(\u0003)\u0003)\u0007)\u0138\n)\f)\u000e)\u013b\u000b)\u0003",
    "*\u0003*\u0003*\u0003*\u0003+\u0006+\u0142\n+\r+\u000e+\u0143\u0003",
    "+\u0003+\u0003+\u0003+\u0005+\u014a\n+\u0003+\u0006+\u014d\n+\r+\u000e",
    "+\u014e\u0003+\u0003+\u0003+\u0003+\u0005+\u0155\n+\u0003+\u0006+\u0158",
    "\n+\r+\u000e+\u0159\u0005+\u015c\n+\u0003,\u0006,\u015f\n,\r,\u000e",
    ",\u0160\u0003,\u0003,\u0006,\u0165\n,\r,\u000e,\u0166\u0003,\u0006,",
    "\u016a\n,\r,\u000e,\u016b\u0003,\u0003,\u0007,\u0170\n,\f,\u000e,\u0173",
    "\u000b,\u0003,\u0005,\u0176\n,\u0003-\u0003-\u0005-\u017a\n-\u0003-",
    "\u0006-\u017d\n-\r-\u000e-\u017e\u0003.\u0003.\u0007.\u0183\n.\f.\u000e",
    ".\u0186\u000b.\u0003.\u0003.\u0003/\u0003/\u0005/\u018c\n/\u00030\u0003",
    "0\u00030\u00050\u0191\n0\u00030\u00030\u00031\u00031\u00031\u00031\u0003",
    "2\u00032\u00033\u00063\u019c\n3\r3\u000e3\u019d\u00033\u00053\u01a1",
    "\n3\u00034\u00034\u00035\u00035\u00036\u00036\u00036\u00036\u00056\u01ab",
    "\n6\u00037\u00037\u00037\u00037\u00037\u00037\u00037\u00037\u00037\u0003",
    "7\u00037\u00057\u01b8\n7\u00038\u00038\u00038\u00038\u00038\u00038\u0003",
    "8\u00039\u00039\u00039\u00039\u00079\u01c5\n9\f9\u000e9\u01c8\u000b",
    "9\u00039\u00059\u01cb\n9\u00039\u00039\u00039\u00039\u00039\u00079\u01d2",
    "\n9\f9\u000e9\u01d5\u000b9\u00039\u00039\u00059\u01d9\n9\u00039\u0003",
    "9\u0003\u01d3\u0002:\u0003\u0003\u0005\u0004\u0007\u0005\t\u0006\u000b",
    "\u0007\r\b\u000f\t\u0011\n\u0013\u000b\u0015\f\u0017\r\u0019\u000e\u001b",
    "\u000f\u001d\u0010\u001f\u0011!\u0012#\u0013%\u0014\'\u0015)\u0016+",
    "\u0017-\u0002/\u00021\u00023\u00185\u00197\u001a9\u001b;\u001c=\u001d",
    "?\u001eA\u001fC E!G\"I#K$M%O&Q\'S(U)W*Y\u0002[+]\u0002_,a-c\u0002e.",
    "g\u0002i\u0002k\u0002m\u0002o\u0002q/\u0003\u0002\u0012\u0004\u0002",
    "--//\u0005\u0002\'\',,11\u0004\u0002>>@@\u0005\u0002C\\aac|\u0006\u0002",
    "2;C\\aac|\u0003\u00022;\u0003\u000223\u0004\u0002GGgg\u0006\u0002\f",
    "\f\u000f\u000f$$^^\u0006\u0002\f\f\u000f\u000f))^^\u0004\u0002\u000b",
    "\u000b\"\"\u0004\u0002\f\f\u000f\u000f\u0005\u00022;CHch\u0003\u0002",
    "29\n\u0002$$))^^ddhhppttvv\u0003\u000225\u0002\u01f0\u0002\u0003\u0003",
    "\u0002\u0002\u0002\u0002\u0005\u0003\u0002\u0002\u0002\u0002\u0007\u0003",
    "\u0002\u0002\u0002\u0002\t\u0003\u0002\u0002\u0002\u0002\u000b\u0003",
    "\u0002\u0002\u0002\u0002\r\u0003\u0002\u0002\u0002\u0002\u000f\u0003",
    "\u0002\u0002\u0002\u0002\u0011\u0003\u0002\u0002\u0002\u0002\u0013\u0003",
    "\u0002\u0002\u0002\u0002\u0015\u0003\u0002\u0002\u0002\u0002\u0017\u0003",
    "\u0002\u0002\u0002\u0002\u0019\u0003\u0002\u0002\u0002\u0002\u001b\u0003",
    "\u0002\u0002\u0002\u0002\u001d\u0003\u0002\u0002\u0002\u0002\u001f\u0003",
    "\u0002\u0002\u0002\u0002!\u0003\u0002\u0002\u0002\u0002#\u0003\u0002",
    "\u0002\u0002\u0002%\u0003\u0002\u0002\u0002\u0002\'\u0003\u0002\u0002",
    "\u0002\u0002)\u0003\u0002\u0002\u0002\u0002+\u0003\u0002\u0002\u0002",
    "\u00023\u0003\u0002\u0002\u0002\u00025\u0003\u0002\u0002\u0002\u0002",
    "7\u0003\u0002\u0002\u0002\u00029\u0003\u0002\u0002\u0002\u0002;\u0003",
    "\u0002\u0002\u0002\u0002=\u0003\u0002\u0002\u0002\u0002?\u0003\u0002",
    "\u0002\u0002\u0002A\u0003\u0002\u0002\u0002\u0002C\u0003\u0002\u0002",
    "\u0002\u0002E\u0003\u0002\u0002\u0002\u0002G\u0003\u0002\u0002\u0002",
    "\u0002I\u0003\u0002\u0002\u0002\u0002K\u0003\u0002\u0002\u0002\u0002",
    "M\u0003\u0002\u0002\u0002\u0002O\u0003\u0002\u0002\u0002\u0002Q\u0003",
    "\u0002\u0002\u0002\u0002S\u0003\u0002\u0002\u0002\u0002U\u0003\u0002",
    "\u0002\u0002\u0002W\u0003\u0002\u0002\u0002\u0002[\u0003\u0002\u0002",
    "\u0002\u0002_\u0003\u0002\u0002\u0002\u0002a\u0003\u0002\u0002\u0002",
    "\u0002e\u0003\u0002\u0002\u0002\u0002q\u0003\u0002\u0002\u0002\u0003",
    "s\u0003\u0002\u0002\u0002\u0005|\u0003\u0002\u0002\u0002\u0007\u0081",
    "\u0003\u0002\u0002\u0002\t\u0087\u0003\u0002\u0002\u0002\u000b\u008e",
    "\u0003\u0002\u0002\u0002\r\u0095\u0003\u0002\u0002\u0002\u000f\u009d",
    "\u0003\u0002\u0002\u0002\u0011\u00a7\u0003\u0002\u0002\u0002\u0013\u00af",
    "\u0003\u0002\u0002\u0002\u0015\u00b4\u0003\u0002\u0002\u0002\u0017\u00be",
    "\u0003\u0002\u0002\u0002\u0019\u00c4\u0003\u0002\u0002\u0002\u001b\u00cb",
    "\u0003\u0002\u0002\u0002\u001d\u00d3\u0003\u0002\u0002\u0002\u001f\u00d8",
    "\u0003\u0002\u0002\u0002!\u00dd\u0003\u0002\u0002\u0002#\u00e2\u0003",
    "\u0002\u0002\u0002%\u00eb\u0003\u0002\u0002\u0002\'\u00ee\u0003\u0002",
    "\u0002\u0002)\u00f4\u0003\u0002\u0002\u0002+\u00fa\u0003\u0002\u0002",
    "\u0002-\u0105\u0003\u0002\u0002\u0002/\u0109\u0003\u0002\u0002\u0002",
    "1\u010b\u0003\u0002\u0002\u00023\u010e\u0003\u0002\u0002\u00025\u0110",
    "\u0003\u0002\u0002\u00027\u0112\u0003\u0002\u0002\u00029\u0114\u0003",
    "\u0002\u0002\u0002;\u0116\u0003\u0002\u0002\u0002=\u0118\u0003\u0002",
    "\u0002\u0002?\u011a\u0003\u0002\u0002\u0002A\u011c\u0003\u0002\u0002",
    "\u0002C\u011e\u0003\u0002\u0002\u0002E\u0120\u0003\u0002\u0002\u0002",
    "G\u0122\u0003\u0002\u0002\u0002I\u0124\u0003\u0002\u0002\u0002K\u012f",
    "\u0003\u0002\u0002\u0002M\u0131\u0003\u0002\u0002\u0002O\u0133\u0003",
    "\u0002\u0002\u0002Q\u0135\u0003\u0002\u0002\u0002S\u013c\u0003\u0002",
    "\u0002\u0002U\u015b\u0003\u0002\u0002\u0002W\u0175\u0003\u0002\u0002",
    "\u0002Y\u0177\u0003\u0002\u0002\u0002[\u0180\u0003\u0002\u0002\u0002",
    "]\u018b\u0003\u0002\u0002\u0002_\u018d\u0003\u0002\u0002\u0002a\u0194",
    "\u0003\u0002\u0002\u0002c\u0198\u0003\u0002\u0002\u0002e\u01a0\u0003",
    "\u0002\u0002\u0002g\u01a2\u0003\u0002\u0002\u0002i\u01a4\u0003\u0002",
    "\u0002\u0002k\u01aa\u0003\u0002\u0002\u0002m\u01b7\u0003\u0002\u0002",
    "\u0002o\u01b9\u0003\u0002\u0002\u0002q\u01d8\u0003\u0002\u0002\u0002",
    "st\u0007r\u0002\u0002tu\u0007t\u0002\u0002uv\u0007q\u0002\u0002vw\u0007",
    "i\u0002\u0002wx\u0007t\u0002\u0002xy\u0007c\u0002\u0002yz\u0007o\u0002",
    "\u0002z{\u0007c\u0002\u0002{\u0004\u0003\u0002\u0002\u0002|}\u0007t",
    "\u0002\u0002}~\u0007g\u0002\u0002~\u007f\u0007c\u0002\u0002\u007f\u0080",
    "\u0007n\u0002\u0002\u0080\u0006\u0003\u0002\u0002\u0002\u0081\u0082",
    "\u0007x\u0002\u0002\u0082\u0083\u0007c\u0002\u0002\u0083\u0084\u0007",
    "|\u0002\u0002\u0084\u0085\u0007k\u0002\u0002\u0085\u0086\u0007q\u0002",
    "\u0002\u0086\b\u0003\u0002\u0002\u0002\u0087\u0088\u0007n\u0002\u0002",
    "\u0088\u0089\u0007q\u0002\u0002\u0089\u008a\u0007i\u0002\u0002\u008a",
    "\u008b\u0007k\u0002\u0002\u008b\u008c\u0007e\u0002\u0002\u008c\u008d",
    "\u0007q\u0002\u0002\u008d\n\u0003\u0002\u0002\u0002\u008e\u008f\u0007",
    "e\u0002\u0002\u008f\u0090\u0007c\u0002\u0002\u0090\u0091\u0007f\u0002",
    "\u0002\u0091\u0092\u0007g\u0002\u0002\u0092\u0093\u0007k\u0002\u0002",
    "\u0093\u0094\u0007c\u0002\u0002\u0094\f\u0003\u0002\u0002\u0002\u0095",
    "\u0096\u0007k\u0002\u0002\u0096\u0097\u0007p\u0002\u0002\u0097\u0098",
    "\u0007v\u0002\u0002\u0098\u0099\u0007g\u0002\u0002\u0099\u009a\u0007",
    "k\u0002\u0002\u009a\u009b\u0007t\u0002\u0002\u009b\u009c\u0007q\u0002",
    "\u0002\u009c\u000e\u0003\u0002\u0002\u0002\u009d\u009e\u0007e\u0002",
    "\u0002\u009e\u009f\u0007c\u0002\u0002\u009f\u00a0\u0007t\u0002\u0002",
    "\u00a0\u00a1\u0007c\u0002\u0002\u00a1\u00a2\u0007e\u0002\u0002\u00a2",
    "\u00a3\u0007v\u0002\u0002\u00a3\u00a4\u0007g\u0002\u0002\u00a4\u00a5",
    "\u0007t\u0002\u0002\u00a5\u00a6\u0007g\u0002\u0002\u00a6\u0010\u0003",
    "\u0002\u0002\u0002\u00a7\u00a8\u0007g\u0002\u0002\u00a8\u00a9\u0007",
    "u\u0002\u0002\u00a9\u00aa\u0007e\u0002\u0002\u00aa\u00ab\u0007q\u0002",
    "\u0002\u00ab\u00ac\u0007n\u0002\u0002\u00ac\u00ad\u0007j\u0002\u0002",
    "\u00ad\u00ae\u0007c\u0002\u0002\u00ae\u0012\u0003\u0002\u0002\u0002",
    "\u00af\u00b0\u0007e\u0002\u0002\u00b0\u00b1\u0007c\u0002\u0002\u00b1",
    "\u00b2\u0007u\u0002\u0002\u00b2\u00b3\u0007q\u0002\u0002\u00b3\u0014",
    "\u0003\u0002\u0002\u0002\u00b4\u00b5\u0007e\u0002\u0002\u00b5\u00b6",
    "\u0007q\u0002\u0002\u00b6\u00b7\u0007p\u0002\u0002\u00b7\u00b8\u0007",
    "v\u0002\u0002\u00b8\u00b9\u0007t\u0002\u0002\u00b9\u00ba\u0007c\u0002",
    "\u0002\u00ba\u00bb\u0007t\u0002\u0002\u00bb\u00bc\u0007k\u0002\u0002",
    "\u00bc\u00bd\u0007q\u0002\u0002\u00bd\u0016\u0003\u0002\u0002\u0002",
    "\u00be\u00bf\u0007e\u0002\u0002\u00bf\u00c0\u0007q\u0002\u0002\u00c0",
    "\u00c1\u0007p\u0002\u0002\u00c1\u00c2\u0007u\u0002\u0002\u00c2\u00c3",
    "\u0007v\u0002\u0002\u00c3\u0018\u0003\u0002\u0002\u0002\u00c4\u00c5",
    "\u0007h\u0002\u0002\u00c5\u00c6\u0007w\u0002\u0002\u00c6\u00c7\u0007",
    "p\u0002\u0002\u00c7\u00c8\u0007e\u0002\u0002\u00c8\u00c9\u0007c\u0002",
    "\u0002\u00c9\u00ca\u0007q\u0002\u0002\u00ca\u001a\u0003\u0002\u0002",
    "\u0002\u00cb\u00cc\u0007t\u0002\u0002\u00cc\u00cd\u0007g\u0002\u0002",
    "\u00cd\u00ce\u0007v\u0002\u0002\u00ce\u00cf\u0007q\u0002\u0002\u00cf",
    "\u00d0\u0007t\u0002\u0002\u00d0\u00d1\u0007p\u0002\u0002\u00d1\u00d2",
    "\u0007g\u0002\u0002\u00d2\u001c\u0003\u0002\u0002\u0002\u00d3\u00d4",
    "\u0007r\u0002\u0002\u00d4\u00d5\u0007c\u0002\u0002\u00d5\u00d6\u0007",
    "t\u0002\u0002\u00d6\u00d7\u0007c\u0002\u0002\u00d7\u001e\u0003\u0002",
    "\u0002\u0002\u00d8\u00d9\u0007r\u0002\u0002\u00d9\u00da\u0007c\u0002",
    "\u0002\u00da\u00db\u0007t\u0002\u0002\u00db\u00dc\u0007g\u0002\u0002",
    "\u00dc \u0003\u0002\u0002\u0002\u00dd\u00de\u0007h\u0002\u0002\u00de",
    "\u00df\u0007c\u0002\u0002\u00df\u00e0\u0007e\u0002\u0002\u00e0\u00e1",
    "\u0007c\u0002\u0002\u00e1\"\u0003\u0002\u0002\u0002\u00e2\u00e3\u0007",
    "g\u0002\u0002\u00e3\u00e4\u0007p\u0002\u0002\u00e4\u00e5\u0007s\u0002",
    "\u0002\u00e5\u00e6\u0007w\u0002\u0002\u00e6\u00e7\u0007c\u0002\u0002",
    "\u00e7\u00e8\u0007p\u0002\u0002\u00e8\u00e9\u0007v\u0002\u0002\u00e9",
    "\u00ea\u0007q\u0002\u0002\u00ea$\u0003\u0002\u0002\u0002\u00eb\u00ec",
    "\u0007u\u0002\u0002\u00ec\u00ed\u0007g\u0002\u0002\u00ed&\u0003\u0002",
    "\u0002\u0002\u00ee\u00ef\u0007u\u0002\u0002\u00ef\u00f0\u0007g\u0002",
    "\u0002\u00f0\u00f1\u0007p\u0002\u0002\u00f1\u00f2\u0007c\u0002\u0002",
    "\u00f2\u00f3\u0007q\u0002\u0002\u00f3(\u0003\u0002\u0002\u0002\u00f4",
    "\u00f5\u0007h\u0002\u0002\u00f5\u00f6\u0007c\u0002\u0002\u00f6\u00f7",
    "\u0007n\u0002\u0002\u00f7\u00f8\u0007u\u0002\u0002\u00f8\u00f9\u0007",
    "q\u0002\u0002\u00f9*\u0003\u0002\u0002\u0002\u00fa\u00fb\u0007x\u0002",
    "\u0002\u00fb\u00fc\u0007g\u0002\u0002\u00fc\u00fd\u0007t\u0002\u0002",
    "\u00fd\u00fe\u0007f\u0002\u0002\u00fe\u00ff\u0007c\u0002\u0002\u00ff",
    "\u0100\u0007f\u0002\u0002\u0100\u0101\u0007g\u0002\u0002\u0101\u0102",
    "\u0007k\u0002\u0002\u0102\u0103\u0007t\u0002\u0002\u0103\u0104\u0007",
    "q\u0002\u0002\u0104,\u0003\u0002\u0002\u0002\u0105\u0106\u0007p\u0002",
    "\u0002\u0106\u0107\u0007c\u0002\u0002\u0107\u0108\u0007q\u0002\u0002",
    "\u0108.\u0003\u0002\u0002\u0002\u0109\u010a\u0007G\u0002\u0002\u010a",
    "0\u0003\u0002\u0002\u0002\u010b\u010c\u0007Q\u0002\u0002\u010c\u010d",
    "\u0007W\u0002\u0002\u010d2\u0003\u0002\u0002\u0002\u010e\u010f\u0007",
    "*\u0002\u0002\u010f4\u0003\u0002\u0002\u0002\u0110\u0111\u0007+\u0002",
    "\u0002\u01116\u0003\u0002\u0002\u0002\u0112\u0113\u0007]\u0002\u0002",
    "\u01138\u0003\u0002\u0002\u0002\u0114\u0115\u0007_\u0002\u0002\u0115",
    ":\u0003\u0002\u0002\u0002\u0116\u0117\u0007}\u0002\u0002\u0117<\u0003",
    "\u0002\u0002\u0002\u0118\u0119\u0007\u007f\u0002\u0002\u0119>\u0003",
    "\u0002\u0002\u0002\u011a\u011b\u0007.\u0002\u0002\u011b@\u0003\u0002",
    "\u0002\u0002\u011c\u011d\u0007?\u0002\u0002\u011dB\u0003\u0002\u0002",
    "\u0002\u011e\u011f\t\u0002\u0002\u0002\u011fD\u0003\u0002\u0002\u0002",
    "\u0120\u0121\t\u0003\u0002\u0002\u0121F\u0003\u0002\u0002\u0002\u0122",
    "\u0123\u0005/\u0018\u0002\u0123H\u0003\u0002\u0002\u0002\u0124\u0125",
    "\u00051\u0019\u0002\u0125J\u0003\u0002\u0002\u0002\u0126\u0127\u0007",
    "@\u0002\u0002\u0127\u0130\u0007?\u0002\u0002\u0128\u0129\u0007?\u0002",
    "\u0002\u0129\u0130\u0007?\u0002\u0002\u012a\u012b\u0007>\u0002\u0002",
    "\u012b\u0130\u0007?\u0002\u0002\u012c\u0130\t\u0004\u0002\u0002\u012d",
    "\u012e\u0007#\u0002\u0002\u012e\u0130\u0007?\u0002\u0002\u012f\u0126",
    "\u0003\u0002\u0002\u0002\u012f\u0128\u0003\u0002\u0002\u0002\u012f\u012a",
    "\u0003\u0002\u0002\u0002\u012f\u012c\u0003\u0002\u0002\u0002\u012f\u012d",
    "\u0003\u0002\u0002\u0002\u0130L\u0003\u0002\u0002\u0002\u0131\u0132",
    "\u0007<\u0002\u0002\u0132N\u0003\u0002\u0002\u0002\u0133\u0134\u0005",
    "-\u0017\u0002\u0134P\u0003\u0002\u0002\u0002\u0135\u0139\t\u0005\u0002",
    "\u0002\u0136\u0138\t\u0006\u0002\u0002\u0137\u0136\u0003\u0002\u0002",
    "\u0002\u0138\u013b\u0003\u0002\u0002\u0002\u0139\u0137\u0003\u0002\u0002",
    "\u0002\u0139\u013a\u0003\u0002\u0002\u0002\u013aR\u0003\u0002\u0002",
    "\u0002\u013b\u0139\u0003\u0002\u0002\u0002\u013c\u013d\u0005Q)\u0002",
    "\u013d\u013e\u00070\u0002\u0002\u013e\u013f\u0005Q)\u0002\u013fT\u0003",
    "\u0002\u0002\u0002\u0140\u0142\t\u0007\u0002\u0002\u0141\u0140\u0003",
    "\u0002\u0002\u0002\u0142\u0143\u0003\u0002\u0002\u0002\u0143\u0141\u0003",
    "\u0002\u0002\u0002\u0143\u0144\u0003\u0002\u0002\u0002\u0144\u015c\u0003",
    "\u0002\u0002\u0002\u0145\u0146\u00072\u0002\u0002\u0146\u014a\u0007",
    "z\u0002\u0002\u0147\u0148\u00072\u0002\u0002\u0148\u014a\u0007Z\u0002",
    "\u0002\u0149\u0145\u0003\u0002\u0002\u0002\u0149\u0147\u0003\u0002\u0002",
    "\u0002\u014a\u014c\u0003\u0002\u0002\u0002\u014b\u014d\u0005g4\u0002",
    "\u014c\u014b\u0003\u0002\u0002\u0002\u014d\u014e\u0003\u0002\u0002\u0002",
    "\u014e\u014c\u0003\u0002\u0002\u0002\u014e\u014f\u0003\u0002\u0002\u0002",
    "\u014f\u015c\u0003\u0002\u0002\u0002\u0150\u0151\u00072\u0002\u0002",
    "\u0151\u0155\u0007d\u0002\u0002\u0152\u0153\u00072\u0002\u0002\u0153",
    "\u0155\u0007D\u0002\u0002\u0154\u0150\u0003\u0002\u0002\u0002\u0154",
    "\u0152\u0003\u0002\u0002\u0002\u0155\u0157\u0003\u0002\u0002\u0002\u0156",
    "\u0158\t\b\u0002\u0002\u0157\u0156\u0003\u0002\u0002\u0002\u0158\u0159",
    "\u0003\u0002\u0002\u0002\u0159\u0157\u0003\u0002\u0002\u0002\u0159\u015a",
    "\u0003\u0002\u0002\u0002\u015a\u015c\u0003\u0002\u0002\u0002\u015b\u0141",
    "\u0003\u0002\u0002\u0002\u015b\u0149\u0003\u0002\u0002\u0002\u015b\u0154",
    "\u0003\u0002\u0002\u0002\u015cV\u0003\u0002\u0002\u0002\u015d\u015f",
    "\t\u0007\u0002\u0002\u015e\u015d\u0003\u0002\u0002\u0002\u015f\u0160",
    "\u0003\u0002\u0002\u0002\u0160\u015e\u0003\u0002\u0002\u0002\u0160\u0161",
    "\u0003\u0002\u0002\u0002\u0161\u0162\u0003\u0002\u0002\u0002\u0162\u0164",
    "\u00070\u0002\u0002\u0163\u0165\t\u0007\u0002\u0002\u0164\u0163\u0003",
    "\u0002\u0002\u0002\u0165\u0166\u0003\u0002\u0002\u0002\u0166\u0164\u0003",
    "\u0002\u0002\u0002\u0166\u0167\u0003\u0002\u0002\u0002\u0167\u0176\u0003",
    "\u0002\u0002\u0002\u0168\u016a\t\u0007\u0002\u0002\u0169\u0168\u0003",
    "\u0002\u0002\u0002\u016a\u016b\u0003\u0002\u0002\u0002\u016b\u0169\u0003",
    "\u0002\u0002\u0002\u016b\u016c\u0003\u0002\u0002\u0002\u016c\u016d\u0003",
    "\u0002\u0002\u0002\u016d\u0171\u00070\u0002\u0002\u016e\u0170\t\u0007",
    "\u0002\u0002\u016f\u016e\u0003\u0002\u0002\u0002\u0170\u0173\u0003\u0002",
    "\u0002\u0002\u0171\u016f\u0003\u0002\u0002\u0002\u0171\u0172\u0003\u0002",
    "\u0002\u0002\u0172\u0174\u0003\u0002\u0002\u0002\u0173\u0171\u0003\u0002",
    "\u0002\u0002\u0174\u0176\u0005Y-\u0002\u0175\u015e\u0003\u0002\u0002",
    "\u0002\u0175\u0169\u0003\u0002\u0002\u0002\u0176X\u0003\u0002\u0002",
    "\u0002\u0177\u0179\t\t\u0002\u0002\u0178\u017a\t\u0002\u0002\u0002\u0179",
    "\u0178\u0003\u0002\u0002\u0002\u0179\u017a\u0003\u0002\u0002\u0002\u017a",
    "\u017c\u0003\u0002\u0002\u0002\u017b\u017d\t\u0007\u0002\u0002\u017c",
    "\u017b\u0003\u0002\u0002\u0002\u017d\u017e\u0003\u0002\u0002\u0002\u017e",
    "\u017c\u0003\u0002\u0002\u0002\u017e\u017f\u0003\u0002\u0002\u0002\u017f",
    "Z\u0003\u0002\u0002\u0002\u0180\u0184\u0007$\u0002\u0002\u0181\u0183",
    "\u0005]/\u0002\u0182\u0181\u0003\u0002\u0002\u0002\u0183\u0186\u0003",
    "\u0002\u0002\u0002\u0184\u0182\u0003\u0002\u0002\u0002\u0184\u0185\u0003",
    "\u0002\u0002\u0002\u0185\u0187\u0003\u0002\u0002\u0002\u0186\u0184\u0003",
    "\u0002\u0002\u0002\u0187\u0188\u0007$\u0002\u0002\u0188\\\u0003\u0002",
    "\u0002\u0002\u0189\u018c\n\n\u0002\u0002\u018a\u018c\u0005k6\u0002\u018b",
    "\u0189\u0003\u0002\u0002\u0002\u018b\u018a\u0003\u0002\u0002\u0002\u018c",
    "^\u0003\u0002\u0002\u0002\u018d\u0190\u0007)\u0002\u0002\u018e\u0191",
    "\u0005k6\u0002\u018f\u0191\n\u000b\u0002\u0002\u0190\u018e\u0003\u0002",
    "\u0002\u0002\u0190\u018f\u0003\u0002\u0002\u0002\u0191\u0192\u0003\u0002",
    "\u0002\u0002\u0192\u0193\u0007)\u0002\u0002\u0193`\u0003\u0002\u0002",
    "\u0002\u0194\u0195\t\f\u0002\u0002\u0195\u0196\u0003\u0002\u0002\u0002",
    "\u0196\u0197\b1\u0002\u0002\u0197b\u0003\u0002\u0002\u0002\u0198\u0199",
    "\u0007=\u0002\u0002\u0199d\u0003\u0002\u0002\u0002\u019a\u019c\t\r\u0002",
    "\u0002\u019b\u019a\u0003\u0002\u0002\u0002\u019c\u019d\u0003\u0002\u0002",
    "\u0002\u019d\u019b\u0003\u0002\u0002\u0002\u019d\u019e\u0003\u0002\u0002",
    "\u0002\u019e\u01a1\u0003\u0002\u0002\u0002\u019f\u01a1\u0005c2\u0002",
    "\u01a0\u019b\u0003\u0002\u0002\u0002\u01a0\u019f\u0003\u0002\u0002\u0002",
    "\u01a1f\u0003\u0002\u0002\u0002\u01a2\u01a3\t\u000e\u0002\u0002\u01a3",
    "h\u0003\u0002\u0002\u0002\u01a4\u01a5\t\u000f\u0002\u0002\u01a5j\u0003",
    "\u0002\u0002\u0002\u01a6\u01a7\u0007^\u0002\u0002\u01a7\u01ab\t\u0010",
    "\u0002\u0002\u01a8\u01ab\u0005o8\u0002\u01a9\u01ab\u0005m7\u0002\u01aa",
    "\u01a6\u0003\u0002\u0002\u0002\u01aa\u01a8\u0003\u0002\u0002\u0002\u01aa",
    "\u01a9\u0003\u0002\u0002\u0002\u01abl\u0003\u0002\u0002\u0002\u01ac",
    "\u01ad\u0007^\u0002\u0002\u01ad\u01ae\t\u0011\u0002\u0002\u01ae\u01af",
    "\u0005i5\u0002\u01af\u01b0\u0005i5\u0002\u01b0\u01b8\u0003\u0002\u0002",
    "\u0002\u01b1\u01b2\u0007^\u0002\u0002\u01b2\u01b3\u0005i5\u0002\u01b3",
    "\u01b4\u0005i5\u0002\u01b4\u01b8\u0003\u0002\u0002\u0002\u01b5\u01b6",
    "\u0007^\u0002\u0002\u01b6\u01b8\u0005i5\u0002\u01b7\u01ac\u0003\u0002",
    "\u0002\u0002\u01b7\u01b1\u0003\u0002\u0002\u0002\u01b7\u01b5\u0003\u0002",
    "\u0002\u0002\u01b8n\u0003\u0002\u0002\u0002\u01b9\u01ba\u0007^\u0002",
    "\u0002\u01ba\u01bb\u0007w\u0002\u0002\u01bb\u01bc\u0005g4\u0002\u01bc",
    "\u01bd\u0005g4\u0002\u01bd\u01be\u0005g4\u0002\u01be\u01bf\u0005g4\u0002",
    "\u01bfp\u0003\u0002\u0002\u0002\u01c0\u01c1\u00071\u0002\u0002\u01c1",
    "\u01c2\u00071\u0002\u0002\u01c2\u01c6\u0003\u0002\u0002\u0002\u01c3",
    "\u01c5\n\r\u0002\u0002\u01c4\u01c3\u0003\u0002\u0002\u0002\u01c5\u01c8",
    "\u0003\u0002\u0002\u0002\u01c6\u01c4\u0003\u0002\u0002\u0002\u01c6\u01c7",
    "\u0003\u0002\u0002\u0002\u01c7\u01ca\u0003\u0002\u0002\u0002\u01c8\u01c6",
    "\u0003\u0002\u0002\u0002\u01c9\u01cb\u0007\u000f\u0002\u0002\u01ca\u01c9",
    "\u0003\u0002\u0002\u0002\u01ca\u01cb\u0003\u0002\u0002\u0002\u01cb\u01cc",
    "\u0003\u0002\u0002\u0002\u01cc\u01d9\u0007\f\u0002\u0002\u01cd\u01ce",
    "\u00071\u0002\u0002\u01ce\u01cf\u0007,\u0002\u0002\u01cf\u01d3\u0003",
    "\u0002\u0002\u0002\u01d0\u01d2\u000b\u0002\u0002\u0002\u01d1\u01d0\u0003",
    "\u0002\u0002\u0002\u01d2\u01d5\u0003\u0002\u0002\u0002\u01d3\u01d4\u0003",
    "\u0002\u0002\u0002\u01d3\u01d1\u0003\u0002\u0002\u0002\u01d4\u01d6\u0003",
    "\u0002\u0002\u0002\u01d5\u01d3\u0003\u0002\u0002\u0002\u01d6\u01d7\u0007",
    ",\u0002\u0002\u01d7\u01d9\u00071\u0002\u0002\u01d8\u01c0\u0003\u0002",
    "\u0002\u0002\u01d8\u01cd\u0003\u0002\u0002\u0002\u01d9\u01da\u0003\u0002",
    "\u0002\u0002\u01da\u01db\b9\u0003\u0002\u01dbr\u0003\u0002\u0002\u0002",
    "\u001d\u0002\u012f\u0139\u0143\u0149\u014e\u0154\u0159\u015b\u0160\u0166",
    "\u016b\u0171\u0175\u0179\u017e\u0184\u018b\u0190\u019d\u01a0\u01aa\u01b7",
    "\u01c6\u01ca\u01d3\u01d8\u0004\b\u0002\u0002\u0002\u0003\u0002"].join("");


var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);

var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); });

function ivprog(input) {
	antlr4.Lexer.call(this, input);
    this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.PredictionContextCache());
    return this;
}

ivprog.prototype = Object.create(antlr4.Lexer.prototype);
ivprog.prototype.constructor = ivprog;

ivprog.EOF = antlr4.Token.EOF;
ivprog.RK_PROGRAM = 1;
ivprog.RK_REAL = 2;
ivprog.RK_VOID = 3;
ivprog.RK_BOOLEAN = 4;
ivprog.RK_STRING = 5;
ivprog.RK_INTEGER = 6;
ivprog.RK_CHARACTER = 7;
ivprog.RK_SWITCH = 8;
ivprog.RK_CASE = 9;
ivprog.RK_DEFAULT = 10;
ivprog.RK_CONST = 11;
ivprog.RK_FUNCTION = 12;
ivprog.RK_RETURN = 13;
ivprog.RK_FOR = 14;
ivprog.RK_BREAK = 15;
ivprog.RK_DO = 16;
ivprog.RK_WHILE = 17;
ivprog.RK_IF = 18;
ivprog.RK_ELSE = 19;
ivprog.RK_FALSE = 20;
ivprog.RK_TRUE = 21;
ivprog.OPEN_PARENTHESIS = 22;
ivprog.CLOSE_PARENTHESIS = 23;
ivprog.OPEN_BRACE = 24;
ivprog.CLOSE_BRACE = 25;
ivprog.OPEN_CURLY = 26;
ivprog.CLOSE_CURLY = 27;
ivprog.COMMA = 28;
ivprog.EQUAL = 29;
ivprog.SUM_OP = 30;
ivprog.MULTI_OP = 31;
ivprog.AND_OPERATOR = 32;
ivprog.OR_OPERATOR = 33;
ivprog.RELATIONAL_OPERATOR = 34;
ivprog.COLON = 35;
ivprog.NOT_OPERATOR = 36;
ivprog.ID = 37;
ivprog.LIB_ID = 38;
ivprog.INTEGER = 39;
ivprog.REAL = 40;
ivprog.STRING = 41;
ivprog.CHARACTER = 42;
ivprog.WHITESPACE = 43;
ivprog.EOS = 44;
ivprog.COMMENTS = 45;

ivprog.prototype.channelNames = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN" ];

ivprog.prototype.modeNames = [ "DEFAULT_MODE" ];

ivprog.prototype.literalNames = [ null, "'programa'", "'real'", "'vazio'", 
                                  "'logico'", "'cadeia'", "'inteiro'", "'caractere'", 
                                  "'escolha'", "'caso'", "'contrario'", 
                                  "'const'", "'funcao'", "'retorne'", "'para'", 
                                  "'pare'", "'faca'", "'enquanto'", "'se'", 
                                  "'senao'", "'falso'", "'verdadeiro'", 
                                  "'('", "')'", "'['", "']'", "'{'", "'}'", 
                                  "','", "'='", null, null, null, null, 
                                  null, "':'" ];

ivprog.prototype.symbolicNames = [ null, "RK_PROGRAM", "RK_REAL", "RK_VOID", 
                                   "RK_BOOLEAN", "RK_STRING", "RK_INTEGER", 
                                   "RK_CHARACTER", "RK_SWITCH", "RK_CASE", 
                                   "RK_DEFAULT", "RK_CONST", "RK_FUNCTION", 
                                   "RK_RETURN", "RK_FOR", "RK_BREAK", "RK_DO", 
                                   "RK_WHILE", "RK_IF", "RK_ELSE", "RK_FALSE", 
                                   "RK_TRUE", "OPEN_PARENTHESIS", "CLOSE_PARENTHESIS", 
                                   "OPEN_BRACE", "CLOSE_BRACE", "OPEN_CURLY", 
                                   "CLOSE_CURLY", "COMMA", "EQUAL", "SUM_OP", 
                                   "MULTI_OP", "AND_OPERATOR", "OR_OPERATOR", 
                                   "RELATIONAL_OPERATOR", "COLON", "NOT_OPERATOR", 
                                   "ID", "LIB_ID", "INTEGER", "REAL", "STRING", 
                                   "CHARACTER", "WHITESPACE", "EOS", "COMMENTS" ];

ivprog.prototype.ruleNames = [ "RK_PROGRAM", "RK_REAL", "RK_VOID", "RK_BOOLEAN", 
                               "RK_STRING", "RK_INTEGER", "RK_CHARACTER", 
                               "RK_SWITCH", "RK_CASE", "RK_DEFAULT", "RK_CONST", 
                               "RK_FUNCTION", "RK_RETURN", "RK_FOR", "RK_BREAK", 
                               "RK_DO", "RK_WHILE", "RK_IF", "RK_ELSE", 
                               "RK_FALSE", "RK_TRUE", "RK_LOGICAL_NOT", 
                               "RK_LOGICAL_AND", "RK_LOGICAL_OR", "OPEN_PARENTHESIS", 
                               "CLOSE_PARENTHESIS", "OPEN_BRACE", "CLOSE_BRACE", 
                               "OPEN_CURLY", "CLOSE_CURLY", "COMMA", "EQUAL", 
                               "SUM_OP", "MULTI_OP", "AND_OPERATOR", "OR_OPERATOR", 
                               "RELATIONAL_OPERATOR", "COLON", "NOT_OPERATOR", 
                               "ID", "LIB_ID", "INTEGER", "REAL", "ExponentPart", 
                               "STRING", "STRING_CHARACTER", "CHARACTER", 
                               "WHITESPACE", "SEMICOLON", "EOS", "HEX_DIGIT", 
                               "OCTAL_DIGIT", "ESC_SEQ", "ESC_OCTAL", "ESC_UNICODE", 
                               "COMMENTS" ];

ivprog.prototype.grammarFileName = "ivprog.g4";



exports.ivprog = ivprog;



/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = {
ivprog: __webpack_require__(0).ivprog
};


/***/ }),
/* 2 */
/***/ (function(module, exports) {

module.exports = __webpack_require__(/*! antlr4/index */ "./node_modules/antlr4/index.js");

/***/ })
/******/ ]);

/***/ }),

/***/ "./grammar/pt/langFunctions.js":
/*!*************************************!*\
  !*** ./grammar/pt/langFunctions.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/* This is a dictionary of the language defined functions
**/
exports.default = {
  main_function: "inicio",
  $read: "leia",
  $write: "escreva",
  $numElements: "total_de_elementos",
  $matrixLines: "total_de_linhas",
  $matrixColumns: "total_de_colunas",
  $substring: "subcadeia",
  $length: "comprimento",
  $uppercase: "caixa_alta",
  $lowercase: "caixa_baixa",
  $charAt: "char_at",
  $isReal: "e_real",
  $isInt: "e_inteiro",
  $isBool: "e_logico",
  $castReal: "como_real",
  $castInt: "como_inteiro",
  $castBool: "como_logico",
  $castString: "como_cadeia",
  $sin: "seno",
  $cos: "cosseno",
  $tan: "tangente",
  $sqrt: "raiz_quadrada",
  $pow: "potencia",
  $log: "logaritmo",
  $abs: "modulo",
  $negate: "trocar_sinal",
  $invert: "inverter_valor",
  $max: "maximo",
  $min: "minimo"
};

/***/ }),

/***/ "./grammar/pt/langLibs.js":
/*!********************************!*\
  !*** ./grammar/pt/langLibs.js ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * This is the dictionary of the language defined libraries
 */
exports.default = {
  $mathLib: "Matematica",
  $ioLib: "ES",
  $strLib: "Texto",
  $arrayLib: "Arranjo",
  $langLib: "Conversao"
};

/***/ }),

/***/ "./i18n/en/error.json":
/*!****************************!*\
  !*** ./i18n/en/error.json ***!
  \****************************/
/*! exports provided: token_missing_one, token_missing_two, eos_missing, invalid_type, invalid_array_dimension, invalid_array_size, extra_lines, invalid_main_return, invalid_var_declaration, invalid_break_command, invalid_terminal, id_missing, main_missing, invalid_global_var, not_implemented, function_missing, invalid_parameters_size, invalid_ref, invalid_parameter_type, unknown_command, loop_condition_type, if_condition_type, invalid_return_type, unexpected_break_command, invalid_dimension, void_in_expression, invalid_array, invalid_array_access, column_outbounds, line_outbounds, invalid_infix_op, invalid_unary_op, unknown_op, default */
/***/ (function(module) {

module.exports = {"token_missing_one":"Erro de sintaxe: Espera-se $0, mas encontrou-se $1 na linha:$2, coluna:$3","token_missing_two":"Erro de sintaxe: Esperava-se $0 ou $1 mas encontrou-se $2 na liha:$3, coluna: $4","eos_missing":"Falta uma nova linha ou ; na linha: $0, coluna: $1","invalid_type":"$0 na linha: $1, coluna: $2 é um tipo inválido. Os tipos válidos são: $3","invalid_array_dimension":"A dimensão inválida na linha: $0, coluna: $1. Insira um $2 ou identificador válido do mesmo tipo.","invalid_array_size":"O tamnho do vetor/matriz excede o máximo de 2 na linha $0","extra_lines":"Nenhum texto é permitido após '}' em 'programa {...}'","invalid_main_return":"A função $0 deve retornar $1 na linha $2","invalid_var_declaration":"Erro na linha $0. Variáveis só podem ser declarados no corpo principal da função e de preferência nas primeiras linhas.","invalid_break_command":"Erro na linha $0. O comando $1 não pode ser usado fora de uma estrutura de repetição ou 'escolha...caso'","invalid_terminal":"Não é possível utilizar $0 na expressão da linha: $1, coluna: $2. Tente um valor númerico, variável ou chamada de função.","id_missing":"Esperava-se um identificador, mas encontrou-se $0 na linha: $1, coluna: $2","main_missing":"A função principal não foi encontrada","invalid_global_var":"Erro crítico: Chamada inválida da função initGlobal fora do contexto BASE","not_implemented":"Erro interno crítico: A função definida pelo sistema $0 não foi implementada.","function_missing":"A função $0 não foi encontrada","invalid_parameters_size":"A quantidade de parâmetros fornecidos está incorreta. Esperava-se $0, encontrou-se $1","invalid_ref":"Você deve fornecer apenas um identificador como parâmetro","invalid_parameter_type":"O valor fornecido como parâmetro é do tipo $0, mas o tipo esperado é $1","unknown_command":"Erro interno crítico: Comando desconhecido encontrado","loop_condition_type":"A condição dos laços de repetição deve ser do tipo lógico","if_condition_type":"A condição de um comando se...senao deve ser do tipo lógico","invalid_return_type":"A função $0 deve retornar um tipo $1, ao invés de $1","unexpected_break_command":"Erro interno crítico: Comando pare encontrado fora do contexto de um laço/escolha..caso","invalid_dimension":"As dimensões de um vetor/matriz devem ser do tipo inteiro","void_in_expression":"A função $0 não pode ser utilizada aqui pois seu tipo de retorno é vazio","invalid_array":"Expressão literal de Vetor/Mariz inválida","invalid_array_access":"Identificador $0 não se refere a um vetor/matriz válido","column_outbounds":"Número de colunas $0 é inválido para a matriz $1 que possui $2 colunas","line_outbounds":"Número de linhas $0 é invaálido para a matriz $1 que possui $2 linhas","invalid_infix_op":"Não é possível aplicar a operação $0 entre os tipos $1 e $2","invalid_unary_op":"Não é possível aplicar a operação $0 ao tipo $1","unknown_op":"Erro interno crítico: Operação $0 desconhecida"};

/***/ }),

/***/ "./i18n/en/index.js":
/*!**************************!*\
  !*** ./i18n/en/index.js ***!
  \**************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _error = __webpack_require__(/*! ./error.json */ "./i18n/en/error.json");

var _error2 = _interopRequireDefault(_error);

var _message = __webpack_require__(/*! ./message.json */ "./i18n/en/message.json");

var _message2 = _interopRequireDefault(_message);

var _ui = __webpack_require__(/*! ./ui.json */ "./i18n/en/ui.json");

var _ui2 = _interopRequireDefault(_ui);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = {
  'message': _message2.default,
  'error': _error2.default,
  'ui': _ui2.default
};

/***/ }),

/***/ "./i18n/en/message.json":
/*!******************************!*\
  !*** ./i18n/en/message.json ***!
  \******************************/
/*! exports provided: default */
/***/ (function(module) {

module.exports = {};

/***/ }),

/***/ "./i18n/en/ui.json":
/*!*************************!*\
  !*** ./i18n/en/ui.json ***!
  \*************************/
/*! exports provided: function, btn_clear, btn_function, btn_arithmetic_plus, btn_arithmetic_minus, btn_arithmetic_multiplication, btn_arithmetic_division, btn_arithmetic_module, btn_break, btn_case, start, void, integer, real, program, text, text_start, boolean, true, false, variable, command, new_parameter, new_variable, new_global, new_function, vector, text_comment_start, text_comment_main, text_read_var, text_write_var, text_command_read, text_command_write, text_comment, text_attribution, text_if, text_else, text_break, text_for, text_code_while, text_code_do, text_command_do, text_code_switch, text_code_case, text_logic_expression, text_arithmetic_expression, text_iftrue, text_receives, text_repeatNtimes, text_return, text_btn_return, text_whiletrue, text_dowhiletrue, text_switch, text_functioncall, text_value, text_operator, text_parentheses, text_change, text_teacher_algorithm, text_teacher_algorithm_include, text_teacher_test_case, text_teacher_config, text_teacher_data_types, text_teacher_commands, text_teacher_functions, text_teacher_create_functions, text_teacher_create_movement_functions, text_teacher_test_case_input, text_teacher_test_case_output, text_teacher_test_case_actions, text_teacher_test_case_add, text_header_ivprog_functions, text_menu_functions_math, text_menu_functions_text, text_menu_functions_arrangement, text_menu_functions_conversion, text_none_variable, text_none_variable_instruction, text_ivprog_description, tooltip_visual, tooltip_textual, tooltip_upload, tooltip_download, tooltip_undo, tooltip_redo, tooltip_run, tooltip_evaluate, tooltip_help, tooltip_add_global, tooltip_minimize, tooltip_console, var_menu_select_var, var_menu_select_all, var_menu_select_function, expression_menu_select, math, text_t, inform_valid_name, inform_valid_content, inform_valid_expression, inform_valid_name_duplicated, inform_valid_global_duplicated, inform_valid_variable_duplicated, arrangement, conversion, $sin, $cos, $tan, $sqrt, $pow, $log, $abs, $negate, $invert, $max, $min, $substring, $length, $uppercase, $lowercase, $charAt, $numElements, $matrixLines, $matrixColumns, $isReal, $isInt, $isBool, $castReal, $castInt, $castBool, $castString, text_ivprog_version, default */
/***/ (function(module) {

module.exports = {"function":"function","btn_clear":"Clear","btn_function":"Function","btn_arithmetic_plus":"Sum","btn_arithmetic_minus":"Minus","btn_arithmetic_multiplication":"Multiplication","btn_arithmetic_division":"Division","btn_arithmetic_module":"Module","btn_break":"Break","btn_case":"Case","start":"start","void":"void","integer":"integer","real":"real","program":"program","text":"string","text_start":"text","boolean":"boolean","true":"true","false":"false","variable":"Variable","command":"Command","new_parameter":"new_parameter","new_variable":"new_variable","new_global":"new_global","new_function":"new_function","vector":"vector","text_comment_start":"Initial comment of function...","text_comment_main":"This is the main function...","text_read_var":"Reading data","text_write_var":"Writing data","text_command_read":"read","text_command_write":"write","text_comment":"Comment","text_attribution":"Attribution","text_if":"if","text_else":"else","text_break":"break","text_for":"for","text_code_while":"while","text_code_do":"do","text_command_do":"do","text_code_switch":"switch","text_code_case":"case","text_logic_expression":"Logic Expression","text_arithmetic_expression":"Relational Expression","text_iftrue":"If true then","text_receives":"receives","text_repeatNtimes":"Repeat N times","text_return":"return","text_btn_return":"Return","text_whiletrue":"While true","text_dowhiletrue":"Do while true","text_switch":"Switch","text_functioncall":"Function call","text_value":"Value","text_operator":"Operator","text_parentheses":"Parentheses","text_change":"Change","text_teacher_algorithm":"Algorithm","text_teacher_algorithm_include":"Include the following algorithm in exercise","text_teacher_test_case":"Test cases","text_teacher_config":"Settings","text_teacher_data_types":"Data types","text_teacher_commands":"Commands","text_teacher_functions":"Functions","text_teacher_create_functions":"Create new functions","text_teacher_create_movement_functions":"Move functions","text_teacher_test_case_input":"Input","text_teacher_test_case_output":"Output","text_teacher_test_case_actions":"Actions","text_teacher_test_case_add":"Add test cases","text_header_ivprog_functions":"iVProg Functions","text_menu_functions_math":"Mathematic","text_menu_functions_text":"Text","text_menu_functions_arrangement":"Arrangement","text_menu_functions_conversion":"Conversion","text_none_variable":"There is no declared variable","text_none_variable_instruction":"Create a new variable to use it","text_ivprog_description":"Interactive Visual Programming on the Internet","tooltip_visual":"Visual programming","tooltip_textual":"Textual programming","tooltip_upload":"Upload code file","tooltip_download":"Download code file","tooltip_undo":"Undo","tooltip_redo":"Redo","tooltip_run":"Run program","tooltip_evaluate":"Evaluate program","tooltip_help":"Help","tooltip_add_global":"Add global variable","tooltip_minimize":"Hidde function elements","tooltip_console":"Open/Close console","var_menu_select_var":"Select a var","var_menu_select_all":"Select","var_menu_select_function":"Select a function","expression_menu_select":"Construct any logical condition","math":"Mathematic","text_t":"Text","inform_valid_name":"Inform a valid name!","inform_valid_content":"Enter some content!","inform_valid_expression":"Construct the logical condition!","inform_valid_name_duplicated":"This name is already in use by other function.","inform_valid_global_duplicated":"A global variable with this name already exists.","inform_valid_variable_duplicated":"A local variable with this name already exists.","arrangement":"Arrangement","conversion":"Conversion","$sin":"sin","$cos":"cos","$tan":"tan","$sqrt":"sqrt","$pow":"pow","$log":"log","$abs":"abs","$negate":"negate","$invert":"invert","$max":"maximum","$min":"minimum","$substring":"substring","$length":"length","$uppercase":"uppercase","$lowercase":"lowercase","$charAt":"char_at","$numElements":"total_of_elements","$matrixLines":"total_of_lines","$matrixColumns":"total_of_columns","$isReal":"is_real","$isInt":"is_integer","$isBool":"is_logic","$castReal":"to_real","$castInt":"to_integer","$castBool":"to_logic","$castString":"to_string","text_ivprog_version":"Version 2018_12_19 Build 13_18"};

/***/ }),

/***/ "./i18n/es/error.json":
/*!****************************!*\
  !*** ./i18n/es/error.json ***!
  \****************************/
/*! exports provided: default */
/***/ (function(module) {

module.exports = {};

/***/ }),

/***/ "./i18n/es/index.js":
/*!**************************!*\
  !*** ./i18n/es/index.js ***!
  \**************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _error = __webpack_require__(/*! ./error.json */ "./i18n/es/error.json");

var _error2 = _interopRequireDefault(_error);

var _message = __webpack_require__(/*! ./message.json */ "./i18n/es/message.json");

var _message2 = _interopRequireDefault(_message);

var _ui = __webpack_require__(/*! ./ui.json */ "./i18n/es/ui.json");

var _ui2 = _interopRequireDefault(_ui);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = {
  'message': _message2.default,
  'error': _error2.default,
  'ui': _ui2.default
};

/***/ }),

/***/ "./i18n/es/message.json":
/*!******************************!*\
  !*** ./i18n/es/message.json ***!
  \******************************/
/*! exports provided: default */
/***/ (function(module) {

module.exports = {};

/***/ }),

/***/ "./i18n/es/ui.json":
/*!*************************!*\
  !*** ./i18n/es/ui.json ***!
  \*************************/
/*! exports provided: function, btn_clear, btn_function, btn_arithmetic_plus, btn_arithmetic_minus, btn_arithmetic_multiplication, btn_arithmetic_division, btn_arithmetic_module, btn_break, btn_case, start, void, integer, real, program, text, text_start, boolean, true, false, variable, command, new_parameter, new_variable, new_global, new_function, vector, text_comment_start, text_comment_main, text_read_var, text_write_var, text_command_read, text_command_write, text_comment, text_attribution, text_if, text_break, text_else, text_return, text_btn_return, text_for, text_code_while, text_code_do, text_command_do, text_code_switch, text_code_case, text_logic_expression, text_arithmetic_expression, text_iftrue, text_repeatNtimes, text_receives, text_whiletrue, text_dowhiletrue, text_switch, text_functioncall, text_value, text_operator, text_parentheses, text_change, text_teacher_algorithm, text_teacher_algorithm_include, text_teacher_test_case, text_teacher_config, text_teacher_data_types, text_teacher_commands, text_teacher_functions, text_teacher_create_functions, text_teacher_create_movement_functions, text_teacher_test_case_input, text_teacher_test_case_output, text_teacher_test_case_actions, text_teacher_test_case_add, text_header_ivprog_functions, text_menu_functions_math, text_menu_functions_text, text_menu_functions_arrangement, text_menu_functions_conversion, text_none_variable, text_none_variable_instruction, text_ivprog_description, tooltip_visual, tooltip_textual, tooltip_upload, tooltip_download, tooltip_undo, tooltip_redo, tooltip_run, tooltip_evaluate, tooltip_help, tooltip_add_global, tooltip_minimize, tooltip_console, var_menu_select_var, var_menu_select_all, var_menu_select_function, expression_menu_select, $sin, math, arrangement, conversion, inform_valid_name, inform_valid_content, inform_valid_expression, inform_valid_name_duplicated, inform_valid_global_duplicated, inform_valid_variable_duplicated, text_t, $cos, $tan, $sqrt, $pow, $log, $abs, $negate, $invert, $max, $min, $substring, $length, $uppercase, $lowercase, $charAt, $numElements, $matrixLines, $matrixColumns, $isReal, $isInt, $isBool, $castReal, $castInt, $castBool, $castString, text_ivprog_version, default */
/***/ (function(module) {

module.exports = {"function":"function","btn_clear":"Clear","btn_function":"Function","btn_arithmetic_plus":"Sum","btn_arithmetic_minus":"Minus","btn_arithmetic_multiplication":"Multiplication","btn_arithmetic_division":"Division","btn_arithmetic_module":"Module","btn_break":"Break","btn_case":"Case","start":"start","void":"void","integer":"integer","real":"real","program":"program","text":"Text","text_start":"text","boolean":"boolean","true":"true","false":"false","variable":"Variable","command":"Command","new_parameter":"new_parameter","new_variable":"new_variable","new_global":"new_global","new_function":"new_function","vector":"vector","text_comment_start":"Initial comment of function...","text_comment_main":"This is the main function...","text_read_var":"Reading data","text_write_var":"Writing data","text_command_read":"read","text_command_write":"write","text_comment":"Comment","text_attribution":"Attribution","text_if":"if","text_break":"break","text_else":"else","text_return":"return","text_btn_return":"Return","text_for":"for","text_code_while":"while","text_code_do":"do","text_command_do":"do","text_code_switch":"switch","text_code_case":"case","text_logic_expression":"Logic Expression","text_arithmetic_expression":"Relational Expression","text_iftrue":"If true then","text_repeatNtimes":"Repeat N times","text_receives":"receives","text_whiletrue":"While true","text_dowhiletrue":"Do while true","text_switch":"Switch","text_functioncall":"Function call","text_value":"Value","text_operator":"Operator","text_parentheses":"Parentheses","text_change":"Change","text_teacher_algorithm":"Algorithm","text_teacher_algorithm_include":"Include the following algorithm in exercise","text_teacher_test_case":"Test cases","text_teacher_config":"Settings","text_teacher_data_types":"Data types","text_teacher_commands":"Commands","text_teacher_functions":"Functions","text_teacher_create_functions":"Create new functions","text_teacher_create_movement_functions":"Move functions","text_teacher_test_case_input":"Input","text_teacher_test_case_output":"Output","text_teacher_test_case_actions":"Actions","text_teacher_test_case_add":"Add test cases","text_header_ivprog_functions":"iVProg Functions","text_menu_functions_math":"Mathematics","text_menu_functions_text":"Text","text_menu_functions_arrangement":"Arrangement","text_menu_functions_conversion":"Conversion","text_none_variable":"There is no declared variable","text_none_variable_instruction":"Create a new variable to use it","text_ivprog_description":"Interactive Visual Programming on the Internet","tooltip_visual":"Visual programming","tooltip_textual":"Textual programming","tooltip_upload":"Upload code file","tooltip_download":"Download code file","tooltip_undo":"Undo","tooltip_redo":"Redo","tooltip_run":"Run program","tooltip_evaluate":"Evaluate program","tooltip_help":"Help","tooltip_add_global":"Add global variable","tooltip_minimize":"Hidde function elements","tooltip_console":"Open/Close console","var_menu_select_var":"Select a var","var_menu_select_all":"Select","var_menu_select_function":"Select a function","expression_menu_select":"Construct any logical condition","$sin":"sin","math":"Mathematic","arrangement":"Arrangement","conversion":"Conversion","inform_valid_name":"Inform a valid name!","inform_valid_content":"Enter some content!","inform_valid_expression":"Construct the logical condition!","inform_valid_name_duplicated":"This name is already in use by other function.","inform_valid_global_duplicated":"A global variable with this name already exists.","inform_valid_variable_duplicated":"A local variable with this name already exists.","text_t":"Text","$cos":"cos","$tan":"tan","$sqrt":"sqrt","$pow":"pow","$log":"log","$abs":"abs","$negate":"negate","$invert":"invert","$max":"maximum","$min":"minimum","$substring":"substring","$length":"length","$uppercase":"uppercase","$lowercase":"lowercase","$charAt":"char_at","$numElements":"total_of_elements","$matrixLines":"total_of_lines","$matrixColumns":"total_of_columns","$isReal":"is_real","$isInt":"is_integer","$isBool":"is_logic","$castReal":"to_real","$castInt":"to_integer","$castBool":"to_logic","$castString":"to_string","text_ivprog_version":"Version 2018_12_19 Build 13_18"};

/***/ }),

/***/ "./i18n/index.js":
/*!***********************!*\
  !*** ./i18n/index.js ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _en = __webpack_require__(/*! ./en */ "./i18n/en/index.js");

var _en2 = _interopRequireDefault(_en);

var _pt = __webpack_require__(/*! ./pt */ "./i18n/pt/index.js");

var _pt2 = _interopRequireDefault(_pt);

var _es = __webpack_require__(/*! ./es */ "./i18n/es/index.js");

var _es2 = _interopRequireDefault(_es);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = {
  'en': _en2.default,
  'pt': _pt2.default,
  'es': _es2.default
};

/***/ }),

/***/ "./i18n/pt/error.json":
/*!****************************!*\
  !*** ./i18n/pt/error.json ***!
  \****************************/
/*! exports provided: token_missing_one, token_missing_two, eos_missing, invalid_type, invalid_array_dimension, invalid_array_size, extra_lines, invalid_main_return, invalid_var_declaration, invalid_break_command, invalid_terminal, const_not_init, id_missing, invalid_id_format, main_missing, invalid_global_var, not_implemented, function_missing, function_missing_full, invalid_parameters_size_full, invalid_parameters_size, invalid_ref_full, invalid_ref, invalid_parameter_type_full, invalid_parameter_type, unknown_command_full, unknown_command, loop_condition_type_full, loop_condition_type, endless_loop_full, endless_loop, for_condition_type_full, for_condition_type, if_condition_type_full, if_condition_type, invalid_return_type_full, invalid_return_type, invalid_void_return_full, invalid_void_return, unexpected_break_command_full, unexpected_break_command, invalid_dimension, void_in_expression_full, void_in_expression, invalid_array_access_full, invalid_array_access, invalid_matrix_access_full, invalid_matrix_access, matrix_column_outbounds_full, matrix_column_outbounds, matrix_line_outbounds_full, matrix_line_outbounds, vector_line_outbounds_full, vector_line_outbounds, vector_not_matrix_full, vector_not_matrix, invalid_infix_op_full, invalid_infix_op, invalid_unary_op_full, invalid_unary_op, unknown_op, duplicate_function, duplicate_variable, main_parameters, symbol_not_found_full, symbol_not_found, array_dimension_not_int_full, array_dimension_not_int, array_dimension_not_positive_full, array_dimension_not_positive, incompatible_types_full, incompatible_types, incompatible_types_array_full, incompatible_types_array, invalid_case_type_full, invalid_case_type, function_no_return, invalid_array_literal_type_full, invalid_array_literal_type, invalid_array_literal_line_full, invalid_array_literal_line, invalid_array_literal_column_full, invalid_array_literal_column, default */
/***/ (function(module) {

module.exports = {"token_missing_one":"Erro de sintaxe: Espera-se $0, mas encontrou-se $1 na linha:$2, coluna:$3","token_missing_two":"Erro de sintaxe: Esperava-se $0 ou $1 mas encontrou-se $2 na liha:$3, coluna: $4","eos_missing":"Falta uma nova linha ou ; na linha: $0, coluna: $1","invalid_type":"$0 na linha: $1, coluna: $2 é um tipo inválido. Os tipos válidos são: $3","invalid_array_dimension":"A dimensão inválida na linha: $0, coluna: $1. Insira um $2 ou identificador válido do mesmo tipo.","invalid_array_size":"O tamnho do vetor/matriz excede o máximo de 2 na linha $0","extra_lines":"Nenhum texto é permitido após '}' em 'programa {...}'","invalid_main_return":"A função $0 deve retornar $1 na linha $2","invalid_var_declaration":"Erro na linha $0. Variáveis só podem ser declarados no corpo principal da função e de preferência nas primeiras linhas.","invalid_break_command":"Erro na linha $0. O comando $1 não pode ser usado fora de uma estrutura de repetição ou 'escolha...caso'","invalid_terminal":"Não é possível utilizar $0 na expressão da linha: $1, coluna: $2. Tente um valor númerico, variável ou chamada de função.","const_not_init":"Erro na linha: $0, coluna: $1. Uma variável declarada como const deve ser inicializada","id_missing":"Esperava-se um identificador, mas encontrou-se $0 na linha: $1, coluna: $2","invalid_id_format":"$0 na linha: $1, coluna: $2 não é um identificador válido. O símbolo '.' não é permitido neste contexto.","main_missing":"A função principal não foi encontrada","invalid_global_var":"Erro crítico: Chamada inválida da função initGlobal fora do contexto BASE","not_implemented":"Erro interno crítico: A função definida pelo sistema $0 não foi implementada.","function_missing":"A função $0 não foi encontrada","function_missing_full":"A função $0 na linha: $1, coluna: $2 não foi encontrada","invalid_parameters_size_full":"Erro na linha $0: a quantidade de parâmetros fornecidos à função $1 está incorreta. Esperava-se $2, encontrou-se $3.","invalid_parameters_size":"A quantidade de parâmetros fornecidos à função $0 está incorreta. Esperava-se $1, encontrou-se $2","invalid_ref_full":"A expressão $0 fornecida como parâmetro para a função $1 na linha $2 não é válida para esta função. Use uma variável ou posição de vetor.","invalid_ref":"A expressão $0 fornecida como parâmetro para a função $1 não é válida para esta função. Use uma variável ou posição de vetor.","invalid_parameter_type_full":"A expressão $0 fornecida como parâmetro para a função $1 na linha $2 não é compatível com o tipo esperado.","invalid_parameter_type":"A expressão $0 fornecida como parâmetro para a função $1 não é compatível com o tipo esperado.","unknown_command_full":"Erro interno crítico: comando desconhecido encontrado na linha $0","unknown_command":"Erro interno crítico: comando desconhecido encontrado!","loop_condition_type_full":"Erro na linha: $0, coluna $1: a condição dos laços de repetição deve ser do tipo lógico","loop_condition_type":"A condição dos laços de repetição deve ser do tipo lógico","endless_loop_full":"Possível laço infinito detectado no seu código. Verifique a linha $0","endless_loop":"Possível laço infinito detectado no seu código.","for_condition_type_full":"Erro na linha: $0, coluna $1: a condição de parada do comando para(...) deve ser do tipo lógico","for_condition_type":"A condição de parada do comando para(...) deve ser do tipo lógico","if_condition_type_full":"Erro na linha: $0, coluna $1: a condição de um comando se...senao deve ser do tipo lógico","if_condition_type":"A condição de um comando se...senao deve ser do tipo lógico","invalid_return_type_full":"Erro na linha $0: a expressão não produz um tipo compatível com a função $1. Tipo esperado: $2.","invalid_return_type":"A expressão não produz um tipo compatível com a função $0. Tipo esperado: $1.","invalid_void_return_full":"Erro na linha $0: a função $1 não pode retornar uma expressão vazia, use uma espressão do tipo $2","invalid_void_return":"A função $0 não pode retornar uma expressão vazia, use uma espressão do tipo $1","unexpected_break_command_full":"Erro interno crítico: comando pare encontrado fora do contexto de um laço/escolha..caso na linha $0","unexpected_break_command":"Erro interno crítico: comando pare encontrado fora do contexto de um laço/escolha..caso","invalid_dimension":"As dimensões de um vetor/matriz devem ser do tipo inteiro","void_in_expression_full":"Erro na linha: $0, coluna: $1: a função $2 não pode ser utilizada em uma expressão pois seu tipo de retorno é vazio","void_in_expression":"A função $0 não pode ser utilizada em uma expressão pois seu tipo de retorno é vazio","invalid_array_access_full":"Identificador $0 na linha: $1, coluna: $2 não se refere a um vetor/matriz válido","invalid_array_access":"Identificador $0 não se refere a um vetor/matriz válido","invalid_matrix_access_full":"Identificador $0 na linha: $1, coluna: $2 não se refere a uma matriz válida","invalid_matrix_access":"Identificador $0 não se refere a uma matriz válida","matrix_column_outbounds_full":"Erro na linha $0: número de colunas $1 é inválido para a matriz $2 que possui $3 colunas","matrix_column_outbounds":"Número de colunas $0 é inválido para a matriz $1 que possui $2 colunas","matrix_line_outbounds_full":"Erro na linha $0: número de linhas $1 é inválido para a matriz $2 que possui $3 linhas","matrix_line_outbounds":"Número de linhas $0 é inválido para a matriz $1 que possui $2 linhas","vector_line_outbounds_full":"Erro na linha $0: número de linhas $1 é inválido para a matriz $2 que possui $3 linhas","vector_line_outbounds":"Número de linhas $0 é inválido para a matriz $1 que possui $2 linhas","vector_not_matrix_full":"Erro na linha $0: $1 não é uma matriz","vector_not_matrix":"$1 não é uma matriz","invalid_infix_op_full":"Erro na linha $0: não é possível aplicar a operação $1 entre os tipos $2 e $3","invalid_infix_op":"Não é possível aplicar a operação $0 entre os tipos $1 e $2","invalid_unary_op_full":"Erro na linha $0: não é possível aplicar a operação $1 ao tipo $2","invalid_unary_op":"Não é possível aplicar a operação $0 ao tipo $1","unknown_op":"Erro interno crítico: Operação $0 desconhecida","duplicate_function":"A função $0 na linha: $1, coluna: $2 já foi definida anteriormente.","duplicate_variable":"A variável $0 na linha: $1, coluna: $2 já foi declarada anteriormente.","main_parameters":"A função inicio não pode ter parâmetros.","symbol_not_found_full":"A variável $0 na linha: $1, coluna: $2 não foi declarada","symbol_not_found":"A variável $0 não foi declarada","array_dimension_not_int_full":"As dimensões de um vetor/matriz na linha: $0 devem ser do tipo inteiro.","array_dimension_not_int":"As dimensões de um vetor/matriz devem ser do tipo inteiro.","array_dimension_not_positive_full":"As dimensões de um vetor/matriz na linha: $0 devem ser valores positivos.","array_dimension_not_positive":"As dimensões de um vetor/matriz devem ser valores positivos.","incompatible_types_full":"O tipo $0 não é compatível com o tipo resultante da expressão na linha $1","incompatible_types":"O tipo $0 não é compatível com o tipo resultante da expressão fornecida.","incompatible_types_array_full":"A expressão $0 é incompatível com o tipo $1 na linha: $2, coluna: $3.","incompatible_types_array":"A expressão $0 é incompatível com o tipo $1.","invalid_case_type_full":"O caso $0 na linha $1 é incompatível com o tipo $2.","invalid_case_type":"O caso $0 é incompatível com o tipo $1.","function_no_return":"A função $0 não possui um retorno acessível. Toda função deve ter ao menos um retorno no seu corpo principal.","invalid_array_literal_type_full":"Erro na linha $0: a expressão $1 não resulta em um tipo compatível.","invalid_array_literal_type":"A expressão $0 não resulta em um tipo compatível.","invalid_array_literal_line_full":"Erro na linha $0: esperava-se $1 linhas mas encontrou $2.","invalid_array_literal_line":"Esperava-se $0 linhas mas encontrou $1.","invalid_array_literal_column_full":"Erro na linha $0: esperava-se $1 colunas mas encontrou $2.","invalid_array_literal_column":"Esperava-se $0 colunas mas encontrou $1."};

/***/ }),

/***/ "./i18n/pt/index.js":
/*!**************************!*\
  !*** ./i18n/pt/index.js ***!
  \**************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _error = __webpack_require__(/*! ./error.json */ "./i18n/pt/error.json");

var _error2 = _interopRequireDefault(_error);

var _message = __webpack_require__(/*! ./message.json */ "./i18n/pt/message.json");

var _message2 = _interopRequireDefault(_message);

var _ui = __webpack_require__(/*! ./ui.json */ "./i18n/pt/ui.json");

var _ui2 = _interopRequireDefault(_ui);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = {
  'message': _message2.default,
  'error': _error2.default,
  'ui': _ui2.default
};

/***/ }),

/***/ "./i18n/pt/message.json":
/*!******************************!*\
  !*** ./i18n/pt/message.json ***!
  \******************************/
/*! exports provided: default */
/***/ (function(module) {

module.exports = {};

/***/ }),

/***/ "./i18n/pt/ui.json":
/*!*************************!*\
  !*** ./i18n/pt/ui.json ***!
  \*************************/
/*! exports provided: function, btn_clear, btn_function, btn_arithmetic_plus, btn_arithmetic_minus, btn_arithmetic_multiplication, btn_arithmetic_division, btn_arithmetic_module, btn_break, btn_case, start, void, integer, and, or, not, real, program, text, text_start, boolean, true, false, variable, command, new_parameter, new_variable, new_global, new_function, vector, text_comment_start, text_comment_main, text_read_var, text_write_var, text_command_read, text_command_write, text_return, text_btn_return, text_comment, join_or, matrix_string, vector_string, text_attribution, text_if, text_break, text_else, text_for, text_code_while, text_code_do, text_command_do, text_code_switch, text_code_case, text_logic_expression, text_arithmetic_expression, text_iftrue, text_repeatNtimes, text_receives, text_whiletrue, text_dowhiletrue, text_switch, text_functioncall, text_value, text_operator, text_parentheses, text_change, text_teacher_algorithm, text_teacher_algorithm_include, text_teacher_test_case, text_teacher_config, text_teacher_data_types, text_teacher_commands, text_teacher_functions, text_teacher_create_functions, text_teacher_create_movement_functions, text_teacher_test_case_input, text_teacher_test_case_output, text_teacher_test_case_actions, text_teacher_test_case_add, text_header_ivprog_functions, text_menu_functions_math, text_menu_functions_text, text_menu_functions_arrangement, text_menu_functions_conversion, text_none_variable, text_none_variable_instruction, text_ivprog_description, tooltip_visual, tooltip_textual, tooltip_upload, tooltip_download, tooltip_undo, tooltip_redo, tooltip_run, tooltip_evaluate, tooltip_help, tooltip_add_global, tooltip_minimize, tooltip_console, var_menu_select_var, var_menu_select_all, var_menu_select_function, expression_menu_select, $sin, math, text_t, inform_valid_name, inform_valid_content, inform_valid_expression, inform_valid_name_duplicated, inform_valid_global_duplicated, inform_valid_variable_duplicated, arrangement, conversion, $cos, $tan, $sqrt, $pow, $log, $abs, $negate, $invert, $max, $min, $substring, $length, $uppercase, $lowercase, $charAt, $numElements, $matrixLines, $matrixColumns, $isReal, $isInt, $isBool, $castReal, $castInt, $castBool, $castString, text_ivprog_version, default */
/***/ (function(module) {

module.exports = {"function":"funcao","btn_clear":"Limpar","btn_function":"Função","btn_arithmetic_plus":"Adição","btn_arithmetic_minus":"Subtração","btn_arithmetic_multiplication":"Multiplicação","btn_arithmetic_division":"Divisão","btn_arithmetic_module":"Módulo","btn_break":"Pare","btn_case":"Caso","start":"inicio","void":"vazio","integer":"inteiro","and":"E","or":"OU","not":"nao","real":"real","program":"programa","text":"cadeia","text_start":"texto","boolean":"logico","true":"verdadeiro","false":"falso","variable":"Variável","command":"Comando","new_parameter":"novo_parametro","new_variable":"nova_variavel","new_global":"nova_global","new_function":"nova_funcao","vector":"vetor","text_comment_start":"Comentário inicial da função...","text_comment_main":"Esta é a função principal...","text_read_var":"Leitura de dados","text_write_var":"Escrita de dados","text_command_read":"leia","text_command_write":"escreva","text_return":"retorne","text_btn_return":"Retorno","text_comment":"Comentário","join_or":"ou","matrix_string":"matriz de $0","vector_string":"vetor de $0","text_attribution":"Atribuição","text_if":"se","text_break":"pare","text_else":"senao","text_for":"para","text_code_while":"enquanto","text_code_do":"faca","text_command_do":"faça","text_code_switch":"escolha","text_code_case":"caso","text_logic_expression":"Expressão Lógica","text_arithmetic_expression":"Expressão Relacional","text_iftrue":"Se verdadeiro então","text_repeatNtimes":"Repita N vezes","text_receives":"recebe","text_whiletrue":"Enquanto verdadeiro","text_dowhiletrue":"Faça enquanto verdadeiro","text_switch":"Escolha","text_functioncall":"Chamada de função","text_value":"Valor","text_operator":"Operador","text_parentheses":"Parênteses","text_change":"Alterar","text_teacher_algorithm":"Algoritmo","text_teacher_algorithm_include":"Incluir o algoritmo abaixo no exercício","text_teacher_test_case":"Casos de teste","text_teacher_config":"Configurações","text_teacher_data_types":"Tipos de dados","text_teacher_commands":"Comandos","text_teacher_functions":"Funções","text_teacher_create_functions":"Criar novas funções","text_teacher_create_movement_functions":"Movimentar funções","text_teacher_test_case_input":"Entrada","text_teacher_test_case_output":"Saída","text_teacher_test_case_actions":"Ações","text_teacher_test_case_add":"Adicionar caso de teste","text_header_ivprog_functions":"Funções do iVProg","text_menu_functions_math":"Matemática","text_menu_functions_text":"Texto","text_menu_functions_arrangement":"Arranjo","text_menu_functions_conversion":"Conversão","text_none_variable":"Nenhuma variável declarada","text_none_variable_instruction":"Antes de utilizar uma variável, é necessário criá-la","text_ivprog_description":"Programação Visual interativa na Internet","tooltip_visual":"Programação visual","tooltip_textual":"Programação textual","tooltip_upload":"Upload de código fonte","tooltip_download":"Download do código fonte","tooltip_undo":"Desfazer","tooltip_redo":"Refazer","tooltip_run":"Executar o programa","tooltip_evaluate":"Avaliar o programa","tooltip_help":"Ajuda","tooltip_add_global":"Adicionar variável global","tooltip_minimize":"Ocultar os elementos da função","tooltip_console":"Abrir/fechar o terminal","var_menu_select_var":"Selecione uma variável","var_menu_select_all":"Selecione","var_menu_select_function":"Selecione uma função","expression_menu_select":"Construir uma expressão lógica","$sin":"seno","math":"Matematica","text_t":"Texto","inform_valid_name":"Informe um nome válido!","inform_valid_content":"Informe o conteúdo!","inform_valid_expression":"Construa uma expressão lógica!","inform_valid_name_duplicated":"Este nome já está em uso por outra função!","inform_valid_global_duplicated":"Já existe uma variável global com o nome informado.","inform_valid_variable_duplicated":"Já existe uma variável local com o nome informado.","arrangement":"Arranjo","conversion":"Conversao","$cos":"cosseno","$tan":"tangente","$sqrt":"raiz_quadrada","$pow":"potencia","$log":"logaritmo","$abs":"modulo","$negate":"trocar_sinal","$invert":"inverter_valor","$max":"maximo","$min":"minimo","$substring":"subcadeia","$length":"comprimento","$uppercase":"caixa_alta","$lowercase":"caixa_baixa","$charAt":"texto_na_posicao","$numElements":"total_de_elementos","$matrixLines":"total_de_linhas","$matrixColumns":"total_de_colunas","$isReal":"e_real","$isInt":"e_inteiro","$isBool":"e_logico","$castReal":"como_real","$castInt":"como_inteiro","$castBool":"como_logico","$castString":"como_cadeia","text_ivprog_version":"Versão 2018_12_19 Build 13_18"};

/***/ }),

/***/ "./js/Sortable.js":
/*!************************!*\
  !*** ./js/Sortable.js ***!
  \************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/**!
 * Sortable
 * @author	RubaXa   <trash@rubaxa.org>
 * @license MIT
 */

(function sortableModule(factory) {
	"use strict";

	if (true) {
		!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
				__WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {}
})(function sortableFactory() {
	"use strict";

	if (typeof window == "undefined" || !window.document) {
		return function sortableError() {
			throw new Error("Sortable.js requires a window with a document");
		};
	}

	var dragEl,
	    parentEl,
	    ghostEl,
	    cloneEl,
	    rootEl,
	    nextEl,
	    lastDownEl,
	    scrollEl,
	    scrollParentEl,
	    scrollCustomFn,
	    lastEl,
	    lastCSS,
	    lastParentCSS,
	    oldIndex,
	    newIndex,
	    activeGroup,
	    putSortable,
	    autoScroll = {},
	    tapEvt,
	    touchEvt,
	    moved,


	/** @const */
	R_SPACE = /\s+/g,
	    R_FLOAT = /left|right|inline/,
	    expando = 'Sortable' + new Date().getTime(),
	    win = window,
	    document = win.document,
	    parseInt = win.parseInt,
	    $ = win.jQuery || win.Zepto,
	    Polymer = win.Polymer,
	    captureMode = false,
	    supportDraggable = !!('draggable' in document.createElement('div')),
	    supportCssPointerEvents = function (el) {
		// false when IE11
		if (!!navigator.userAgent.match(/Trident.*rv[ :]?11\./)) {
			return false;
		}
		el = document.createElement('x');
		el.style.cssText = 'pointer-events:auto';
		return el.style.pointerEvents === 'auto';
	}(),
	    _silent = false,
	    abs = Math.abs,
	    min = Math.min,
	    savedInputChecked = [],
	    touchDragOverListeners = [],
	    _autoScroll = _throttle(function ( /**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl) {
		// Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
		if (rootEl && options.scroll) {
			var _this = rootEl[expando],
			    el,
			    rect,
			    sens = options.scrollSensitivity,
			    speed = options.scrollSpeed,
			    x = evt.clientX,
			    y = evt.clientY,
			    winWidth = window.innerWidth,
			    winHeight = window.innerHeight,
			    vx,
			    vy,
			    scrollOffsetX,
			    scrollOffsetY;

			// Delect scrollEl
			if (scrollParentEl !== rootEl) {
				scrollEl = options.scroll;
				scrollParentEl = rootEl;
				scrollCustomFn = options.scrollFn;

				if (scrollEl === true) {
					scrollEl = rootEl;

					do {
						if (scrollEl.offsetWidth < scrollEl.scrollWidth || scrollEl.offsetHeight < scrollEl.scrollHeight) {
							break;
						}
						/* jshint boss:true */
					} while (scrollEl = scrollEl.parentNode);
				}
			}

			if (scrollEl) {
				el = scrollEl;
				rect = scrollEl.getBoundingClientRect();
				vx = (abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens);
				vy = (abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens);
			}

			if (!(vx || vy)) {
				vx = (winWidth - x <= sens) - (x <= sens);
				vy = (winHeight - y <= sens) - (y <= sens);

				/* jshint expr:true */
				(vx || vy) && (el = win);
			}

			if (autoScroll.vx !== vx || autoScroll.vy !== vy || autoScroll.el !== el) {
				autoScroll.el = el;
				autoScroll.vx = vx;
				autoScroll.vy = vy;

				clearInterval(autoScroll.pid);

				if (el) {
					autoScroll.pid = setInterval(function () {
						scrollOffsetY = vy ? vy * speed : 0;
						scrollOffsetX = vx ? vx * speed : 0;

						if ('function' === typeof scrollCustomFn) {
							return scrollCustomFn.call(_this, scrollOffsetX, scrollOffsetY, evt);
						}

						if (el === win) {
							win.scrollTo(win.pageXOffset + scrollOffsetX, win.pageYOffset + scrollOffsetY);
						} else {
							el.scrollTop += scrollOffsetY;
							el.scrollLeft += scrollOffsetX;
						}
					}, 24);
				}
			}
		}
	}, 30),
	    _prepareGroup = function _prepareGroup(options) {
		function toFn(value, pull) {
			if (value === void 0 || value === true) {
				value = group.name;
			}

			if (typeof value === 'function') {
				return value;
			} else {
				return function (to, from) {
					var fromGroup = from.options.group.name;

					return pull ? value : value && (value.join ? value.indexOf(fromGroup) > -1 : fromGroup == value);
				};
			}
		}

		var group = {};
		var originalGroup = options.group;

		if (!originalGroup || (typeof originalGroup === "undefined" ? "undefined" : _typeof(originalGroup)) != 'object') {
			originalGroup = { name: originalGroup };
		}

		group.name = originalGroup.name;
		group.checkPull = toFn(originalGroup.pull, true);
		group.checkPut = toFn(originalGroup.put);
		group.revertClone = originalGroup.revertClone;

		options.group = group;
	};

	/**
  * @class  Sortable
  * @param  {HTMLElement}  el
  * @param  {Object}       [options]
  */
	function Sortable(el, options) {
		if (!(el && el.nodeType && el.nodeType === 1)) {
			throw 'Sortable: `el` must be HTMLElement, and not ' + {}.toString.call(el);
		}

		this.el = el; // root element
		this.options = options = _extend({}, options);

		// Export instance
		el[expando] = this;

		// Default options
		var defaults = {
			group: Math.random(),
			sort: true,
			disabled: false,
			store: null,
			handle: null,
			scroll: true,
			scrollSensitivity: 30,
			scrollSpeed: 10,
			draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*',
			ghostClass: 'sortable-ghost',
			chosenClass: 'sortable-chosen',
			dragClass: 'sortable-drag',
			ignore: 'a, img',
			filter: null,
			preventOnFilter: true,
			animation: 0,
			setData: function setData(dataTransfer, dragEl) {
				dataTransfer.setData('Text', dragEl.textContent);
			},
			dropBubble: false,
			dragoverBubble: false,
			dataIdAttr: 'data-id',
			delay: 0,
			forceFallback: false,
			fallbackClass: 'sortable-fallback',
			fallbackOnBody: false,
			fallbackTolerance: 0,
			fallbackOffset: { x: 0, y: 0 }
		};

		// Set default options
		for (var name in defaults) {
			!(name in options) && (options[name] = defaults[name]);
		}

		_prepareGroup(options);

		// Bind all private methods
		for (var fn in this) {
			if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
				this[fn] = this[fn].bind(this);
			}
		}

		// Setup drag mode
		this.nativeDraggable = options.forceFallback ? false : supportDraggable;

		// Bind events
		_on(el, 'mousedown', this._onTapStart);
		_on(el, 'touchstart', this._onTapStart);
		_on(el, 'pointerdown', this._onTapStart);

		if (this.nativeDraggable) {
			_on(el, 'dragover', this);
			_on(el, 'dragenter', this);
		}

		touchDragOverListeners.push(this._onDragOver);

		// Restore sorting
		options.store && this.sort(options.store.get(this));
	}

	Sortable.prototype = /** @lends Sortable.prototype */{
		constructor: Sortable,

		_onTapStart: function _onTapStart( /** Event|TouchEvent */evt) {
			var _this = this,
			    el = this.el,
			    options = this.options,
			    preventOnFilter = options.preventOnFilter,
			    type = evt.type,
			    touch = evt.touches && evt.touches[0],
			    target = (touch || evt).target,
			    originalTarget = evt.target.shadowRoot && evt.path && evt.path[0] || target,
			    filter = options.filter,
			    startIndex;

			_saveInputCheckedState(el);

			// Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.
			if (dragEl) {
				return;
			}

			if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {
				return; // only left button or enabled
			}

			target = _closest(target, options.draggable, el);

			if (!target) {
				return;
			}

			if (lastDownEl === target) {
				// Ignoring duplicate `down`
				return;
			}

			// Get the index of the dragged element within its parent
			startIndex = _index(target, options.draggable);

			// Check filter
			if (typeof filter === 'function') {
				if (filter.call(this, evt, target, this)) {
					_dispatchEvent(_this, originalTarget, 'filter', target, el, startIndex);
					preventOnFilter && evt.preventDefault();
					return; // cancel dnd
				}
			} else if (filter) {
				filter = filter.split(',').some(function (criteria) {
					criteria = _closest(originalTarget, criteria.trim(), el);

					if (criteria) {
						_dispatchEvent(_this, criteria, 'filter', target, el, startIndex);
						return true;
					}
				});

				if (filter) {
					preventOnFilter && evt.preventDefault();
					return; // cancel dnd
				}
			}

			if (options.handle && !_closest(originalTarget, options.handle, el)) {
				return;
			}

			// Prepare `dragstart`
			this._prepareDragStart(evt, touch, target, startIndex);
		},

		_prepareDragStart: function _prepareDragStart( /** Event */evt, /** Touch */touch, /** HTMLElement */target, /** Number */startIndex) {
			var _this = this,
			    el = _this.el,
			    options = _this.options,
			    ownerDocument = el.ownerDocument,
			    dragStartFn;

			if (target && !dragEl && target.parentNode === el) {
				tapEvt = evt;

				rootEl = el;
				dragEl = target;
				parentEl = dragEl.parentNode;
				nextEl = dragEl.nextSibling;
				lastDownEl = target;
				activeGroup = options.group;
				oldIndex = startIndex;

				this._lastX = (touch || evt).clientX;
				this._lastY = (touch || evt).clientY;

				dragEl.style['will-change'] = 'transform';

				dragStartFn = function dragStartFn() {
					// Delayed drag has been triggered
					// we can re-enable the events: touchmove/mousemove
					_this._disableDelayedDrag();

					// Make the element draggable
					dragEl.draggable = _this.nativeDraggable;

					// Chosen item
					_toggleClass(dragEl, options.chosenClass, true);

					// Bind the events: dragstart/dragend
					_this._triggerDragStart(evt, touch);

					// Drag start event
					_dispatchEvent(_this, rootEl, 'choose', dragEl, rootEl, oldIndex);
				};

				// Disable "draggable"
				options.ignore.split(',').forEach(function (criteria) {
					_find(dragEl, criteria.trim(), _disableDraggable);
				});

				_on(ownerDocument, 'mouseup', _this._onDrop);
				_on(ownerDocument, 'touchend', _this._onDrop);
				_on(ownerDocument, 'touchcancel', _this._onDrop);
				_on(ownerDocument, 'pointercancel', _this._onDrop);
				_on(ownerDocument, 'selectstart', _this);

				if (options.delay) {
					// If the user moves the pointer or let go the click or touch
					// before the delay has been reached:
					// disable the delayed drag
					_on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
					_on(ownerDocument, 'touchend', _this._disableDelayedDrag);
					_on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
					_on(ownerDocument, 'mousemove', _this._disableDelayedDrag);
					_on(ownerDocument, 'touchmove', _this._disableDelayedDrag);
					_on(ownerDocument, 'pointermove', _this._disableDelayedDrag);

					_this._dragStartTimer = setTimeout(dragStartFn, options.delay);
				} else {
					dragStartFn();
				}
			}
		},

		_disableDelayedDrag: function _disableDelayedDrag() {
			var ownerDocument = this.el.ownerDocument;

			clearTimeout(this._dragStartTimer);
			_off(ownerDocument, 'mouseup', this._disableDelayedDrag);
			_off(ownerDocument, 'touchend', this._disableDelayedDrag);
			_off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
			_off(ownerDocument, 'mousemove', this._disableDelayedDrag);
			_off(ownerDocument, 'touchmove', this._disableDelayedDrag);
			_off(ownerDocument, 'pointermove', this._disableDelayedDrag);
		},

		_triggerDragStart: function _triggerDragStart( /** Event */evt, /** Touch */touch) {
			touch = touch || (evt.pointerType == 'touch' ? evt : null);

			if (touch) {
				// Touch device support
				tapEvt = {
					target: dragEl,
					clientX: touch.clientX,
					clientY: touch.clientY
				};

				this._onDragStart(tapEvt, 'touch');
			} else if (!this.nativeDraggable) {
				this._onDragStart(tapEvt, true);
			} else {
				_on(dragEl, 'dragend', this);
				_on(rootEl, 'dragstart', this._onDragStart);
			}

			try {
				if (document.selection) {
					// Timeout neccessary for IE9
					setTimeout(function () {
						document.selection.empty();
					});
				} else {
					window.getSelection().removeAllRanges();
				}
			} catch (err) {}
		},

		_dragStarted: function _dragStarted() {
			if (rootEl && dragEl) {
				var options = this.options;

				// Apply effect
				_toggleClass(dragEl, options.ghostClass, true);
				_toggleClass(dragEl, options.dragClass, false);

				Sortable.active = this;

				// Drag start event
				_dispatchEvent(this, rootEl, 'start', dragEl, rootEl, oldIndex);
			} else {
				this._nulling();
			}
		},

		_emulateDragOver: function _emulateDragOver() {
			if (touchEvt) {
				if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY) {
					return;
				}

				this._lastX = touchEvt.clientX;
				this._lastY = touchEvt.clientY;

				if (!supportCssPointerEvents) {
					_css(ghostEl, 'display', 'none');
				}

				var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY),
				    parent = target,
				    i = touchDragOverListeners.length;

				if (parent) {
					do {
						if (parent[expando]) {
							while (i--) {
								touchDragOverListeners[i]({
									clientX: touchEvt.clientX,
									clientY: touchEvt.clientY,
									target: target,
									rootEl: parent
								});
							}

							break;
						}

						target = parent; // store last element
					}
					/* jshint boss:true */
					while (parent = parent.parentNode);
				}

				if (!supportCssPointerEvents) {
					_css(ghostEl, 'display', '');
				}
			}
		},

		_onTouchMove: function _onTouchMove( /**TouchEvent*/evt) {
			if (tapEvt) {
				var options = this.options,
				    fallbackTolerance = options.fallbackTolerance,
				    fallbackOffset = options.fallbackOffset,
				    touch = evt.touches ? evt.touches[0] : evt,
				    dx = touch.clientX - tapEvt.clientX + fallbackOffset.x,
				    dy = touch.clientY - tapEvt.clientY + fallbackOffset.y,
				    translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)';

				// only set the status to dragging, when we are actually dragging
				if (!Sortable.active) {
					if (fallbackTolerance && min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) < fallbackTolerance) {
						return;
					}

					this._dragStarted();
				}

				// as well as creating the ghost element on the document body
				this._appendGhost();

				moved = true;
				touchEvt = touch;

				_css(ghostEl, 'webkitTransform', translate3d);
				_css(ghostEl, 'mozTransform', translate3d);
				_css(ghostEl, 'msTransform', translate3d);
				_css(ghostEl, 'transform', translate3d);

				evt.preventDefault();
			}
		},

		_appendGhost: function _appendGhost() {
			if (!ghostEl) {
				var rect = dragEl.getBoundingClientRect(),
				    css = _css(dragEl),
				    options = this.options,
				    ghostRect;

				ghostEl = dragEl.cloneNode(true);

				_toggleClass(ghostEl, options.ghostClass, false);
				_toggleClass(ghostEl, options.fallbackClass, true);
				_toggleClass(ghostEl, options.dragClass, true);

				_css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10));
				_css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10));
				_css(ghostEl, 'width', rect.width);
				_css(ghostEl, 'height', rect.height);
				_css(ghostEl, 'opacity', '0.8');
				_css(ghostEl, 'position', 'fixed');
				_css(ghostEl, 'zIndex', '100000');
				_css(ghostEl, 'pointerEvents', 'none');

				options.fallbackOnBody && document.body.appendChild(ghostEl) || rootEl.appendChild(ghostEl);

				// Fixing dimensions.
				ghostRect = ghostEl.getBoundingClientRect();
				_css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
				_css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
			}
		},

		_onDragStart: function _onDragStart( /**Event*/evt, /**boolean*/useFallback) {
			var dataTransfer = evt.dataTransfer,
			    options = this.options;

			this._offUpEvents();

			if (activeGroup.checkPull(this, this, dragEl, evt)) {
				cloneEl = _clone(dragEl);

				cloneEl.draggable = false;
				cloneEl.style['will-change'] = '';

				_css(cloneEl, 'display', 'none');
				_toggleClass(cloneEl, this.options.chosenClass, false);

				rootEl.insertBefore(cloneEl, dragEl);
				_dispatchEvent(this, rootEl, 'clone', dragEl);
			}

			_toggleClass(dragEl, options.dragClass, true);

			if (useFallback) {
				if (useFallback === 'touch') {
					// Bind touch events
					_on(document, 'touchmove', this._onTouchMove);
					_on(document, 'touchend', this._onDrop);
					_on(document, 'touchcancel', this._onDrop);
					_on(document, 'pointermove', this._onTouchMove);
					_on(document, 'pointerup', this._onDrop);
				} else {
					// Old brwoser
					_on(document, 'mousemove', this._onTouchMove);
					_on(document, 'mouseup', this._onDrop);
				}

				this._loopId = setInterval(this._emulateDragOver, 50);
			} else {
				if (dataTransfer) {
					dataTransfer.effectAllowed = 'move';
					options.setData && options.setData.call(this, dataTransfer, dragEl);
				}

				_on(document, 'drop', this);
				setTimeout(this._dragStarted, 0);
			}
		},

		_onDragOver: function _onDragOver( /**Event*/evt) {
			var el = this.el,
			    target,
			    dragRect,
			    targetRect,
			    revert,
			    options = this.options,
			    group = options.group,
			    activeSortable = Sortable.active,
			    isOwner = activeGroup === group,
			    isMovingBetweenSortable = false,
			    canSort = options.sort;

			if (evt.preventDefault !== void 0) {
				evt.preventDefault();
				!options.dragoverBubble && evt.stopPropagation();
			}

			if (dragEl.animated) {
				return;
			}

			moved = true;

			if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list
			: putSortable === this || (activeSortable.lastPullMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt)) && (evt.rootEl === void 0 || evt.rootEl === this.el) // touch fallback
			) {
					// Smart auto-scrolling
					_autoScroll(evt, options, this.el);

					if (_silent) {
						return;
					}

					target = _closest(evt.target, options.draggable, el);
					dragRect = dragEl.getBoundingClientRect();

					if (putSortable !== this) {
						putSortable = this;
						isMovingBetweenSortable = true;
					}

					if (revert) {
						_cloneHide(activeSortable, true);
						parentEl = rootEl; // actualization

						if (cloneEl || nextEl) {
							rootEl.insertBefore(dragEl, cloneEl || nextEl);
						} else if (!canSort) {
							rootEl.appendChild(dragEl);
						}

						return;
					}

					if (el.children.length === 0 || el.children[0] === ghostEl || el === evt.target && _ghostIsLast(el, evt)) {
						//assign target only if condition is true
						if (el.children.length !== 0 && el.children[0] !== ghostEl && el === evt.target) {
							target = el.lastElementChild;
						}

						if (target) {
							if (target.animated) {
								return;
							}

							targetRect = target.getBoundingClientRect();
						}

						_cloneHide(activeSortable, isOwner);

						if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt) !== false) {
							if (!dragEl.contains(el)) {
								el.appendChild(dragEl);
								parentEl = el; // actualization
							}

							this._animate(dragRect, dragEl);
							target && this._animate(targetRect, target);
						}
					} else if (target && !target.animated && target !== dragEl && target.parentNode[expando] !== void 0) {
						if (lastEl !== target) {
							lastEl = target;
							lastCSS = _css(target);
							lastParentCSS = _css(target.parentNode);
						}

						targetRect = target.getBoundingClientRect();

						var width = targetRect.right - targetRect.left,
						    height = targetRect.bottom - targetRect.top,
						    floating = R_FLOAT.test(lastCSS.cssFloat + lastCSS.display) || lastParentCSS.display == 'flex' && lastParentCSS['flex-direction'].indexOf('row') === 0,
						    isWide = target.offsetWidth > dragEl.offsetWidth,
						    isLong = target.offsetHeight > dragEl.offsetHeight,
						    halfway = (floating ? (evt.clientX - targetRect.left) / width : (evt.clientY - targetRect.top) / height) > 0.5,
						    nextSibling = target.nextElementSibling,
						    after = false;

						if (floating) {
							var elTop = dragEl.offsetTop,
							    tgTop = target.offsetTop;

							if (elTop === tgTop) {
								after = target.previousElementSibling === dragEl && !isWide || halfway && isWide;
							} else if (target.previousElementSibling === dragEl || dragEl.previousElementSibling === target) {
								after = (evt.clientY - targetRect.top) / height > 0.5;
							} else {
								after = tgTop > elTop;
							}
						} else if (!isMovingBetweenSortable) {
							after = nextSibling !== dragEl && !isLong || halfway && isLong;
						}

						var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);

						if (moveVector !== false) {
							if (moveVector === 1 || moveVector === -1) {
								after = moveVector === 1;
							}

							_silent = true;
							setTimeout(_unsilent, 30);

							_cloneHide(activeSortable, isOwner);

							if (!dragEl.contains(el)) {
								if (after && !nextSibling) {
									el.appendChild(dragEl);
								} else {
									target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
								}
							}

							parentEl = dragEl.parentNode; // actualization

							this._animate(dragRect, dragEl);
							this._animate(targetRect, target);
						}
					}
				}
		},

		_animate: function _animate(prevRect, target) {
			var ms = this.options.animation;

			if (ms) {
				var currentRect = target.getBoundingClientRect();

				if (prevRect.nodeType === 1) {
					prevRect = prevRect.getBoundingClientRect();
				}

				_css(target, 'transition', 'none');
				_css(target, 'transform', 'translate3d(' + (prevRect.left - currentRect.left) + 'px,' + (prevRect.top - currentRect.top) + 'px,0)');

				target.offsetWidth; // repaint

				_css(target, 'transition', 'all ' + ms + 'ms');
				_css(target, 'transform', 'translate3d(0,0,0)');

				clearTimeout(target.animated);
				target.animated = setTimeout(function () {
					_css(target, 'transition', '');
					_css(target, 'transform', '');
					target.animated = false;
				}, ms);
			}
		},

		_offUpEvents: function _offUpEvents() {
			var ownerDocument = this.el.ownerDocument;

			_off(document, 'touchmove', this._onTouchMove);
			_off(document, 'pointermove', this._onTouchMove);
			_off(ownerDocument, 'mouseup', this._onDrop);
			_off(ownerDocument, 'touchend', this._onDrop);
			_off(ownerDocument, 'pointerup', this._onDrop);
			_off(ownerDocument, 'touchcancel', this._onDrop);
			_off(ownerDocument, 'pointercancel', this._onDrop);
			_off(ownerDocument, 'selectstart', this);
		},

		_onDrop: function _onDrop( /**Event*/evt) {
			var el = this.el,
			    options = this.options;

			clearInterval(this._loopId);
			clearInterval(autoScroll.pid);
			clearTimeout(this._dragStartTimer);

			// Unbind events
			_off(document, 'mousemove', this._onTouchMove);

			if (this.nativeDraggable) {
				_off(document, 'drop', this);
				_off(el, 'dragstart', this._onDragStart);
			}

			this._offUpEvents();

			if (evt) {
				if (moved) {
					evt.preventDefault();
					!options.dropBubble && evt.stopPropagation();
				}

				ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);

				if (rootEl === parentEl || Sortable.active.lastPullMode !== 'clone') {
					// Remove clone
					cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);
				}

				if (dragEl) {
					if (this.nativeDraggable) {
						_off(dragEl, 'dragend', this);
					}

					_disableDraggable(dragEl);
					dragEl.style['will-change'] = '';

					// Remove class's
					_toggleClass(dragEl, this.options.ghostClass, false);
					_toggleClass(dragEl, this.options.chosenClass, false);

					// Drag stop event
					_dispatchEvent(this, rootEl, 'unchoose', dragEl, rootEl, oldIndex);

					if (rootEl !== parentEl) {
						newIndex = _index(dragEl, options.draggable);

						if (newIndex >= 0) {
							// Add event
							_dispatchEvent(null, parentEl, 'add', dragEl, rootEl, oldIndex, newIndex);

							// Remove event
							_dispatchEvent(this, rootEl, 'remove', dragEl, rootEl, oldIndex, newIndex);

							// drag from one list and drop into another
							_dispatchEvent(null, parentEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
							_dispatchEvent(this, rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
						}
					} else {
						if (dragEl.nextSibling !== nextEl) {
							// Get the index of the dragged element within its parent
							newIndex = _index(dragEl, options.draggable);

							if (newIndex >= 0) {
								// drag & drop within the same list
								_dispatchEvent(this, rootEl, 'update', dragEl, rootEl, oldIndex, newIndex);
								_dispatchEvent(this, rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
							}
						}
					}

					if (Sortable.active) {
						/* jshint eqnull:true */
						if (newIndex == null || newIndex === -1) {
							newIndex = oldIndex;
						}

						_dispatchEvent(this, rootEl, 'end', dragEl, rootEl, oldIndex, newIndex);

						// Save sorting
						this.save();
					}
				}
			}

			this._nulling();
		},

		_nulling: function _nulling() {
			rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = scrollEl = scrollParentEl = tapEvt = touchEvt = moved = newIndex = lastEl = lastCSS = putSortable = activeGroup = Sortable.active = null;

			savedInputChecked.forEach(function (el) {
				el.checked = true;
			});
			savedInputChecked.length = 0;
		},

		handleEvent: function handleEvent( /**Event*/evt) {
			switch (evt.type) {
				case 'drop':
				case 'dragend':
					this._onDrop(evt);
					break;

				case 'dragover':
				case 'dragenter':
					if (dragEl) {
						this._onDragOver(evt);
						_globalDragOver(evt);
					}
					break;

				case 'selectstart':
					evt.preventDefault();
					break;
			}
		},

		/**
   * Serializes the item into an array of string.
   * @returns {String[]}
   */
		toArray: function toArray() {
			var order = [],
			    el,
			    children = this.el.children,
			    i = 0,
			    n = children.length,
			    options = this.options;

			for (; i < n; i++) {
				el = children[i];
				if (_closest(el, options.draggable, this.el)) {
					order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
				}
			}

			return order;
		},

		/**
   * Sorts the elements according to the array.
   * @param  {String[]}  order  order of the items
   */
		sort: function sort(order) {
			var items = {},
			    rootEl = this.el;

			this.toArray().forEach(function (id, i) {
				var el = rootEl.children[i];

				if (_closest(el, this.options.draggable, rootEl)) {
					items[id] = el;
				}
			}, this);

			order.forEach(function (id) {
				if (items[id]) {
					rootEl.removeChild(items[id]);
					rootEl.appendChild(items[id]);
				}
			});
		},

		/**
   * Save the current sorting
   */
		save: function save() {
			var store = this.options.store;
			store && store.set(this);
		},

		/**
   * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
   * @param   {HTMLElement}  el
   * @param   {String}       [selector]  default: `options.draggable`
   * @returns {HTMLElement|null}
   */
		closest: function closest(el, selector) {
			return _closest(el, selector || this.options.draggable, this.el);
		},

		/**
   * Set/get option
   * @param   {string} name
   * @param   {*}      [value]
   * @returns {*}
   */
		option: function option(name, value) {
			var options = this.options;

			if (value === void 0) {
				return options[name];
			} else {
				options[name] = value;

				if (name === 'group') {
					_prepareGroup(options);
				}
			}
		},

		/**
   * Destroy
   */
		destroy: function destroy() {
			var el = this.el;

			el[expando] = null;

			_off(el, 'mousedown', this._onTapStart);
			_off(el, 'touchstart', this._onTapStart);
			_off(el, 'pointerdown', this._onTapStart);

			if (this.nativeDraggable) {
				_off(el, 'dragover', this);
				_off(el, 'dragenter', this);
			}

			// Remove draggable attributes
			Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
				el.removeAttribute('draggable');
			});

			touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);

			this._onDrop();

			this.el = el = null;
		}
	};

	function _cloneHide(sortable, state) {
		if (sortable.lastPullMode !== 'clone') {
			state = true;
		}

		if (cloneEl && cloneEl.state !== state) {
			_css(cloneEl, 'display', state ? 'none' : '');

			if (!state) {
				if (cloneEl.state) {
					if (sortable.options.group.revertClone) {
						rootEl.insertBefore(cloneEl, nextEl);
						sortable._animate(dragEl, cloneEl);
					} else {
						rootEl.insertBefore(cloneEl, dragEl);
					}
				}
			}

			cloneEl.state = state;
		}
	}

	function _closest( /**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) {
		if (el) {
			ctx = ctx || document;

			do {
				if (selector === '>*' && el.parentNode === ctx || _matches(el, selector)) {
					return el;
				}
				/* jshint boss:true */
			} while (el = _getParentOrHost(el));
		}

		return null;
	}

	function _getParentOrHost(el) {
		var parent = el.host;

		return parent && parent.nodeType ? parent : el.parentNode;
	}

	function _globalDragOver( /**Event*/evt) {
		if (evt.dataTransfer) {
			evt.dataTransfer.dropEffect = 'move';
		}
		evt.preventDefault();
	}

	function _on(el, event, fn) {
		el.addEventListener(event, fn, captureMode);
	}

	function _off(el, event, fn) {
		el.removeEventListener(event, fn, captureMode);
	}

	function _toggleClass(el, name, state) {
		if (el) {
			if (el.classList) {
				el.classList[state ? 'add' : 'remove'](name);
			} else {
				var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');
				el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');
			}
		}
	}

	function _css(el, prop, val) {
		var style = el && el.style;

		if (style) {
			if (val === void 0) {
				if (document.defaultView && document.defaultView.getComputedStyle) {
					val = document.defaultView.getComputedStyle(el, '');
				} else if (el.currentStyle) {
					val = el.currentStyle;
				}

				return prop === void 0 ? val : val[prop];
			} else {
				if (!(prop in style)) {
					prop = '-webkit-' + prop;
				}

				style[prop] = val + (typeof val === 'string' ? '' : 'px');
			}
		}
	}

	function _find(ctx, tagName, iterator) {
		if (ctx) {
			var list = ctx.getElementsByTagName(tagName),
			    i = 0,
			    n = list.length;

			if (iterator) {
				for (; i < n; i++) {
					iterator(list[i], i);
				}
			}

			return list;
		}

		return [];
	}

	function _dispatchEvent(sortable, rootEl, name, targetEl, fromEl, startIndex, newIndex) {
		sortable = sortable || rootEl[expando];

		var evt = document.createEvent('Event'),
		    options = sortable.options,
		    onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);

		evt.initEvent(name, true, true);

		evt.to = rootEl;
		evt.from = fromEl || rootEl;
		evt.item = targetEl || rootEl;
		evt.clone = cloneEl;

		evt.oldIndex = startIndex;
		evt.newIndex = newIndex;

		rootEl.dispatchEvent(evt);

		if (options[onName]) {
			options[onName].call(sortable, evt);
		}
	}

	function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvt, willInsertAfter) {
		var evt,
		    sortable = fromEl[expando],
		    onMoveFn = sortable.options.onMove,
		    retVal;

		evt = document.createEvent('Event');
		evt.initEvent('move', true, true);

		evt.to = toEl;
		evt.from = fromEl;
		evt.dragged = dragEl;
		evt.draggedRect = dragRect;
		evt.related = targetEl || toEl;
		evt.relatedRect = targetRect || toEl.getBoundingClientRect();
		evt.willInsertAfter = willInsertAfter;

		fromEl.dispatchEvent(evt);

		if (onMoveFn) {
			retVal = onMoveFn.call(sortable, evt, originalEvt);
		}

		return retVal;
	}

	function _disableDraggable(el) {
		el.draggable = false;
	}

	function _unsilent() {
		_silent = false;
	}

	/** @returns {HTMLElement|false} */
	function _ghostIsLast(el, evt) {
		var lastEl = el.lastElementChild,
		    rect = lastEl.getBoundingClientRect();

		// 5 — min delta
		// abs — нельзя добавлять, а то глюки при наведении сверху
		return evt.clientY - (rect.top + rect.height) > 5 || evt.clientX - (rect.left + rect.width) > 5;
	}

	/**
  * Generate id
  * @param   {HTMLElement} el
  * @returns {String}
  * @private
  */
	function _generateId(el) {
		var str = el.tagName + el.className + el.src + el.href + el.textContent,
		    i = str.length,
		    sum = 0;

		while (i--) {
			sum += str.charCodeAt(i);
		}

		return sum.toString(36);
	}

	/**
  * Returns the index of an element within its parent for a selected set of
  * elements
  * @param  {HTMLElement} el
  * @param  {selector} selector
  * @return {number}
  */
	function _index(el, selector) {
		var index = 0;

		if (!el || !el.parentNode) {
			return -1;
		}

		while (el && (el = el.previousElementSibling)) {
			if (el.nodeName.toUpperCase() !== 'TEMPLATE' && (selector === '>*' || _matches(el, selector))) {
				index++;
			}
		}

		return index;
	}

	function _matches( /**HTMLElement*/el, /**String*/selector) {
		if (el) {
			selector = selector.split('.');

			var tag = selector.shift().toUpperCase(),
			    re = new RegExp('\\s(' + selector.join('|') + ')(?=\\s)', 'g');

			return (tag === '' || el.nodeName.toUpperCase() == tag) && (!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length);
		}

		return false;
	}

	function _throttle(callback, ms) {
		var args, _this;

		return function () {
			if (args === void 0) {
				args = arguments;
				_this = this;

				setTimeout(function () {
					if (args.length === 1) {
						callback.call(_this, args[0]);
					} else {
						callback.apply(_this, args);
					}

					args = void 0;
				}, ms);
			}
		};
	}

	function _extend(dst, src) {
		if (dst && src) {
			for (var key in src) {
				if (src.hasOwnProperty(key)) {
					dst[key] = src[key];
				}
			}
		}

		return dst;
	}

	function _clone(el) {
		return $ ? $(el).clone(true)[0] : Polymer && Polymer.dom ? Polymer.dom(el).cloneNode(true) : el.cloneNode(true);
	}

	function _saveInputCheckedState(root) {
		var inputs = root.getElementsByTagName('input');
		var idx = inputs.length;

		while (idx--) {
			var el = inputs[idx];
			el.checked && savedInputChecked.push(el);
		}
	}

	// Fixed #973: 
	_on(document, 'touchmove', function (evt) {
		if (Sortable.active) {
			evt.preventDefault();
		}
	});

	try {
		window.addEventListener('test', null, Object.defineProperty({}, 'passive', {
			get: function get() {
				captureMode = {
					capture: false,
					passive: false
				};
			}
		}));
	} catch (err) {}

	// Export utils
	Sortable.utils = {
		on: _on,
		off: _off,
		css: _css,
		find: _find,
		is: function is(el, selector) {
			return !!_closest(el, selector, el);
		},
		extend: _extend,
		throttle: _throttle,
		closest: _closest,
		toggleClass: _toggleClass,
		clone: _clone,
		index: _index
	};

	/**
  * Create sortable instance
  * @param {HTMLElement}  el
  * @param {Object}      [options]
  */
	Sortable.create = function (el, options) {
		return new Sortable(el, options);
	};

	// Export
	Sortable.version = '1.6.1';
	return Sortable;
});

/***/ }),

/***/ "./js/assessment/ivprogAssessment.js":
/*!*******************************************!*\
  !*** ./js/assessment/ivprogAssessment.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IVProgAssessment = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _ivprogParser = __webpack_require__(/*! ./../ast/ivprogParser */ "./js/ast/ivprogParser.js");

var _semanticAnalyser = __webpack_require__(/*! ./../processor/semantic/semanticAnalyser */ "./js/processor/semantic/semanticAnalyser.js");

var _ivprogProcessor = __webpack_require__(/*! ./../processor/ivprogProcessor */ "./js/processor/ivprogProcessor.js");

var _inputTest = __webpack_require__(/*! ./../util/inputTest */ "./js/util/inputTest.js");

var _outputTest = __webpack_require__(/*! ./../util/outputTest */ "./js/util/outputTest.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var IVProgAssessment = exports.IVProgAssessment = function () {
  function IVProgAssessment(textCode, testCases, domConsole) {
    _classCallCheck(this, IVProgAssessment);

    this.textCode = textCode;
    this.testCases = testCases;
    this.domConsole = domConsole;
  }

  _createClass(IVProgAssessment, [{
    key: "runTest",
    value: function runTest() {
      var _this = this;

      try {
        // try and show error messages through domconsole
        var parser = _ivprogParser.IVProgParser.createParser(this.textCode);
        var semantic = new _semanticAnalyser.SemanticAnalyser(parser.parseTree());
        var validTree = semantic.analyseTree();
        // loop test cases and show messages through domconsole
        var partialTests = this.testCases.map(function (t, name) {
          return _this.partialEvaluateTestCase(new _ivprogProcessor.IVProgProcessor(validTree), t.input, t.output, name);
        });
        var testResult = partialTests.reduce(function (acc, curr) {
          return acc.then(curr);
        }, Promise.resolve(0));
        return testResult.then(function (total) {
          return Promise.resolve(total / _this.testCases.length);
        }).catch(function (err) {
          _this.domConsole.err("Erro durante a execução do programa"); // try and show error messages through domconsole
          _this.domConsole.err(err.message);
          return Promise.resolve(0);
        });
      } catch (error) {
        this.domConsole.err("Erro durante a execução do programa"); // try and show error messages through domconsole
        this.domConsole.err(error.message);
        return Promise.resolve(0);
      }
    }
  }, {
    key: "evaluateTestCase",
    value: function evaluateTestCase(prog, inputList, outputList, name, accumulator) {
      var outerThis = this;
      var input = new _inputTest.InputTest(inputList);
      var output = new _outputTest.OutputTest();
      prog.registerInput(input);
      prog.registerOutput(output);
      var startTime = Date.now();
      return prog.interpretAST().then(function (_) {
        var millis = Date.now() - startTime;
        if (input.inputList.length !== input.index) {
          outerThis.domConsole.err("Caso de teste " + (name + 1) + ": Falhou, ainda restam entradas!");
          outerThis.domConsole.info("Levou " + millis + "ms");
          return Promise.resolve(accumulator + 1 * (input.index / inputList.length));
        } else if (output.list.length < outputList.length) {
          outerThis.domConsole.err("Caso de teste " + (name + 1) + ": Falhou <" + inputList.join(", ") + ";" + outputList.join(", ") + ";" + output.list.join(", ") + ">");
          outerThis.domConsole.info("Levou " + millis + "ms");
          return Promise.resolve(accumulator + 1 * (output.list.length / outputList.length));
        } else if (output.list.length > outputList.length) {
          outerThis.domConsole.err("Caso de teste " + (name + 1) + ": Falhou <" + inputList.join(", ") + ";" + outputList.join(", ") + ";" + output.list.join(", ") + ">");
          outerThis.domConsole.info("Levou " + millis + "ms");
          return Promise.resolve(accumulator + 1 * (outputList.length / output.list.length));
        } else {
          var isOk = outerThis.checkOutput(output.list, outputList);
          if (!isOk) {
            outerThis.domConsole.err("Caso de teste " + (name + 1) + ": Falhou <" + inputList.join(", ") + ";" + outputList.join(", ") + ";" + output.list.join(", ") + ">");
            outerThis.domConsole.info("Levou " + millis + "ms");
            return Promise.resolve(accumulator);
          } else {
            outerThis.domConsole.info("Caso de teste " + (name + 1) + ": OK!");
            outerThis.domConsole.info("Levou " + millis + "ms");
            return Promise.resolve(accumulator + 1);
          }
        }
      }).catch(function (_) {
        return Promise.resolve(accumulator);
      });
    }
  }, {
    key: "partialEvaluateTestCase",
    value: function partialEvaluateTestCase(prog, inputList, outputList, name) {
      var _this2 = this;

      var partial = function partial(accumulator) {
        return _this2.evaluateTestCase(prog, inputList, outputList, name, accumulator);
      };
      partial = partial.bind(this);
      return partial;
    }
  }, {
    key: "checkOutput",
    value: function checkOutput(aList, bList) {
      for (var i = 0; i < aList.length; i++) {
        var outValue = aList[i];
        if (outValue != bList[i]) {
          return false;
        }
      }
      return true;
    }
  }]);

  return IVProgAssessment;
}();

/***/ }),

/***/ "./js/ast/commands/arrayAssign.js":
/*!****************************************!*\
  !*** ./js/ast/commands/arrayAssign.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ArrayIndexAssign = undefined;

var _assign = __webpack_require__(/*! ./assign */ "./js/ast/commands/assign.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ArrayIndexAssign = exports.ArrayIndexAssign = function (_Assign) {
  _inherits(ArrayIndexAssign, _Assign);

  function ArrayIndexAssign(id, lineExpression, columnExpression, expression) {
    _classCallCheck(this, ArrayIndexAssign);

    var _this = _possibleConstructorReturn(this, (ArrayIndexAssign.__proto__ || Object.getPrototypeOf(ArrayIndexAssign)).call(this, id, expression));

    _this.line = lineExpression;
    _this.column = columnExpression;
    return _this;
  }

  return ArrayIndexAssign;
}(_assign.Assign);

/***/ }),

/***/ "./js/ast/commands/arrayDeclaration.js":
/*!*********************************************!*\
  !*** ./js/ast/commands/arrayDeclaration.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ArrayDeclaration = undefined;

var _declaration = __webpack_require__(/*! ./declaration */ "./js/ast/commands/declaration.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ArrayDeclaration = exports.ArrayDeclaration = function (_Declaration) {
  _inherits(ArrayDeclaration, _Declaration);

  function ArrayDeclaration(id, type, lines, columns, initial, isConst) {
    _classCallCheck(this, ArrayDeclaration);

    var _this = _possibleConstructorReturn(this, (ArrayDeclaration.__proto__ || Object.getPrototypeOf(ArrayDeclaration)).call(this, id, type, initial, isConst));

    _this.lines = lines;
    _this.columns = columns;
    return _this;
  }

  return ArrayDeclaration;
}(_declaration.Declaration);

/***/ }),

/***/ "./js/ast/commands/assign.js":
/*!***********************************!*\
  !*** ./js/ast/commands/assign.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Assign = undefined;

var _command = __webpack_require__(/*! ./command */ "./js/ast/commands/command.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Assign = exports.Assign = function (_Command) {
  _inherits(Assign, _Command);

  function Assign(id, expression) {
    _classCallCheck(this, Assign);

    var _this = _possibleConstructorReturn(this, (Assign.__proto__ || Object.getPrototypeOf(Assign)).call(this));

    _this.id = id;
    _this.expression = expression;
    return _this;
  }

  return Assign;
}(_command.Command);

/***/ }),

/***/ "./js/ast/commands/break.js":
/*!**********************************!*\
  !*** ./js/ast/commands/break.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Break = undefined;

var _command = __webpack_require__(/*! ./command */ "./js/ast/commands/command.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Break = exports.Break = function (_Command) {
  _inherits(Break, _Command);

  function Break() {
    _classCallCheck(this, Break);

    return _possibleConstructorReturn(this, (Break.__proto__ || Object.getPrototypeOf(Break)).call(this));
  }

  return Break;
}(_command.Command);

/***/ }),

/***/ "./js/ast/commands/case.js":
/*!*********************************!*\
  !*** ./js/ast/commands/case.js ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Case = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _command = __webpack_require__(/*! ./command */ "./js/ast/commands/command.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Case = exports.Case = function (_Command) {
  _inherits(Case, _Command);

  function Case(expression) {
    _classCallCheck(this, Case);

    var _this = _possibleConstructorReturn(this, (Case.__proto__ || Object.getPrototypeOf(Case)).call(this));

    _this.expression = expression;
    _this.commands = [];
    return _this;
  }

  _createClass(Case, [{
    key: 'setCommands',
    value: function setCommands(commands) {
      this.commands = commands;
    }
  }, {
    key: 'isDefault',
    get: function get() {
      return this.expression === null;
    }
  }]);

  return Case;
}(_command.Command);

/***/ }),

/***/ "./js/ast/commands/command.js":
/*!************************************!*\
  !*** ./js/ast/commands/command.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Command = exports.Command = function () {
  function Command() {
    _classCallCheck(this, Command);

    this._sourceInfo = null;
  }

  _createClass(Command, [{
    key: "sourceInfo",
    set: function set(sourceInfo) {
      this._sourceInfo = sourceInfo;
    },
    get: function get() {
      return this._sourceInfo;
    }
  }]);

  return Command;
}();

/***/ }),

/***/ "./js/ast/commands/commandBlock.js":
/*!*****************************************!*\
  !*** ./js/ast/commands/commandBlock.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var CommandBlock = exports.CommandBlock = function () {
	function CommandBlock(variables, commands) {
		_classCallCheck(this, CommandBlock);

		this.variables = variables;
		this.commands = commands;
		this._sourceInfo = null;
	}

	_createClass(CommandBlock, [{
		key: "sourceInfo",
		set: function set(sourceInfo) {
			this._sourceInfo = sourceInfo;
		},
		get: function get() {
			return this._sourceInfo;
		}
	}]);

	return CommandBlock;
}();

/***/ }),

/***/ "./js/ast/commands/declaration.js":
/*!****************************************!*\
  !*** ./js/ast/commands/declaration.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Declaration = undefined;

var _command = __webpack_require__(/*! ./command */ "./js/ast/commands/command.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Declaration = exports.Declaration = function (_Command) {
  _inherits(Declaration, _Command);

  function Declaration(id, type, initial, isConst) {
    _classCallCheck(this, Declaration);

    var _this = _possibleConstructorReturn(this, (Declaration.__proto__ || Object.getPrototypeOf(Declaration)).call(this));

    _this.id = id;
    _this.type = type;
    _this.initial = initial;
    _this.isConst = isConst;
    return _this;
  }

  return Declaration;
}(_command.Command);

/***/ }),

/***/ "./js/ast/commands/doWhile.js":
/*!************************************!*\
  !*** ./js/ast/commands/doWhile.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DoWhile = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _while = __webpack_require__(/*! ./while */ "./js/ast/commands/while.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DoWhile = exports.DoWhile = function (_While) {
  _inherits(DoWhile, _While);

  function DoWhile(condition, commandBlock) {
    _classCallCheck(this, DoWhile);

    return _possibleConstructorReturn(this, (DoWhile.__proto__ || Object.getPrototypeOf(DoWhile)).call(this, condition, commandBlock));
  }

  _createClass(DoWhile, [{
    key: 'testFirst',
    get: function get() {
      return false;
    }
  }]);

  return DoWhile;
}(_while.While);

/***/ }),

/***/ "./js/ast/commands/for.js":
/*!********************************!*\
  !*** ./js/ast/commands/for.js ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.For = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _command = __webpack_require__(/*! ./command */ "./js/ast/commands/command.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var For = exports.For = function (_Command) {
  _inherits(For, _Command);

  function For(assignment, condition, increment, commandBlock) {
    _classCallCheck(this, For);

    var _this = _possibleConstructorReturn(this, (For.__proto__ || Object.getPrototypeOf(For)).call(this));

    _this.assignment = assignment;
    _this.condition = condition;
    _this.increment = increment;
    _this.commandBlock = commandBlock;
    return _this;
  }

  _createClass(For, [{
    key: 'commands',
    get: function get() {
      return this.commandBlock.commands;
    }
  }]);

  return For;
}(_command.Command);

/***/ }),

/***/ "./js/ast/commands/formalParameter.js":
/*!********************************************!*\
  !*** ./js/ast/commands/formalParameter.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var FormalParameter = exports.FormalParameter = function () {
  function FormalParameter(type, id) {
    var byRef = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

    _classCallCheck(this, FormalParameter);

    this.type = type;
    this.id = id;
    this.byRef = byRef;
    this._sourceInfo = null;
  }

  _createClass(FormalParameter, [{
    key: "sourceInfo",
    set: function set(sourceInfo) {
      this._sourceInfo = sourceInfo;
    },
    get: function get() {
      return this._sourceInfo;
    }
  }]);

  return FormalParameter;
}();

/***/ }),

/***/ "./js/ast/commands/function.js":
/*!*************************************!*\
  !*** ./js/ast/commands/function.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Function = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Function = exports.Function = function () {
  function Function(name, returnType, formalParameters, commandBlock) {
    _classCallCheck(this, Function);

    this.name = name;
    this.returnType = returnType;
    this.formalParameters = formalParameters;
    this.commandBlock = commandBlock;
    this._sourceInfo = null;
  }

  _createClass(Function, [{
    key: 'isMain',
    get: function get() {
      return this.name === null && this.returnType.isCompatible(_types.Types.VOID);
    }
  }, {
    key: 'commands',
    get: function get() {
      return this.commandBlock.commands;
    }
  }, {
    key: 'variablesDeclarations',
    get: function get() {
      return this.commandBlock.variables;
    }
  }, {
    key: 'sourceInfo',
    set: function set(sourceInfo) {
      this._sourceInfo = sourceInfo;
    },
    get: function get() {
      return this._sourceInfo;
    }
  }]);

  return Function;
}();

/***/ }),

/***/ "./js/ast/commands/ifThenElse.js":
/*!***************************************!*\
  !*** ./js/ast/commands/ifThenElse.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IfThenElse = undefined;

var _command = __webpack_require__(/*! ./command */ "./js/ast/commands/command.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var IfThenElse = exports.IfThenElse = function (_Command) {
  _inherits(IfThenElse, _Command);

  function IfThenElse(condition, ifTrue, ifFalse) {
    _classCallCheck(this, IfThenElse);

    var _this = _possibleConstructorReturn(this, (IfThenElse.__proto__ || Object.getPrototypeOf(IfThenElse)).call(this));

    _this.condition = condition;
    _this.ifTrue = ifTrue;
    _this.ifFalse = ifFalse;
    return _this;
  }

  return IfThenElse;
}(_command.Command);

/***/ }),

/***/ "./js/ast/commands/index.js":
/*!**********************************!*\
  !*** ./js/ast/commands/index.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FunctionCall = exports.FormalParameter = exports.SysCall = exports.Case = exports.Switch = exports.DoWhile = exports.CommandBlock = exports.IfThenElse = exports.Function = exports.For = exports.While = exports.ArrayDeclaration = exports.Declaration = exports.ArrayIndexAssign = exports.Assign = exports.Return = exports.Break = undefined;

var _break = __webpack_require__(/*! ./break */ "./js/ast/commands/break.js");

var _return = __webpack_require__(/*! ./return */ "./js/ast/commands/return.js");

var _assign = __webpack_require__(/*! ./assign */ "./js/ast/commands/assign.js");

var _arrayAssign = __webpack_require__(/*! ./arrayAssign */ "./js/ast/commands/arrayAssign.js");

var _declaration = __webpack_require__(/*! ./declaration */ "./js/ast/commands/declaration.js");

var _arrayDeclaration = __webpack_require__(/*! ./arrayDeclaration */ "./js/ast/commands/arrayDeclaration.js");

var _while = __webpack_require__(/*! ./while */ "./js/ast/commands/while.js");

var _for = __webpack_require__(/*! ./for */ "./js/ast/commands/for.js");

var _function = __webpack_require__(/*! ./function */ "./js/ast/commands/function.js");

var _ifThenElse = __webpack_require__(/*! ./ifThenElse */ "./js/ast/commands/ifThenElse.js");

var _commandBlock = __webpack_require__(/*! ./commandBlock */ "./js/ast/commands/commandBlock.js");

var _doWhile = __webpack_require__(/*! ./doWhile */ "./js/ast/commands/doWhile.js");

var _switch = __webpack_require__(/*! ./switch */ "./js/ast/commands/switch.js");

var _case = __webpack_require__(/*! ./case */ "./js/ast/commands/case.js");

var _sysCall = __webpack_require__(/*! ./sysCall */ "./js/ast/commands/sysCall.js");

var _formalParameter = __webpack_require__(/*! ./formalParameter */ "./js/ast/commands/formalParameter.js");

var _functionCall = __webpack_require__(/*! ./../expressions/functionCall */ "./js/ast/expressions/functionCall.js");

//Proxy to expression since they do exatcly the same thing

exports.Break = _break.Break;
exports.Return = _return.Return;
exports.Assign = _assign.Assign;
exports.ArrayIndexAssign = _arrayAssign.ArrayIndexAssign;
exports.Declaration = _declaration.Declaration;
exports.ArrayDeclaration = _arrayDeclaration.ArrayDeclaration;
exports.While = _while.While;
exports.For = _for.For;
exports.Function = _function.Function;
exports.IfThenElse = _ifThenElse.IfThenElse;
exports.CommandBlock = _commandBlock.CommandBlock;
exports.DoWhile = _doWhile.DoWhile;
exports.Switch = _switch.Switch;
exports.Case = _case.Case;
exports.SysCall = _sysCall.SysCall;
exports.FormalParameter = _formalParameter.FormalParameter;
exports.FunctionCall = _functionCall.FunctionCall;

/***/ }),

/***/ "./js/ast/commands/return.js":
/*!***********************************!*\
  !*** ./js/ast/commands/return.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Return = undefined;

var _command = __webpack_require__(/*! ./command */ "./js/ast/commands/command.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Return = exports.Return = function (_Command) {
  _inherits(Return, _Command);

  function Return(expression) {
    _classCallCheck(this, Return);

    var _this = _possibleConstructorReturn(this, (Return.__proto__ || Object.getPrototypeOf(Return)).call(this));

    _this.expression = expression;
    return _this;
  }

  return Return;
}(_command.Command);

/***/ }),

/***/ "./js/ast/commands/switch.js":
/*!***********************************!*\
  !*** ./js/ast/commands/switch.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Switch = undefined;

var _command = __webpack_require__(/*! ./command */ "./js/ast/commands/command.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Switch = exports.Switch = function (_Command) {
  _inherits(Switch, _Command);

  function Switch(expression, cases) {
    _classCallCheck(this, Switch);

    var _this = _possibleConstructorReturn(this, (Switch.__proto__ || Object.getPrototypeOf(Switch)).call(this));

    _this.expression = expression;
    _this.cases = cases;
    return _this;
  }

  return Switch;
}(_command.Command);

/***/ }),

/***/ "./js/ast/commands/sysCall.js":
/*!************************************!*\
  !*** ./js/ast/commands/sysCall.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * This class represents all the language defined functions.
 * The language processor uses the id provided here to properly execute the desired function.
 * The function is actually implemented inside the language processor.
 * All the functions can be found at: js/processor/definedFunctions.js
 */
var SysCall = exports.SysCall = function SysCall(langFunc) {
  _classCallCheck(this, SysCall);

  this.langFunc = langFunc;
};

/***/ }),

/***/ "./js/ast/commands/while.js":
/*!**********************************!*\
  !*** ./js/ast/commands/while.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.While = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _command = __webpack_require__(/*! ./command */ "./js/ast/commands/command.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var While = exports.While = function (_Command) {
  _inherits(While, _Command);

  function While(expression, commandBlock) {
    _classCallCheck(this, While);

    var _this = _possibleConstructorReturn(this, (While.__proto__ || Object.getPrototypeOf(While)).call(this));

    _this.expression = expression;
    _this.commandBlock = commandBlock;
    return _this;
  }

  _createClass(While, [{
    key: 'commands',
    get: function get() {
      return this.commandBlock.commands;
    }
  }, {
    key: 'testFirst',
    get: function get() {
      return true;
    }
  }]);

  return While;
}(_command.Command);

/***/ }),

/***/ "./js/ast/error/syntaxError.js":
/*!*************************************!*\
  !*** ./js/ast/error/syntaxError.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var SyntaxError = exports.SyntaxError = function (_Error) {
  _inherits(SyntaxError, _Error);

  function SyntaxError() {
    var _ref;

    _classCallCheck(this, SyntaxError);

    for (var _len = arguments.length, msg = Array(_len), _key = 0; _key < _len; _key++) {
      msg[_key] = arguments[_key];
    }

    var _this = _possibleConstructorReturn(this, (_ref = SyntaxError.__proto__ || Object.getPrototypeOf(SyntaxError)).call.apply(_ref, [this].concat(msg)));

    if (Error.captureStackTrace) Error.captureStackTrace(_this, SyntaxError);
    return _this;
  }

  return SyntaxError;
}(Error);

/***/ }),

/***/ "./js/ast/error/syntaxErrorFactory.js":
/*!********************************************!*\
  !*** ./js/ast/error/syntaxErrorFactory.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SyntaxErrorFactory = undefined;

var _localizedStringsService = __webpack_require__(/*! ./../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _syntaxError = __webpack_require__(/*! ./syntaxError */ "./js/ast/error/syntaxError.js");

var SyntaxErrorFactory = exports.SyntaxErrorFactory = Object.freeze({
  extra_lines: function extra_lines() {
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("extra_lines"));
  },
  token_missing_one: function token_missing_one(expected, token) {
    var context = [expected, token.text, token.line, token.column];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("token_missing_one", context));
  },
  token_missing_list: function token_missing_list(expectedList, token) {
    var line = expectedList.join(_localizedStringsService.LocalizedStrings.getOR());
    return SyntaxErrorFactory.token_missing_one(line, token);
  },
  id_missing: function id_missing(token) {
    var context = [token.text, token.line, token.column];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("id_missing", context));
  },
  eos_missing: function eos_missing(token) {
    var context = [token.line, token.column];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("eos_missing", context));
  },
  invalid_array_dimension: function invalid_array_dimension(typeName, token) {
    var context = [token.line, token.column, typeName];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("invalid_array_dimension", context));
  },
  invalid_array_size: function invalid_array_size(token) {
    var context = [token.line];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("invalid_array_size", context));
  },
  invalid_main_return: function invalid_main_return(name, typeName, token) {
    var context = [name, typeName, token.line];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("invalid_main_return", context));
  },
  invalid_var_declaration: function invalid_var_declaration(token) {
    var context = [token.line];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("invalid_var_declaration", context));
  },
  invalid_break_command: function invalid_break_command(cmdName, token) {
    var context = [token.line, cmdName];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("invalid_break_command", context));
  },
  invalid_terminal: function invalid_terminal(token) {
    var context = [token.text, token.line, token.column];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError('invalid_terminal', context));
  },
  invalid_type: function invalid_type(list, token) {
    var line = list.join(_localizedStringsService.LocalizedStrings.getOR());
    var context = [token.text, token.line, token.column, line];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("invalid_type", context));
  },
  const_not_init: function const_not_init(token) {
    var context = [token.line, token.column];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("const_not_init", context));
  },
  invalid_id_format: function invalid_id_format(token) {
    var context = [token.text, token.line, token.column];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("invalid_id_format", context));
  },
  duplicate_function: function duplicate_function(token) {
    var context = [token.text, token.line, token.column];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("duplicate_function", context));
  },
  main_parameters: function main_parameters() {
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("main_parameters"));
  },
  duplicate_variable: function duplicate_variable(token) {
    var context = [token.text, token.line, token.column];
    return new _syntaxError.SyntaxError(_localizedStringsService.LocalizedStrings.getError("duplicate_variable", context));
  }
});

/***/ }),

/***/ "./js/ast/expressions/arrayAccess.js":
/*!*******************************************!*\
  !*** ./js/ast/expressions/arrayAccess.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.ArrayAccess = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _expression = __webpack_require__(/*! ./expression */ "./js/ast/expressions/expression.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ArrayAccess = exports.ArrayAccess = function (_Expression) {
	_inherits(ArrayAccess, _Expression);

	function ArrayAccess(id, line, column) {
		_classCallCheck(this, ArrayAccess);

		var _this = _possibleConstructorReturn(this, (ArrayAccess.__proto__ || Object.getPrototypeOf(ArrayAccess)).call(this));

		_this.id = id;
		_this.line = line;
		_this.column = column;
		return _this;
	}

	_createClass(ArrayAccess, [{
		key: 'toString',
		value: function toString() {
			var strLine = this.line.toString();
			var strColumn = null;
			if (this.column) {
				strColumn = this.column.toString();
			}
			if (strColumn) {
				return this.id + '[' + strLine + '][' + strColumn + ']';
			} else {
				return this.id + '[' + strLine + ']';
			}
		}
	}]);

	return ArrayAccess;
}(_expression.Expression);

/***/ }),

/***/ "./js/ast/expressions/arrayLiteral.js":
/*!********************************************!*\
  !*** ./js/ast/expressions/arrayLiteral.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ArrayLiteral = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _literal = __webpack_require__(/*! ./literal */ "./js/ast/expressions/literal.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ArrayLiteral = exports.ArrayLiteral = function (_Literal) {
  _inherits(ArrayLiteral, _Literal);

  function ArrayLiteral(type, value) {
    _classCallCheck(this, ArrayLiteral);

    var _this = _possibleConstructorReturn(this, (ArrayLiteral.__proto__ || Object.getPrototypeOf(ArrayLiteral)).call(this, type));

    _this.value = value;
    return _this;
  }

  _createClass(ArrayLiteral, [{
    key: 'validateType',
    value: function validateType() {
      // let valid = true;
      // if(this.columns !== null) {
      //   const len = this.columns;
      //   const len2 = this.lines;
      //   for (let i = len - 1; i >= 0; i--) {
      //     for (let j = len2 - 1; j >= 0; j--) {
      //       if(this.value[i].value[j].type !== this.subtype) {
      //         valid = false;
      //         break;
      //       }
      //     }
      //   }
      // } else {
      //   const len = this.lines;
      //   for (var i = len - 1; i >= 0; i--) {
      //     if(this.value[i].type !== this.subtype) {
      //       valid = false;
      //       break;
      //     }
      //   }
      // }
      return true; //valid;
    }
  }, {
    key: 'validateSize',
    value: function validateSize() {
      var valid = true;
      if (this.columns !== null) {
        var equalityTest = data.value.map(function (v) {
          return v.length;
        }).reduce(function (old, next) {
          if (old === null) {
            return next;
          } else if (old === next) {
            return old;
          } else {
            return -1;
          }
        }, null);
        valid = equalityTest !== -1;
      }
      return valid;
    }
  }, {
    key: 'toString',
    value: function toString() {
      var strList = this.value.map(function (arrayLiteral) {
        return arrayLiteral.toString();
      });
      return "{" + strList.join(',') + "}";
    }
  }, {
    key: 'subtype',
    get: function get() {
      var element = this.value[0];
      if (element instanceof ArrayLiteral) {
        return element.value[0].type;
      } else {
        return element.type;
      }
    }
  }, {
    key: 'lines',
    get: function get() {
      return this.value.length;
    }
  }, {
    key: 'columns',
    get: function get() {
      var element = this.value[0];
      if (!(element instanceof ArrayLiteral)) {
        return null;
      } else {
        return element.value[0].length;
      }
    }
  }, {
    key: 'isVector',
    get: function get() {
      return this.columns === null;
    }
  }, {
    key: 'isValid',
    get: function get() {
      return true; //this.validateType() && this.validateSize();
    }
  }]);

  return ArrayLiteral;
}(_literal.Literal);

/***/ }),

/***/ "./js/ast/expressions/boolLiteral.js":
/*!*******************************************!*\
  !*** ./js/ast/expressions/boolLiteral.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.BoolLiteral = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _literal = __webpack_require__(/*! ./literal */ "./js/ast/expressions/literal.js");

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

var _parsers = __webpack_require__(/*! ./../../typeSystem/parsers */ "./js/typeSystem/parsers.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var BoolLiteral = exports.BoolLiteral = function (_Literal) {
  _inherits(BoolLiteral, _Literal);

  function BoolLiteral(value) {
    _classCallCheck(this, BoolLiteral);

    var _this = _possibleConstructorReturn(this, (BoolLiteral.__proto__ || Object.getPrototypeOf(BoolLiteral)).call(this, _types.Types.BOOLEAN));

    _this.value = value;
    return _this;
  }

  _createClass(BoolLiteral, [{
    key: 'toString',
    value: function toString() {
      return (0, _parsers.convertBoolToString)(this.value);
    }
  }]);

  return BoolLiteral;
}(_literal.Literal);

/***/ }),

/***/ "./js/ast/expressions/expression.js":
/*!******************************************!*\
  !*** ./js/ast/expressions/expression.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Expression = exports.Expression = function () {
	function Expression() {
		_classCallCheck(this, Expression);

		this._sourceInfo = null;
	}

	_createClass(Expression, [{
		key: "sourceInfo",
		set: function set(sourceInfo) {
			this._sourceInfo = sourceInfo;
		},
		get: function get() {
			return this._sourceInfo;
		}
	}]);

	return Expression;
}();

/***/ }),

/***/ "./js/ast/expressions/functionCall.js":
/*!********************************************!*\
  !*** ./js/ast/expressions/functionCall.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.FunctionCall = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _expression = __webpack_require__(/*! ./expression */ "./js/ast/expressions/expression.js");

var _definedFunctions = __webpack_require__(/*! ../../processor/definedFunctions */ "./js/processor/definedFunctions.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var FunctionCall = exports.FunctionCall = function (_Expression) {
	_inherits(FunctionCall, _Expression);

	function FunctionCall(id, actualParameters) {
		_classCallCheck(this, FunctionCall);

		var _this = _possibleConstructorReturn(this, (FunctionCall.__proto__ || Object.getPrototypeOf(FunctionCall)).call(this));

		_this.id = id;
		_this.actualParameters = actualParameters;
		return _this;
	}

	_createClass(FunctionCall, [{
		key: 'toString',
		value: function toString() {
			var name = null;
			if (this.isMainCall) {
				name = _definedFunctions.LanguageDefinedFunction.getMainFunctionName();
			} else {
				name = _definedFunctions.LanguageDefinedFunction.getLocalName(this.id);
			}
			var params = null;
			if (this.actualParameters.length == 0) {
				params = "()";
			} else {
				var strParams = this.actualParameters.map(function (v) {
					return v.toString();
				});
				params = "(" + strParams.join(",") + ")";
			}
			return name + params;
		}
	}, {
		key: 'isMainCall',
		get: function get() {
			return this.id === null;
		}
	}, {
		key: 'parametersSize',
		get: function get() {
			return this.actualParameters.length;
		}
	}]);

	return FunctionCall;
}(_expression.Expression);

/***/ }),

/***/ "./js/ast/expressions/index.js":
/*!*************************************!*\
  !*** ./js/ast/expressions/index.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnaryApp = exports.InfixApp = exports.VariableLiteral = exports.ArrayLiteral = exports.StringLiteral = exports.BoolLiteral = exports.RealLiteral = exports.IntLiteral = exports.FunctionCall = exports.ArrayAccess = undefined;

var _arrayAccess = __webpack_require__(/*! ./arrayAccess */ "./js/ast/expressions/arrayAccess.js");

var _functionCall = __webpack_require__(/*! ./functionCall */ "./js/ast/expressions/functionCall.js");

var _intLiteral = __webpack_require__(/*! ./intLiteral */ "./js/ast/expressions/intLiteral.js");

var _realLiteral = __webpack_require__(/*! ./realLiteral */ "./js/ast/expressions/realLiteral.js");

var _boolLiteral = __webpack_require__(/*! ./boolLiteral */ "./js/ast/expressions/boolLiteral.js");

var _stringLiteral = __webpack_require__(/*! ./stringLiteral */ "./js/ast/expressions/stringLiteral.js");

var _arrayLiteral = __webpack_require__(/*! ./arrayLiteral */ "./js/ast/expressions/arrayLiteral.js");

var _variableLiteral = __webpack_require__(/*! ./variableLiteral */ "./js/ast/expressions/variableLiteral.js");

var _infixApp = __webpack_require__(/*! ./infixApp */ "./js/ast/expressions/infixApp.js");

var _unaryApp = __webpack_require__(/*! ./unaryApp */ "./js/ast/expressions/unaryApp.js");

exports.ArrayAccess = _arrayAccess.ArrayAccess;
exports.FunctionCall = _functionCall.FunctionCall;
exports.IntLiteral = _intLiteral.IntLiteral;
exports.RealLiteral = _realLiteral.RealLiteral;
exports.BoolLiteral = _boolLiteral.BoolLiteral;
exports.StringLiteral = _stringLiteral.StringLiteral;
exports.ArrayLiteral = _arrayLiteral.ArrayLiteral;
exports.VariableLiteral = _variableLiteral.VariableLiteral;
exports.InfixApp = _infixApp.InfixApp;
exports.UnaryApp = _unaryApp.UnaryApp;

/***/ }),

/***/ "./js/ast/expressions/infixApp.js":
/*!****************************************!*\
  !*** ./js/ast/expressions/infixApp.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.InfixApp = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _expression = __webpack_require__(/*! ./expression */ "./js/ast/expressions/expression.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var InfixApp = exports.InfixApp = function (_Expression) {
  _inherits(InfixApp, _Expression);

  function InfixApp(op, left, right) {
    _classCallCheck(this, InfixApp);

    var _this = _possibleConstructorReturn(this, (InfixApp.__proto__ || Object.getPrototypeOf(InfixApp)).call(this));

    _this.op = op;
    _this.left = left;
    _this.right = right;
    return _this;
  }

  _createClass(InfixApp, [{
    key: 'toString',
    value: function toString() {
      var l = this.left.toString();
      var op = this.op.value;
      var r = this.right.toString();
      return l + op + r;
    }
  }]);

  return InfixApp;
}(_expression.Expression);

/***/ }),

/***/ "./js/ast/expressions/intLiteral.js":
/*!******************************************!*\
  !*** ./js/ast/expressions/intLiteral.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IntLiteral = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _literal = __webpack_require__(/*! ./literal */ "./js/ast/expressions/literal.js");

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

var _parsers = __webpack_require__(/*! ./../../typeSystem/parsers */ "./js/typeSystem/parsers.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var IntLiteral = exports.IntLiteral = function (_Literal) {
  _inherits(IntLiteral, _Literal);

  function IntLiteral(value) {
    _classCallCheck(this, IntLiteral);

    var _this = _possibleConstructorReturn(this, (IntLiteral.__proto__ || Object.getPrototypeOf(IntLiteral)).call(this, _types.Types.INTEGER));

    _this.value = value;
    return _this;
  }

  _createClass(IntLiteral, [{
    key: 'toString',
    value: function toString() {
      return (0, _parsers.convertToString)(this.value, this.type);
    }
  }]);

  return IntLiteral;
}(_literal.Literal);

/***/ }),

/***/ "./js/ast/expressions/literal.js":
/*!***************************************!*\
  !*** ./js/ast/expressions/literal.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Literal = undefined;

var _expression = __webpack_require__(/*! ./expression */ "./js/ast/expressions/expression.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Literal = exports.Literal = function (_Expression) {
  _inherits(Literal, _Expression);

  function Literal(type) {
    _classCallCheck(this, Literal);

    var _this = _possibleConstructorReturn(this, (Literal.__proto__ || Object.getPrototypeOf(Literal)).call(this));

    _this.type = type;
    return _this;
  }

  return Literal;
}(_expression.Expression);

/***/ }),

/***/ "./js/ast/expressions/realLiteral.js":
/*!*******************************************!*\
  !*** ./js/ast/expressions/realLiteral.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RealLiteral = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _literal = __webpack_require__(/*! ./literal */ "./js/ast/expressions/literal.js");

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

var _parsers = __webpack_require__(/*! ./../../typeSystem/parsers */ "./js/typeSystem/parsers.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var RealLiteral = exports.RealLiteral = function (_Literal) {
  _inherits(RealLiteral, _Literal);

  function RealLiteral(value) {
    _classCallCheck(this, RealLiteral);

    var _this = _possibleConstructorReturn(this, (RealLiteral.__proto__ || Object.getPrototypeOf(RealLiteral)).call(this, _types.Types.REAL));

    _this.value = value;
    return _this;
  }

  _createClass(RealLiteral, [{
    key: 'toString',
    value: function toString() {
      return (0, _parsers.convertToString)(this.value, this.type);
    }
  }]);

  return RealLiteral;
}(_literal.Literal);

/***/ }),

/***/ "./js/ast/expressions/stringLiteral.js":
/*!*********************************************!*\
  !*** ./js/ast/expressions/stringLiteral.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.StringLiteral = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _literal = __webpack_require__(/*! ./literal */ "./js/ast/expressions/literal.js");

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var StringLiteral = exports.StringLiteral = function (_Literal) {
  _inherits(StringLiteral, _Literal);

  function StringLiteral(value) {
    _classCallCheck(this, StringLiteral);

    var _this = _possibleConstructorReturn(this, (StringLiteral.__proto__ || Object.getPrototypeOf(StringLiteral)).call(this, _types.Types.STRING));

    _this.value = value;
    return _this;
  }

  _createClass(StringLiteral, [{
    key: 'toString',
    value: function toString() {
      return this.value;
    }
  }]);

  return StringLiteral;
}(_literal.Literal);

/***/ }),

/***/ "./js/ast/expressions/unaryApp.js":
/*!****************************************!*\
  !*** ./js/ast/expressions/unaryApp.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UnaryApp = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _infixApp = __webpack_require__(/*! ./infixApp */ "./js/ast/expressions/infixApp.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var UnaryApp = exports.UnaryApp = function (_InfixApp) {
  _inherits(UnaryApp, _InfixApp);

  function UnaryApp(op, left) {
    _classCallCheck(this, UnaryApp);

    return _possibleConstructorReturn(this, (UnaryApp.__proto__ || Object.getPrototypeOf(UnaryApp)).call(this, op, left, null));
  }

  _createClass(UnaryApp, [{
    key: 'toString',
    value: function toString() {
      var l = this.left.toString();
      var op = this.op.value;
      return op + l;
    }
  }]);

  return UnaryApp;
}(_infixApp.InfixApp);

/***/ }),

/***/ "./js/ast/expressions/variableLiteral.js":
/*!***********************************************!*\
  !*** ./js/ast/expressions/variableLiteral.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.VariableLiteral = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _literal = __webpack_require__(/*! ./literal */ "./js/ast/expressions/literal.js");

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var VariableLiteral = exports.VariableLiteral = function (_Literal) {
  _inherits(VariableLiteral, _Literal);

  function VariableLiteral(id) {
    _classCallCheck(this, VariableLiteral);

    var _this = _possibleConstructorReturn(this, (VariableLiteral.__proto__ || Object.getPrototypeOf(VariableLiteral)).call(this, _types.Types.UNDEFINED));

    _this.id = id;
    return _this;
  }

  _createClass(VariableLiteral, [{
    key: 'toString',
    value: function toString() {
      return this.id;
    }
  }]);

  return VariableLiteral;
}(_literal.Literal);

/***/ }),

/***/ "./js/ast/ivprogParser.js":
/*!********************************!*\
  !*** ./js/ast/ivprogParser.js ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IVProgParser = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _index = __webpack_require__(/*! antlr4/index */ "./node_modules/antlr4/index.js");

var _expressions = __webpack_require__(/*! ./expressions/ */ "./js/ast/expressions/index.js");

var Expressions = _interopRequireWildcard(_expressions);

var _commands = __webpack_require__(/*! ./commands/ */ "./js/ast/commands/index.js");

var Commands = _interopRequireWildcard(_commands);

var _parsers = __webpack_require__(/*! ./../typeSystem/parsers */ "./js/typeSystem/parsers.js");

var _types = __webpack_require__(/*! ./../typeSystem/types */ "./js/typeSystem/types.js");

var _compoundType = __webpack_require__(/*! ./../typeSystem/compoundType */ "./js/typeSystem/compoundType.js");

var _sourceInfo2 = __webpack_require__(/*! ./sourceInfo */ "./js/ast/sourceInfo.js");

var _operators = __webpack_require__(/*! ./operators */ "./js/ast/operators.js");

var _syntaxErrorFactory = __webpack_require__(/*! ./error/syntaxErrorFactory */ "./js/ast/error/syntaxErrorFactory.js");

var _definedFunctions = __webpack_require__(/*! ./../processor/definedFunctions */ "./js/processor/definedFunctions.js");

var _languageService = __webpack_require__(/*! ../services/languageService */ "./js/services/languageService.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var IVProgParser = exports.IVProgParser = function () {
  _createClass(IVProgParser, null, [{
    key: 'createParser',
    value: function createParser(input) {
      var lexerClass = _languageService.LanguageService.getCurrentLexer();
      return new IVProgParser(input, lexerClass);
    }

    // <BEGIN scope consts>

  }, {
    key: 'BASE',
    get: function get() {
      return 0;
    }
  }, {
    key: 'FUNCTION',
    get: function get() {
      return 1;
    }
  }, {
    key: 'COMMAND',
    get: function get() {
      return 2;
    }
  }, {
    key: 'BREAKABLE',
    get: function get() {
      return 4;
    }
    // </ END scope consts>

  }]);

  function IVProgParser(input, lexerClass) {
    _classCallCheck(this, IVProgParser);

    this.lexerClass = lexerClass;
    this.lexer = new lexerClass(new _index.InputStream(input));
    this.tokenStream = new _index.CommonTokenStream(this.lexer);
    this.tokenStream.fill();
    this.pos = 1;
    this.variableTypes = [this.lexerClass.RK_INTEGER, this.lexerClass.RK_REAL, this.lexerClass.RK_BOOLEAN, this.lexerClass.RK_STRING];
    this.functionTypes = this.variableTypes.concat(this.lexerClass.RK_VOID);
    this.parsingArrayDimension = 0;
    this.scope = [];
    this.langFuncs = _languageService.LanguageService.getCurrentLangFuncs();
    this.definedFuncsNameList = [];
    this.definedVariablesStack = [];
  }

  _createClass(IVProgParser, [{
    key: 'parseTree',
    value: function parseTree() {
      return this.parseProgram();
    }
  }, {
    key: 'getToken',
    value: function getToken() {
      var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.pos;

      // if(index === null)
      //   index = this.pos;
      return this.tokenStream.LT(index);
    }
  }, {
    key: 'insideScope',
    value: function insideScope(scope) {
      if (this.scope.length <= 0) {
        return IVProgParser.BASE === scope;
      } else {
        return this.scope[this.scope.length - 1] === scope;
      }
    }
  }, {
    key: 'pushScope',
    value: function pushScope(scope) {
      this.scope.push(scope);
    }
  }, {
    key: 'pushVariableStack',
    value: function pushVariableStack() {
      this.definedVariablesStack.push([]);
    }
  }, {
    key: 'popScope',
    value: function popScope() {
      return this.scope.pop();
    }
  }, {
    key: 'popVariableStack',
    value: function popVariableStack() {
      return this.definedVariablesStack.pop();
    }
  }, {
    key: 'getCurrentVariableStack',
    value: function getCurrentVariableStack() {
      return this.definedVariablesStack[this.definedVariablesStack.length - 1];
    }
  }, {
    key: 'isEOF',
    value: function isEOF() {
      this.getToken(this.pos);
      return this.tokenStream.fetchedEOF;
    }
  }, {
    key: 'parseProgram',
    value: function parseProgram() {
      var token = this.getToken();
      var globalVars = [];
      var functions = [];

      if (this.lexerClass.RK_PROGRAM === token.type) {
        this.pos++;
        this.consumeNewLines();
        this.checkOpenCurly();
        this.pos++;
        this.pushVariableStack();
        while (true) {
          this.consumeNewLines();
          var _token = this.getToken();
          if (_token.type === this.lexerClass.RK_CONST || this.isVariableType(_token)) {
            globalVars = globalVars.concat(this.parseGlobalVariables());
          } else if (_token.type === this.lexerClass.RK_FUNCTION) {
            this.pushVariableStack();
            functions = functions.concat(this.parseFunction());
            this.popVariableStack();
          } else {
            break;
          }
        }
        this.consumeNewLines();
        this.checkCloseCurly();
        this.pos++;
        this.consumeNewLines();
        if (!this.isEOF()) {
          throw _syntaxErrorFactory.SyntaxErrorFactory.extra_lines();
        }
        this.popVariableStack();
        return { global: globalVars, functions: functions };
      } else {
        throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_PROGRAM], token);
      }
    }
  }, {
    key: 'checkOpenCurly',
    value: function checkOpenCurly() {
      var attempt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var token = this.getToken();
      if (this.lexerClass.OPEN_CURLY !== token.type) {
        if (!attempt) throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one('{', token);else return false;
      }
      return true;
    }
  }, {
    key: 'checkCloseCurly',
    value: function checkCloseCurly() {
      var attempt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var token = this.getToken();
      if (this.lexerClass.CLOSE_CURLY !== token.type) {
        if (!attempt) throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one('}', token);else return false;
      }
      return true;
    }

    /* It checks if the current token at position pos is a ']'.
    * As a check function it doesn't increment pos.
    *
    * @params bool:attempt, indicates that the token is optional. Defaults: false
    *
    * @returns true if the attempt is true and current token is '[',
    *   false is attempt is true and current token is not '['
    **/

  }, {
    key: 'checkOpenBrace',
    value: function checkOpenBrace() {
      var attempt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var token = this.getToken();
      if (this.lexerClass.OPEN_BRACE !== token.type) {
        if (!attempt) {
          throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one('[', token);
        } else {
          return false;
        }
      }
      return true;
    }
  }, {
    key: 'checkCloseBrace',
    value: function checkCloseBrace() {
      var attempt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var token = this.getToken();
      if (this.lexerClass.CLOSE_BRACE !== token.type) {
        if (!attempt) {
          throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one(']', token);
        } else {
          return false;
        }
      }
      return true;
    }
  }, {
    key: 'checkOpenParenthesis',
    value: function checkOpenParenthesis() {
      var attempt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var token = this.getToken();
      if (this.lexerClass.OPEN_PARENTHESIS !== token.type) {
        if (!attempt) {
          throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one('(', token);
        } else {
          return false;
        }
      }
      return true;
    }
  }, {
    key: 'checkCloseParenthesis',
    value: function checkCloseParenthesis() {
      var attempt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var token = this.getToken();
      if (this.lexerClass.CLOSE_PARENTHESIS !== token.type) {
        if (!attempt) {
          throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one(')', token);
        } else {
          return false;
        }
      }
      return true;
    }
  }, {
    key: 'checkEOS',
    value: function checkEOS() {
      var attempt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var eosToken = this.getToken();
      if (eosToken.type !== this.lexerClass.EOS) {
        if (!attempt) throw _syntaxErrorFactory.SyntaxErrorFactory.eos_missing(eosToken);else return false;
      }
      return true;
    }
  }, {
    key: 'checkFunctionDuplicate',
    value: function checkFunctionDuplicate(functionID, funcIDToken) {
      var id = functionID === null ? "$main" : functionID;
      var index = this.definedFuncsNameList.indexOf(id);
      if (index !== -1) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.duplicate_function(funcIDToken);
      }
      this.definedFuncsNameList.push(id);
    }
  }, {
    key: 'checkVariableDuplicate',
    value: function checkVariableDuplicate(variableID, variableIDToken) {
      var index = this.getCurrentVariableStack().indexOf(variableID);
      if (index !== -1) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.duplicate_variable(variableIDToken);
      }
      this.getCurrentVariableStack().push(variableID);
    }
  }, {
    key: 'consumeForSemiColon',
    value: function consumeForSemiColon() {
      var eosToken = this.getToken();
      if (eosToken.type === this.lexerClass.EOS && eosToken.text.match(';')) {
        this.pos++;
        return;
      }
      throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one(';', eosToken);
    }
  }, {
    key: 'parseGlobalVariables',
    value: function parseGlobalVariables() {
      var decl = this.parseMaybeConst();
      this.checkEOS();
      this.pos++;
      return decl;
    }

    /*
    * Checks if the next token is PR_CONST. It's only available
    * at global variables declaration level
    * @returns Declararion(const, type, id, initVal?)
    **/

  }, {
    key: 'parseMaybeConst',
    value: function parseMaybeConst() {
      var constToken = this.getToken();
      if (constToken.type === this.lexerClass.RK_CONST) {
        this.pos++;
        var typeString = this.parseType();
        return this.parseDeclaration(typeString, true);
      } else if (this.isVariableType(constToken)) {
        var _typeString = this.parseType();
        return this.parseDeclaration(_typeString);
      } else {
        throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_list([this.lexer.literalNames[this.lexerClass.RK_CONST]].concat(this.getTypeArray()), constToken);
      }
    }

    /*
    * Parses a declarion of the form: type --- id --- (= --- EAnd)?
    * @returns a list of Declararion(const, type, id, initVal?)
    **/

  }, {
    key: 'parseDeclaration',
    value: function parseDeclaration(typeString) {
      var isConst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

      var initial = null;
      var dim1 = null;
      var dim2 = null;
      var idToken = this.getToken();
      var idString = this.parseID();
      this.checkVariableDuplicate(idString, idToken);
      // Check for array or vector
      // ID[int/IDi][int/IDj]
      if (this.checkOpenBrace(true)) {
        this.pos++;
        this.consumeNewLines();
        dim1 = this.parseArrayDimension();
        this.consumeNewLines();
        this.checkCloseBrace();
        this.pos++;
        if (this.checkOpenBrace(true)) {
          this.pos++;
          this.consumeNewLines();
          dim2 = this.parseArrayDimension();
          this.consumeNewLines();
          this.checkCloseBrace();
          this.pos++;
        }
      }

      var equalsToken = this.getToken();
      if (isConst && equalsToken.type !== this.lexerClass.EQUAL) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.const_not_init(idToken);
      }
      if (equalsToken.type === this.lexerClass.EQUAL) {
        this.pos++;
        initial = this.parseExpressionOR();
      }
      var declaration = null;
      var dimensions = 0;
      if (dim1 !== null) {
        dimensions++;
        if (dim2 !== null) {
          dimensions++;
        }
        declaration = new Commands.ArrayDeclaration(idString, new _compoundType.CompoundType(typeString, dimensions), dim1, dim2, initial, isConst);
      } else {
        declaration = new Commands.Declaration(idString, typeString, initial, isConst);
      }
      declaration.sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(idToken);
      var commaToken = this.getToken();
      if (commaToken.type === this.lexerClass.COMMA) {
        this.pos++;
        this.consumeNewLines();
        return [declaration].concat(this.parseDeclaration(typeString, isConst));
      } else {
        return [declaration];
      }
    }
  }, {
    key: 'consumeNewLines',
    value: function consumeNewLines() {
      var token = this.getToken();
      while (token.type === this.lexerClass.EOS && token.text.match('[\r\n]+')) {
        this.pos++;
        token = this.getToken();
      }
    }
  }, {
    key: 'isVariableType',
    value: function isVariableType(token) {
      return this.variableTypes.find(function (v) {
        return v === token.type;
      });
    }

    /*
    * Reads the next token of the stream to check if it is a Integer or an ID.
    * @returns Integer | ID
    **/

  }, {
    key: 'parseArrayDimension',
    value: function parseArrayDimension() {
      var dimToken = this.getToken();
      if (dimToken.type === this.lexerClass.INTEGER) {
        //parse as int literal
        this.pos++;
        return this.getIntLiteral(dimToken);
      } else if (dimToken.type === this.lexerClass.ID) {
        //parse as variable
        this.pos++;
        return this.parseVariable(dimToken);
      } else {
        throw _syntaxErrorFactory.SyntaxErrorFactory.invalid_array_dimension(this.lexer.literalNames[this.lexerClass.RK_INTEGER], dimToken);
      }
    }

    /*
    * Returns an object {type: 'int', value: value}.
    * It checks for binary and hexadecimal integers.
    * @returns object with fields type and value
    **/

  }, {
    key: 'getIntLiteral',
    value: function getIntLiteral(token) {
      var text = token.text;
      var sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(token);
      var exp = new Expressions.IntLiteral((0, _parsers.toInt)(text));
      exp.sourceInfo = sourceInfo;
      return exp;
    }
  }, {
    key: 'getRealLiteral',
    value: function getRealLiteral(token) {
      var sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(token);
      var exp = new Expressions.RealLiteral((0, _parsers.toReal)(token.text));
      exp.sourceInfo = sourceInfo;
      return exp;
    }
  }, {
    key: 'getStringLiteral',
    value: function getStringLiteral(token) {
      var text = token.text;
      var sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(token);
      var exp = new Expressions.StringLiteral((0, _parsers.toString)(text));
      exp.sourceInfo = sourceInfo;
      return exp;
    }
  }, {
    key: 'getBoolLiteral',
    value: function getBoolLiteral(token) {
      var val = (0, _parsers.toBool)(token.text);
      var exp = new Expressions.BoolLiteral(val);
      exp.sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(token);;
      return exp;
    }
  }, {
    key: 'parseArrayLiteral',
    value: function parseArrayLiteral() {
      this.checkOpenCurly();
      var beginArray = this.getToken();
      if (this.parsingArrayDimension >= 2) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_list('Array dimensions exceed maximum size of 2 at line ' + beginArray.line);
      }
      this.pos++;
      this.parsingArrayDimension++;
      this.consumeNewLines();
      var data = this.parseExpressionList();
      this.consumeNewLines();
      this.checkCloseCurly();
      var endArray = this.getToken();
      this.pos++;
      this.parsingArrayDimension--;
      if (this.parsingArrayDimension === 0) {
        // if (!data.isValid) {
        //   // TODO: better error message
        //   console.log('invalid array');
        //   throw new Error(`Invalid array at line ${beginArray.line}`);
        // }
      }
      var sourceInfo = _sourceInfo2.SourceInfo.createSourceInfoFromList(beginArray, endArray);
      var dataDim = 1;
      if (data[0] instanceof Expressions.ArrayLiteral) {
        dataDim++;
      }
      var type = new _compoundType.CompoundType(_types.Types.UNDEFINED, dataDim);
      var exp = new Expressions.ArrayLiteral(type, data);
      exp.sourceInfo = sourceInfo;
      return exp;
    }

    /*
    * Returns an object {type: 'variable', value: value}.
    * @returns object with fields type and value
    **/

  }, {
    key: 'parseVariable',
    value: function parseVariable(token) {
      var sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(token);
      var exp = new Expressions.VariableLiteral(token.text);
      exp.sourceInfo = sourceInfo;
      return exp;
    }

    /*
    * Returns an object representing a function. It has
    * four attributes: returnType, id, formalParams and block.
    * The block object has two attributes: declarations and commands
    **/

  }, {
    key: 'parseFunction',
    value: function parseFunction() {
      this.pushScope(IVProgParser.FUNCTION);
      var formalParams = [];
      var token = this.getToken();
      if (token.type !== this.lexerClass.RK_FUNCTION) {
        //throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.PR_FUNCAO], token);
        return null;
      }
      this.pos++;
      var funType = this.parseType();
      var dimensions = 0;
      if (this.checkOpenBrace(true)) {
        this.pos++;
        this.checkCloseBrace();
        this.pos++;
        dimensions++;
        if (this.checkOpenBrace(true)) {
          this.pos++;
          this.checkCloseBrace();
          this.pos++;
          dimensions++;
        }
      }
      var funcIDToken = this.getToken();
      var functionID = this.parseID();
      this.checkFunctionDuplicate(functionID, funcIDToken);
      this.checkOpenParenthesis();
      this.pos++;
      this.consumeNewLines();
      if (!this.checkCloseParenthesis(true)) {
        formalParams = this.parseFormalParameters(); // formal parameters 
        this.consumeNewLines();
        this.checkCloseParenthesis();
        this.pos++;
      } else {
        this.pos++;
      }
      this.consumeNewLines();
      var commandsBlock = this.parseCommandBlock();
      var returnType = funType;
      if (dimensions > 0) {
        returnType = new _compoundType.CompoundType(funType, dimensions);
      }
      var func = new Commands.Function(functionID, returnType, formalParams, commandsBlock);
      if (functionID === null && !func.isMain) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.invalid_main_return(_definedFunctions.LanguageDefinedFunction.getMainFunctionName(), this.lexer.literalNames[this.lexerClass.RK_VOID], token.line);
      } else if (func.isMain && formalParams.length !== 0) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.main_parameters();
      }
      this.popScope();
      return func;
    }

    /*
    * Parse the formal parameters of a function.
    * @returns a list of objects with the following attributes: type, id and dimensions.
    **/

  }, {
    key: 'parseFormalParameters',
    value: function parseFormalParameters() {
      var list = [];
      while (true) {
        var dimensions = 0;
        var typeString = this.parseType();
        var idToken = this.getToken();
        var idString = this.parseID();
        this.checkVariableDuplicate(idString, idToken);
        if (this.checkOpenBrace(true)) {
          this.pos++;
          dimensions++;
          this.checkCloseBrace();
          this.pos++;
          if (this.checkOpenBrace(true)) {
            this.pos++;
            dimensions++;
            this.checkCloseBrace();
            this.pos++;
          }
        }
        var type = null;
        if (dimensions > 0) {
          type = new _compoundType.CompoundType(typeString, dimensions);
        } else {
          type = typeString;
        }
        list.push(new Commands.FormalParameter(type, idString));
        var commaToken = this.getToken();
        if (commaToken.type !== this.lexerClass.COMMA) break;
        this.pos++;
        this.consumeNewLines();
      }
      return list;
    }
  }, {
    key: 'parseID',
    value: function parseID() {
      var token = this.getToken();
      if (token.type !== this.lexerClass.ID) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.id_missing(token);
      }
      this.pos++;
      if (this.insideScope(IVProgParser.FUNCTION)) {
        if (token.text === _definedFunctions.LanguageDefinedFunction.getMainFunctionName()) {
          return null;
        }
      }
      return token.text;
    }
  }, {
    key: 'parseMaybeLibID',
    value: function parseMaybeLibID() {
      var token = this.getToken();
      if (token.type !== this.lexerClass.ID && token.type !== this.lexerClass.LIB_ID) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.id_missing(token);
      }
      this.pos++;
      return token.text;
    }
  }, {
    key: 'parseType',
    value: function parseType() {
      var token = this.getToken();
      if (token.type === this.lexerClass.ID && this.insideScope(IVProgParser.FUNCTION)) {
        return _types.Types.VOID;
      } else if (token.type === this.lexerClass.RK_VOID && this.insideScope(IVProgParser.FUNCTION)) {
        this.pos++;
        return _types.Types.VOID;
      } else if (this.isVariableType(token)) {
        this.pos++;
        switch (token.type) {
          case this.lexerClass.RK_INTEGER:
            return _types.Types.INTEGER;
          case this.lexerClass.RK_BOOLEAN:
            return _types.Types.BOOLEAN;
          case this.lexerClass.RK_REAL:
            return _types.Types.REAL;
          case this.lexerClass.RK_STRING:
            return _types.Types.STRING;
          default:
            break;
        }
      }

      throw _syntaxErrorFactory.SyntaxErrorFactory.invalid_type(this.getTypeArray(), token);
    }
  }, {
    key: 'parseCommandBlock',
    value: function parseCommandBlock() {
      var optionalCurly = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var variablesDecl = [];
      var commands = [];
      var hasOpen = false;
      if (this.checkOpenCurly(optionalCurly)) {
        this.pos++;
        hasOpen = true;
      }
      this.consumeNewLines();
      while (true) {

        var cmd = this.parseCommand();
        if (cmd === null) break;
        if (cmd !== -1) {
          if (cmd instanceof Array) {
            variablesDecl = variablesDecl.concat(cmd);
          } else {
            commands.push(cmd);
          }
        }
      }
      this.consumeNewLines();
      if (hasOpen) {
        this.checkCloseCurly();
        this.pos++;
        this.consumeNewLines();
      }
      return new Commands.CommandBlock(variablesDecl, commands);
    }
  }, {
    key: 'parseCommand',
    value: function parseCommand() {
      var token = this.getToken();
      if (this.isVariableType(token)) {
        if (!this.insideScope(IVProgParser.FUNCTION)) {
          throw _syntaxErrorFactory.SyntaxErrorFactory.invalid_var_declaration(token.line);
        }
        this.pushScope(IVProgParser.BASE);
        var varType = this.parseType();
        this.popScope();
        var cmd = this.parseDeclaration(varType);
        this.checkEOS();
        this.pos++;
        return cmd;
      } else if (token.type === this.lexerClass.ID) {
        return this.parseIDCommand();
      } else if (token.type === this.lexerClass.LIB_ID) {
        return this.parseIDCommand();
      } else if (token.type === this.lexerClass.RK_RETURN) {
        return this.parseReturn();
      } else if (token.type === this.lexerClass.RK_WHILE) {
        return this.parseWhile();
      } else if (token.type === this.lexerClass.RK_FOR) {
        return this.parseFor();
      } else if (token.type === this.lexerClass.RK_BREAK) {
        if (!this.insideScope(IVProgParser.BREAKABLE)) {
          throw _syntaxErrorFactory.SyntaxErrorFactory.invalid_break_command(this.lexer.literalNames[this.lexerClass.RK_BREAK], token);
        }
        return this.parseBreak();
      } else if (token.type === this.lexerClass.RK_SWITCH) {
        return this.parseSwitchCase();
      } else if (token.type === this.lexerClass.RK_DO) {
        return this.parseDoWhile();
      } else if (token.type === this.lexerClass.RK_IF) {
        return this.parseIfThenElse();
      } else if (this.checkEOS(true)) {
        this.pos++;
        return -1;
      } else {
        return null;
      }
    }
  }, {
    key: 'parseSwitchCase',
    value: function parseSwitchCase() {
      this.pushScope(IVProgParser.BREAKABLE);
      this.pos++;
      this.checkOpenParenthesis();
      this.pos++;
      this.consumeNewLines();
      var exp = this.parseExpressionOR();
      this.consumeNewLines();
      this.checkCloseParenthesis();
      this.pos++;
      this.consumeNewLines();
      this.checkOpenCurly();
      this.pos++;
      this.consumeNewLines();
      var casesList = this.parseCases();
      this.consumeNewLines();
      this.checkCloseCurly();
      this.pos++;
      this.consumeNewLines();

      this.popScope();
      return new Commands.Switch(exp, casesList);
    }
  }, {
    key: 'parseDoWhile',
    value: function parseDoWhile() {
      this.pos++;
      this.consumeNewLines();
      this.pushScope(IVProgParser.BREAKABLE);
      var commandsBlock = this.parseCommandBlock();
      this.consumeNewLines(); //Maybe not...
      var whileToken = this.getToken();
      if (whileToken.type !== this.lexerClass.RK_WHILE) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_WHILE], whileToken);
      }
      this.pos++;
      this.checkOpenParenthesis();
      this.pos++;
      this.consumeNewLines();
      var condition = this.parseExpressionOR();
      this.consumeNewLines();
      this.checkCloseParenthesis();
      this.pos++;
      this.checkEOS();
      this.popScope();
      return new Commands.DoWhile(condition, commandsBlock);
    }
  }, {
    key: 'parseIfThenElse',
    value: function parseIfThenElse() {
      if (this.insideScope(IVProgParser.BREAKABLE)) {
        this.pushScope(IVProgParser.BREAKABLE);
      } else {
        this.pushScope(IVProgParser.COMMAND);
      }
      this.pos++;
      this.checkOpenParenthesis();
      this.pos++;
      this.consumeNewLines();
      var logicalExpression = this.parseExpressionOR();
      this.consumeNewLines();
      this.checkCloseParenthesis();
      this.pos++;
      this.consumeNewLines();
      var cmdBlocks = this.parseCommandBlock();

      var maybeElse = this.getToken();
      if (maybeElse.type === this.lexerClass.RK_ELSE) {
        this.pos++;
        this.consumeNewLines();
        var maybeIf = this.getToken();
        var elseBlock = null;
        if (this.checkOpenCurly(true)) {
          elseBlock = this.parseCommandBlock();
        } else if (maybeIf.type === this.lexerClass.RK_IF) {
          elseBlock = this.parseIfThenElse();
        } else {
          throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_list([this.lexer.literalNames[this.lexerClass.RK_IF], '{'], maybeIf);
        }
        return new Commands.IfThenElse(logicalExpression, cmdBlocks, elseBlock);
      }
      this.popScope();

      return new Commands.IfThenElse(logicalExpression, cmdBlocks, null);
    }
  }, {
    key: 'parseFor',
    value: function parseFor() {
      this.pushScope(IVProgParser.BREAKABLE);
      this.pos++;
      this.checkOpenParenthesis();
      this.pos++;
      this.consumeNewLines();
      var attribution = this.parseForAssign();
      this.consumeNewLines();
      var condition = this.parseExpressionOR();
      this.consumeForSemiColon();
      var increment = this.parseForAssign(true);
      this.checkCloseParenthesis();
      this.pos++;
      this.consumeNewLines();
      var commandsBlock = this.parseCommandBlock();
      this.popScope();
      return new Commands.For(attribution, condition, increment, commandsBlock);
    }
  }, {
    key: 'parseWhile',
    value: function parseWhile() {
      this.pushScope(IVProgParser.BREAKABLE);
      this.pos++;
      this.checkOpenParenthesis();
      this.pos++;
      this.consumeNewLines();
      var logicalExpression = this.parseExpressionOR();
      this.consumeNewLines();
      this.checkCloseParenthesis();
      this.pos++;
      this.consumeNewLines();
      var cmdBlocks = this.parseCommandBlock();
      this.popScope();
      return new Commands.While(logicalExpression, cmdBlocks);
    }
  }, {
    key: 'parseBreak',
    value: function parseBreak() {
      this.pos++;
      this.checkEOS();
      this.pos++;
      return new Commands.Break();
    }
  }, {
    key: 'parseReturn',
    value: function parseReturn() {
      this.pos++;
      var exp = null;
      if (!this.checkEOS(true)) {
        exp = this.parseExpressionOR();
        this.checkEOS();
      }
      this.pos++;
      return new Commands.Return(exp);
    }
  }, {
    key: 'parseIDCommand',
    value: function parseIDCommand() {
      var refToken = this.getToken();
      var isID = refToken.type === this.lexerClass.ID;
      var id = this.parseMaybeLibID();
      if (this.checkOpenBrace(true)) {
        this.pos++;
        var lineExpression = null;
        var columnExpression = null;
        this.consumeNewLines();
        lineExpression = this.parseExpression();
        this.consumeNewLines();
        this.checkCloseBrace();
        this.pos++;
        if (this.checkOpenBrace(true)) {
          this.pos++;
          this.consumeNewLines();
          columnExpression = this.parseExpression();
          this.consumeNewLines();
          this.checkCloseBrace();
          this.pos++;
        }
        var equalToken = this.getToken();
        if (equalToken.type !== this.lexerClass.EQUAL) {
          throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one('=', equalToken);
        }
        this.pos++;
        var exp = this.parseExpressionOR();
        this.checkEOS();
        this.pos++;
        var cmd = new Commands.ArrayIndexAssign(id, lineExpression, columnExpression, exp);
        cmd.sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(equalToken);
        return cmd;
      }
      var equalOrParenthesis = this.getToken();
      if (isID && equalOrParenthesis.type === this.lexerClass.EQUAL) {
        this.pos++;
        var _exp = this.parseExpressionOR();
        this.checkEOS();
        this.pos++;
        var _cmd = new Commands.Assign(id, _exp);
        _cmd.sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(equalOrParenthesis);
        return _cmd;
      } else if (equalOrParenthesis.type === this.lexerClass.OPEN_PARENTHESIS) {
        var funcCall = this.parseFunctionCallCommand(id);
        this.checkEOS();
        this.pos++;
        return funcCall;
      } else if (isID) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_list(['=', '('], equalOrParenthesis);
      } else {
        throw _syntaxErrorFactory.SyntaxErrorFactory.invalid_id_format(refToken);
      }
    }
  }, {
    key: 'parseForAssign',
    value: function parseForAssign() {
      var isLast = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (!isLast) this.consumeNewLines();
      if (this.checkEOS(true)) {
        return null;
      }
      var id = this.parseID();
      var equal = this.getToken();
      if (equal.type !== this.lexerClass.EQUAL) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one('=', equal);
      }
      this.pos++;
      var exp = this.parseExpressionOR();
      if (!isLast) {
        this.consumeForSemiColon();
      }
      var sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(equal);
      var cmd = new Commands.Assign(id, exp);
      cmd.sourceInfo = sourceInfo;
      return cmd;
    }
  }, {
    key: 'parseCases',
    value: function parseCases() {
      var token = this.getToken();
      if (token.type !== this.lexerClass.RK_CASE) {
        throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_CASE], token);
      }
      this.pos++;
      var nextToken = this.getToken();
      if (nextToken.type === this.lexerClass.RK_DEFAULT) {
        this.pos++;
        var colonToken = this.getToken();
        if (colonToken.type !== this.lexerClass.COLON) {
          throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one(':', colonToken);
        }
        this.pos++;
        this.consumeNewLines();
        var block = this.parseCommandBlock(true);
        var defaultCase = new Commands.Case(null);
        defaultCase.setCommands(block.commands);
        return [defaultCase];
      } else {
        var exp = this.parseExpressionOR();
        var _colonToken = this.getToken();
        if (_colonToken.type !== this.lexerClass.COLON) {
          throw _syntaxErrorFactory.SyntaxErrorFactory.token_missing_one(':', _colonToken);
        }
        this.pos++;
        this.consumeNewLines();
        var _block = this.parseCommandBlock(true);
        var aCase = new Commands.Case(exp);
        aCase.setCommands(_block.commands);
        var caseToken = this.getToken();
        if (caseToken.type === this.lexerClass.RK_CASE) {
          return [aCase].concat(this.parseCases());
        } else {
          return [aCase];
        }
      }
    }

    /*
    * Parses an Expression following the structure:
    *
    * EOR  => EAnd ( 'or' EOR)? #expression and
    *
    * EOR   => ENot ('and' EOR)? #expression or
    *
    * ENot  => 'not'? ER #expression not
    *
    * ER    => E ((>=, <=, ==, >, <) E)? #expression relational
    *
    * E     => factor ((+, -) E)? #expression
    *
    * factor=> term ((*, /, %) factor)?
    *
    * term  => literal || arrayAccess || FuncCall || ID || '('EAnd')'
    **/

  }, {
    key: 'parseExpressionOR',
    value: function parseExpressionOR() {
      var exp1 = this.parseExpressionAND();
      while (this.getToken().type === this.lexerClass.OR_OPERATOR) {
        var opToken = this.getToken();
        this.pos++;
        var or = (0, _operators.convertFromString)('or');
        this.consumeNewLines();
        var exp2 = this.parseExpressionAND();
        var _finalExp = new Expressions.InfixApp(or, exp1, exp2);
        _finalExp.sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(opToken);
        exp1 = _finalExp;
      }
      return exp1;
    }
  }, {
    key: 'parseExpressionAND',
    value: function parseExpressionAND() {
      var exp1 = this.parseExpressionNot();
      while (this.getToken().type === this.lexerClass.AND_OPERATOR) {
        var opToken = this.getToken();
        this.pos++;
        var and = (0, _operators.convertFromString)('and');
        this.consumeNewLines();
        var exp2 = this.parseExpressionNot();
        var _finalExp2 = new Expressions.InfixApp(and, exp1, exp2);
        _finalExp2.sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(opToken);
        exp1 = _finalExp2;
      }
      return exp1;
    }
  }, {
    key: 'parseExpressionNot',
    value: function parseExpressionNot() {
      var maybeNotToken = this.getToken();
      if (maybeNotToken.type === this.lexerClass.NOT_OPERATOR) {
        var opToken = this.getToken();
        this.pos++;
        var not = (0, _operators.convertFromString)('not');
        var exp1 = this.parseExpressionRel();
        finalExp = new Expressions.UnaryApp(not, exp1);
        finalExp.sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(opToken);
        return finalExp;
      } else {
        return this.parseExpressionRel();
      }
    }
  }, {
    key: 'parseExpressionRel',
    value: function parseExpressionRel() {
      var exp1 = this.parseExpression();
      while (this.getToken().type === this.lexerClass.RELATIONAL_OPERATOR) {
        var relToken = this.getToken();
        this.pos++;
        var rel = (0, _operators.convertFromString)(relToken.text);
        var exp2 = this.parseExpression();
        var _finalExp3 = new Expressions.InfixApp(rel, exp1, exp2);
        _finalExp3.sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(relToken);
        exp1 = _finalExp3;
      }
      return exp1;
    }
  }, {
    key: 'parseExpression',
    value: function parseExpression() {
      var factor = this.parseFactor();
      while (this.getToken().type === this.lexerClass.SUM_OP) {
        var sumOpToken = this.getToken();
        this.pos++;
        var op = (0, _operators.convertFromString)(sumOpToken.text);
        var factor2 = this.parseFactor();
        var _finalExp4 = new Expressions.InfixApp(op, factor, factor2);
        _finalExp4.sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(sumOpToken);
        factor = _finalExp4;
      }
      return factor;
    }
  }, {
    key: 'parseFactor',
    value: function parseFactor() {
      var term = this.parseTerm();
      while (this.getToken().type === this.lexerClass.MULTI_OP) {
        var multOpToken = this.getToken();
        this.pos++;
        var op = (0, _operators.convertFromString)(multOpToken.text);
        var term2 = this.parseTerm();
        var _finalExp5 = new Expressions.InfixApp(op, term, term2);
        _finalExp5.sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(multOpToken);
        term = _finalExp5;
      }
      return term;
    }
  }, {
    key: 'parseTerm',
    value: function parseTerm() {
      var token = this.getToken();
      var sourceInfo = null;
      switch (token.type) {
        case this.lexerClass.SUM_OP:
          this.pos++;
          sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(token);
          var exp = new Expressions.UnaryApp((0, _operators.convertFromString)(token.text), this.parseTerm());
          exp.sourceInfo = sourceInfo;
          return exp;
        case this.lexerClass.INTEGER:
          this.pos++;
          return this.getIntLiteral(token);
        case this.lexerClass.REAL:
          this.pos++;
          return this.getRealLiteral(token);
        case this.lexerClass.STRING:
          this.pos++;
          return this.getStringLiteral(token);
        case this.lexerClass.RK_TRUE:
        case this.lexerClass.RK_FALSE:
          this.pos++;
          return this.getBoolLiteral(token);
        case this.lexerClass.OPEN_CURLY:
          return this.parseArrayLiteral();
        case this.lexerClass.ID:
        case this.lexerClass.LIB_ID:
          return this.parseIDTerm();
        case this.lexerClass.OPEN_PARENTHESIS:
          return this.parseParenthesisExp();
        default:
          throw _syntaxErrorFactory.SyntaxErrorFactory.invalid_terminal(token);
      }
    }
  }, {
    key: 'parseIDTerm',
    value: function parseIDTerm() {
      var tokenA = this.getToken();
      var id = this.parseMaybeLibID();
      var isID = tokenA.type === this.lexerClass.ID;
      if (isID && this.checkOpenBrace(true)) {
        var tokenB = null;
        this.pos++;
        var firstIndex = this.parseExpression();
        var secondIndex = null;
        this.consumeNewLines();
        this.checkCloseBrace();
        tokenB = this.getToken();
        this.pos++;
        if (this.checkOpenBrace(true)) {
          this.pos++;
          secondIndex = this.parseExpression();
          this.consumeNewLines();
          this.checkCloseBrace();
          tokenB = this.getToken();
          this.pos++;
        }
        var sourceInfo = _sourceInfo2.SourceInfo.createSourceInfoFromList(tokenA, tokenB);
        var exp = new Expressions.ArrayAccess(id, firstIndex, secondIndex);
        exp.sourceInfo = sourceInfo;
        return exp;
      } else if (this.checkOpenParenthesis(true)) {
        return this.parseFunctionCallExpression(id);
      } else if (isID) {
        var _sourceInfo = _sourceInfo2.SourceInfo.createSourceInfo(tokenA);
        var _exp2 = new Expressions.VariableLiteral(id);
        _exp2.sourceInfo = _sourceInfo;
        return _exp2;
      } else {
        throw _syntaxErrorFactory.SyntaxErrorFactory.invalid_id_format(tokenA);
      }
    }
  }, {
    key: 'getFunctionName',
    value: function getFunctionName(id) {
      var name = _definedFunctions.LanguageDefinedFunction.getInternalName(id);
      if (name === null) {
        if (id === _definedFunctions.LanguageDefinedFunction.getMainFunctionName()) {
          return null;
        }
        return id;
      } else {
        return name;
      }
    }
  }, {
    key: 'parseFunctionCallExpression',
    value: function parseFunctionCallExpression(id) {
      var tokenA = this.getToken(this.pos - 1);
      var actualParameters = this.parseActualParameters();
      var tokenB = this.getToken(this.pos - 1);
      var funcName = this.getFunctionName(id);
      var sourceInfo = _sourceInfo2.SourceInfo.createSourceInfoFromList(tokenA, tokenB);
      var cmd = new Expressions.FunctionCall(funcName, actualParameters);
      cmd.sourceInfo = sourceInfo;
      return cmd;
    }
  }, {
    key: 'parseFunctionCallCommand',
    value: function parseFunctionCallCommand(id) {
      return this.parseFunctionCallExpression(id);
    }
  }, {
    key: 'parseParenthesisExp',
    value: function parseParenthesisExp() {
      this.checkOpenParenthesis();
      var tokenA = this.getToken();
      this.pos++;
      this.consumeNewLines();
      var exp = this.parseExpressionOR();
      this.consumeNewLines();
      this.checkCloseParenthesis();
      var tokenB = this.getToken();
      var sourceInfo = _sourceInfo2.SourceInfo.createSourceInfoFromList(tokenA, tokenB);
      this.pos++;
      exp.sourceInfo = sourceInfo;
      return exp;
    }
  }, {
    key: 'parseActualParameters',
    value: function parseActualParameters() {
      this.checkOpenParenthesis();
      this.pos++;
      if (this.checkCloseParenthesis(true)) {
        this.pos++;
        return [];
      }
      this.consumeNewLines();
      var list = this.parseExpressionList();
      this.consumeNewLines();
      this.checkCloseParenthesis();
      this.pos++;
      return list;
    }
  }, {
    key: 'parseExpressionList',
    value: function parseExpressionList() {
      var list = [];
      while (true) {
        var exp = this.parseExpressionOR();
        list.push(exp);
        var maybeToken = this.getToken();
        if (maybeToken.type !== this.lexerClass.COMMA) {
          break;
        } else {
          this.pos++;
          this.consumeNewLines();
        }
      }
      return list;
    }
  }, {
    key: 'getTypeArray',
    value: function getTypeArray() {
      var _this = this;

      var types = this.insideScope(IVProgParser.FUNCTION) ? this.functionTypes : this.variableTypes;
      return types.map(function (x) {
        return _this.lexer.literalNames[x];
      });
    }
  }]);

  return IVProgParser;
}();

/***/ }),

/***/ "./js/ast/operators.js":
/*!*****************************!*\
  !*** ./js/ast/operators.js ***!
  \*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.convertFromString = convertFromString;
var Operators = exports.Operators = Object.freeze({
  ADD: { ord: 0, value: "+" },
  SUB: { ord: 1, value: "-" },
  MULT: { ord: 2, value: '*' },
  DIV: { ord: 3, value: '/' },
  MOD: { ord: 4, value: '%' },
  GT: { ord: 5, value: '>' },
  GE: { ord: 6, value: '>=' },
  LT: { ord: 7, value: '<' },
  LE: { ord: 8, value: '<=' },
  EQ: { ord: 9, value: '==' },
  NEQ: { ord: 10, value: '!=' },
  AND: { ord: 11, value: 'and' },
  OR: { ord: 12, value: 'or' },
  NOT: { ord: 13, value: 'not' }
});

function convertFromString(op) {
  switch (op) {
    case '+':
      return Operators.ADD;
    case '-':
      return Operators.SUB;
    case '*':
      return Operators.MULT;
    case '/':
      return Operators.DIV;
    case '%':
      return Operators.MOD;
    case '>':
      return Operators.GT;
    case '>=':
      return Operators.GE;
    case '<':
      return Operators.LT;
    case '<=':
      return Operators.LE;
    case '==':
      return Operators.EQ;
    case '!=':
      return Operators.NEQ;
    case 'and':
      return Operators.AND;
    case 'or':
      return Operators.OR;
    case 'not':
      return Operators.NOT;
  }
}

/***/ }),

/***/ "./js/ast/sourceInfo.js":
/*!******************************!*\
  !*** ./js/ast/sourceInfo.js ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var SourceInfo = exports.SourceInfo = function () {
  _createClass(SourceInfo, null, [{
    key: "createSourceInfo",
    value: function createSourceInfo(token) {
      return new SourceInfo(token.line, token.column, token.text.length);
    }
  }, {
    key: "createSourceInfoFromList",
    value: function createSourceInfoFromList(tokenA, tokenB) {
      var line = tokenA.line;
      var column = tokenA.column;
      // copied from https://github.com/UNIVALI-LITE/Portugol-Studio/blob/master/core/src/main/java/br/univali/portugol/nucleo/analise/sintatica/Portugol.g
      // No idea why...
      var size = tokenB.tokenIndex + 1 - tokenA.tokenIndex;
      return new SourceInfo(line, column, size);
    }
  }]);

  function SourceInfo(line, column, size) {
    _classCallCheck(this, SourceInfo);

    this.line = line;
    this.column = column;
    this.size = size;
  }

  return SourceInfo;
}();

/***/ }),

/***/ "./js/io/domConsole.js":
/*!*****************************!*\
  !*** ./js/io/domConsole.js ***!
  \*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DOMConsole = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var DOMConsole = exports.DOMConsole = function () {
  _createClass(DOMConsole, null, [{
    key: 'USER',
    get: function get() {
      return 0;
    }
  }, {
    key: 'INFO',
    get: function get() {
      return 1;
    }
  }, {
    key: 'ERR',
    get: function get() {
      return 2;
    }
  }]);

  function DOMConsole(elementID) {
    _classCallCheck(this, DOMConsole);

    this.input = null;
    this.needInput = false;
    this.termDiv = null;
    this.anyKey = false;
    this.parent = (0, _jquery2.default)(elementID);
    this.setup();
    this.inputListeners = [];
  }

  _createClass(DOMConsole, [{
    key: 'setup',
    value: function setup() {
      this._setupDom();
      this._setupEvents();
    }
  }, {
    key: '_setupEvents',
    value: function _setupEvents() {
      var _this = this;

      this.input.on("keydown", function (event) {
        if (!_this.needInput) {
          event.preventDefault();
          return;
        }
        var keyCode = event.which;
        if (keyCode === 13 || _this.anyKey) {
          var text = _this.input.val();
          text = text.replace('[\n\r]+', '');
          _this.notifyListeners(text);
          _this.write(text);
          _this.input.val("");
        }
      });
    }
  }, {
    key: '_setupDom',
    value: function _setupDom() {
      this.termDiv = (0, _jquery2.default)("<div></div>");
      this.termDiv.addClass("ivprog-term-div");
      this.input = (0, _jquery2.default)('<input text="type">');
      this.input.addClass("ivprog-term-input");
      this.termDiv.append(this.input);
      this.parent.append(this.termDiv);
    }
  }, {
    key: 'notifyListeners',
    value: function notifyListeners(text) {
      this.inputListeners.forEach(function (resolve) {
        return resolve(text);
      });
      this.inputListeners.splice(0, this.inputListeners.length);
      this.hideInput();
      this.anyKey = false;
    }
  }, {
    key: 'write',
    value: function write(text) {
      this._appendText(text, DOMConsole.USER);
    }
  }, {
    key: 'info',
    value: function info(text) {
      this._appendText(text, DOMConsole.INFO);
    }
  }, {
    key: 'err',
    value: function err(text) {
      this._appendText(text, DOMConsole.ERR);
    }
  }, {
    key: '_appendText',
    value: function _appendText(text, type) {
      var divClass = this.getClassForType(type);
      var textDiv = (0, _jquery2.default)("<div></div>");
      textDiv.addClass(divClass);
      textDiv.append(text);
      textDiv.insertBefore(this.input);
      this.scrollTerm();
    }
  }, {
    key: 'scrollTerm',
    value: function scrollTerm() {
      this.termDiv.animate({
        scrollTop: this.termDiv.prop('scrollHeight')
      }, 0);
    }
  }, {
    key: 'getClassForType',
    value: function getClassForType(type) {
      switch (type) {
        case DOMConsole.USER:
          return "ivprog-term-userText";
        case DOMConsole.INFO:
          return "ivprog-term-info";
        case DOMConsole.ERR:
          return "ivprog-term-error";
      }
    }
  }, {
    key: 'dispose',
    value: function dispose() {
      this.parent.off();
      this.input.off();
      this.input = null;
      this.parent.empty();
    }
  }, {
    key: 'showInput',
    value: function showInput() {
      this.needInput = true;
      this.input.show();
      this.input.focus();
    }
  }, {
    key: 'hideInput',
    value: function hideInput() {
      this.needInput = false;
      this.input.hide();
    }
  }, {
    key: 'requestInput',
    value: function requestInput(callback) {
      var anyKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

      this.inputListeners.push(callback);
      this.anyKey = anyKey;
      this.showInput();
    }
  }, {
    key: 'sendOutput',
    value: function sendOutput(text) {
      var _this2 = this;

      text.split("\n").forEach(function (t) {
        t = t.replace(/\t/g, '&#9;');
        _this2.write(t);
      });
    }
  }, {
    key: 'clear',
    value: function clear() {
      this.input.parent().children().not(this.input).remove();
      this.input.val("");
    }
  }]);

  return DOMConsole;
}();

/***/ }),

/***/ "./js/io/input.js":
/*!************************!*\
  !*** ./js/io/input.js ***!
  \************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Input = exports.Input = function () {
  function Input() {
    _classCallCheck(this, Input);
  }

  _createClass(Input, [{
    key: "requestInput",
    value: function requestInput(callback) {
      throw new Error("Must be implemented");
    }
  }]);

  return Input;
}();

/***/ }),

/***/ "./js/io/output.js":
/*!*************************!*\
  !*** ./js/io/output.js ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Output = exports.Output = function () {
  function Output() {
    _classCallCheck(this, Output);
  }

  _createClass(Output, [{
    key: "sendOutput",
    value: function sendOutput(text) {
      throw new Error("Must be implemented");
    }
  }]);

  return Output;
}();

/***/ }),

/***/ "./js/main.js":
/*!********************!*\
  !*** ./js/main.js ***!
  \********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.i18n = exports.LocalizedStrings = exports.initVisualUI = exports.runner = undefined;

var _runner = __webpack_require__(/*! ./runner */ "./js/runner.js");

var _functions = __webpack_require__(/*! ./visualUI/functions */ "./js/visualUI/functions.js");

var _localizedStringsService = __webpack_require__(/*! ./services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _i18nHelper = __webpack_require__(/*! ./services/i18nHelper */ "./js/services/i18nHelper.js");

var i18n = _i18nHelper.i18nHelper.i18n;

exports.runner = _runner.runner;
exports.initVisualUI = _functions.initVisualUI;
exports.LocalizedStrings = _localizedStringsService.LocalizedStrings;
exports.i18n = i18n;

/***/ }),

/***/ "./js/processor/compatibilityTable.js":
/*!********************************************!*\
  !*** ./js/processor/compatibilityTable.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.resultTypeAfterInfixOp = resultTypeAfterInfixOp;
exports.resultTypeAfterUnaryOp = resultTypeAfterUnaryOp;

var _types = __webpack_require__(/*! ./../typeSystem/types */ "./js/typeSystem/types.js");

var _operators = __webpack_require__(/*! ./../ast/operators */ "./js/ast/operators.js");

var _multiType = __webpack_require__(/*! ../typeSystem/multiType */ "./js/typeSystem/multiType.js");

var _config = __webpack_require__(/*! ../util/config */ "./js/util/config.js");

function buildInfixAddTable() {
  var table = [[], [], [], []];

  table[_types.Types.INTEGER.ord][_types.Types.INTEGER.ord] = _types.Types.INTEGER;
  table[_types.Types.INTEGER.ord][_types.Types.REAL.ord] = _types.Types.REAL;
  table[_types.Types.INTEGER.ord][_types.Types.STRING.ord] = _types.Types.STRING;

  table[_types.Types.REAL.ord][_types.Types.INTEGER.ord] = _types.Types.REAL;
  table[_types.Types.REAL.ord][_types.Types.REAL.ord] = _types.Types.REAL;
  table[_types.Types.REAL.ord][_types.Types.STRING.ord] = _types.Types.STRING;

  table[_types.Types.STRING.ord][_types.Types.INTEGER.ord] = _types.Types.STRING;
  table[_types.Types.STRING.ord][_types.Types.REAL.ord] = _types.Types.STRING;
  table[_types.Types.STRING.ord][_types.Types.STRING.ord] = _types.Types.STRING;
  table[_types.Types.STRING.ord][_types.Types.BOOLEAN.ord] = _types.Types.STRING;

  return table;
}

function buildInfixMultiDivSubTable() {
  var table = [[], [], [], []];

  table[_types.Types.INTEGER.ord][_types.Types.INTEGER.ord] = _types.Types.INTEGER;
  table[_types.Types.INTEGER.ord][_types.Types.REAL.ord] = _types.Types.REAL;

  table[_types.Types.REAL.ord][_types.Types.INTEGER.ord] = _types.Types.REAL;
  table[_types.Types.REAL.ord][_types.Types.REAL.ord] = _types.Types.REAL;

  return table;
}

function buildInfixEqualityInequalityTable() {
  var table = [[], [], [], []];

  table[_types.Types.INTEGER.ord][_types.Types.INTEGER.ord] = _types.Types.BOOLEAN;

  table[_types.Types.REAL.ord][_types.Types.REAL.ord] = _types.Types.BOOLEAN;

  table[_types.Types.BOOLEAN.ord][_types.Types.BOOLEAN.ord] = _types.Types.BOOLEAN;

  table[_types.Types.STRING.ord][_types.Types.STRING.ord] = _types.Types.BOOLEAN;

  return table;
}

function buildInfixRelationalTable() {
  var table = [[], [], [], []];

  table[_types.Types.INTEGER.ord][_types.Types.INTEGER.ord] = _types.Types.BOOLEAN;

  table[_types.Types.REAL.ord][_types.Types.REAL.ord] = _types.Types.BOOLEAN;

  table[_types.Types.STRING.ord][_types.Types.STRING.ord] = _types.Types.BOOLEAN;

  return table;
}

function buildInfixAndOrTable() {
  var table = [[], [], [], []];

  table[_types.Types.BOOLEAN.ord][_types.Types.BOOLEAN.ord] = _types.Types.BOOLEAN;

  return table;
}

function buildInfixModTable() {
  var table = [[], [], [], []];

  table[_types.Types.INTEGER.ord][_types.Types.INTEGER.ord] = _types.Types.INTEGER;

  return table;
}

function buildUnarySumSubList() {
  var list = [];

  list[_types.Types.INTEGER.ord] = _types.Types.INTEGER;

  list[_types.Types.REAL.ord] = _types.Types.REAL;

  return list;
}

function buildUnaryNegList() {
  var list = [];

  list[_types.Types.BOOLEAN.ord] = _types.Types.BOOLEAN;

  return list;
}

function buildInfixCompatibilityTable() {
  var compatibilityMap = new WeakMap();
  compatibilityMap.set(_operators.Operators.ADD, buildInfixAddTable());
  compatibilityMap.set(_operators.Operators.SUB, buildInfixMultiDivSubTable());
  compatibilityMap.set(_operators.Operators.MULT, buildInfixMultiDivSubTable());
  compatibilityMap.set(_operators.Operators.DIV, buildInfixMultiDivSubTable());
  compatibilityMap.set(_operators.Operators.EQ, buildInfixEqualityInequalityTable());
  compatibilityMap.set(_operators.Operators.NEQ, buildInfixEqualityInequalityTable());
  compatibilityMap.set(_operators.Operators.GE, buildInfixRelationalTable());
  compatibilityMap.set(_operators.Operators.GT, buildInfixRelationalTable());
  compatibilityMap.set(_operators.Operators.LE, buildInfixRelationalTable());
  compatibilityMap.set(_operators.Operators.LT, buildInfixRelationalTable());
  compatibilityMap.set(_operators.Operators.OR, buildInfixAndOrTable());
  compatibilityMap.set(_operators.Operators.AND, buildInfixAndOrTable());
  compatibilityMap.set(_operators.Operators.MOD, buildInfixModTable());
  return compatibilityMap;
}

function buildUnaryCompatibilityTable() {
  var compatibilityMap = new WeakMap();
  compatibilityMap.set(_operators.Operators.ADD, buildUnarySumSubList());
  compatibilityMap.set(_operators.Operators.SUB, buildUnarySumSubList());
  compatibilityMap.set(_operators.Operators.NOT, buildUnaryNegList());
  return compatibilityMap;
}

var infixMap = buildInfixCompatibilityTable();
var unaryMap = buildUnaryCompatibilityTable();

function resultTypeAfterInfixOp(operator, leftExpressionType, rightExpressionType) {
  try {
    if (leftExpressionType instanceof _multiType.MultiType && rightExpressionType instanceof _multiType.MultiType) {
      var newMulti = [];
      for (var i = 0; i < leftExpressionType.types.length; i++) {
        var element = leftExpressionType.types[i];
        if (rightExpressionType.types.indexOf(element) !== -1) {
          newMulti.push(element);
        }
      }
      if (newMulti.length <= 0) {
        if (_config.Config.enable_type_casting) {
          if (leftExpressionType.isCompatible(_types.Types.INTEGER) || leftExpressionType.isCompatible(_types.Types.REAL)) {
            if (rightExpressionType.isCompatible(_types.Types.INTEGER) || rightExpressionType.isCompatible(_types.Types.REAL)) {
              return new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]);
            }
          }
        }
        return _types.Types.UNDEFINED;
      } else {
        return new _multiType.MultiType(newMulti);
      }
    } else if (leftExpressionType instanceof _multiType.MultiType) {
      if (leftExpressionType.isCompatible(rightExpressionType)) {
        return rightExpressionType;
      } else {
        if (_config.Config.enable_type_casting) {
          if (leftExpressionType.isCompatible(_types.Types.INTEGER) || leftExpressionType.isCompatible(_types.Types.REAL)) {
            if (rightExpressionType.isCompatible(_types.Types.INTEGER) || rightExpressionType.isCompatible(_types.Types.REAL)) {
              return rightExpressionType;
            }
          }
        }
        return _types.Types.UNDEFINED;
      }
    } else if (rightExpressionType instanceof _multiType.MultiType) {
      if (rightExpressionType.isCompatible(leftExpressionType)) {
        return leftExpressionType;
      } else {
        if (_config.Config.enable_type_casting) {
          if (leftExpressionType.isCompatible(_types.Types.INTEGER) || leftExpressionType.isCompatible(_types.Types.REAL)) {
            if (rightExpressionType.isCompatible(_types.Types.INTEGER) || rightExpressionType.isCompatible(_types.Types.REAL)) {
              return leftExpressionType;
            }
          }
        }
        return _types.Types.UNDEFINED;
      }
    }
    var resultType = infixMap.get(operator)[leftExpressionType.ord][rightExpressionType.ord];
    if (resultType === null || resultType === undefined) {
      if (_config.Config.enable_type_casting) {
        if (leftExpressionType.isCompatible(_types.Types.INTEGER) || leftExpressionType.isCompatible(_types.Types.REAL)) {
          if (rightExpressionType.isCompatible(_types.Types.INTEGER) || rightExpressionType.isCompatible(_types.Types.REAL)) {
            if (operator === _operators.Operators.MOD) {
              return _types.Types.INTEGER;
            } else if (operator.ord >= 5 && operator.ord <= 10) {
              return _types.Types.BOOLEAN;
            }
          }
        }
      }
      return _types.Types.UNDEFINED;
    }
    return resultType;
  } catch (e) {
    if (e instanceof TypeError) {
      return _types.Types.UNDEFINED;
    } else {
      throw e;
    }
  }
}

function resultTypeAfterUnaryOp(operator, leftExpressionType) {
  try {
    if (leftExpressionType instanceof _multiType.MultiType) {
      return leftExpressionType;
    }
    return unaryMap.get(operator)[leftExpressionType.ord];
  } catch (e) {
    if (e instanceof TypeError) {
      return _types.Types.UNDEFINED;
    } else {
      throw e;
    }
  }
}

/***/ }),

/***/ "./js/processor/context.js":
/*!*********************************!*\
  !*** ./js/processor/context.js ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var Context = exports.Context = Object.freeze({
  BASE: Symbol('context:base'),
  BREAKABLE: Symbol('context:breakable'),
  FUNCTION: Symbol('context:function')
});

/***/ }),

/***/ "./js/processor/definedFunctions.js":
/*!******************************************!*\
  !*** ./js/processor/definedFunctions.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LanguageDefinedFunction = undefined;

var _languageService = __webpack_require__(/*! ../services/languageService */ "./js/services/languageService.js");

var _io = __webpack_require__(/*! ./lib/io */ "./js/processor/lib/io.js");

var _strings = __webpack_require__(/*! ./lib/strings */ "./js/processor/lib/strings.js");

var _arrays = __webpack_require__(/*! ./lib/arrays */ "./js/processor/lib/arrays.js");

var _lang = __webpack_require__(/*! ./lib/lang */ "./js/processor/lib/lang.js");

var _math = __webpack_require__(/*! ./lib/math */ "./js/processor/lib/math.js");

function valueToKey(value, object) {
  for (var key in object) {
    if (object.hasOwnProperty(key)) {
      if (object[key] === value) {
        return key;
      }
    }
  }
  return null;
}

function concatObjects() {
  var result = {};

  for (var _len = arguments.length, objs = Array(_len), _key = 0; _key < _len; _key++) {
    objs[_key] = arguments[_key];
  }

  for (var i = 0; i < objs.length; i++) {
    var obj = objs[i];
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        result[key] = obj[key];
      }
    }
  }
  return result;
}

var libsObject = {
  $mathLib: {
    $sin: (0, _math.createSinFun)(),
    $cos: (0, _math.createCosFun)(),
    $tan: (0, _math.createTanFun)(),
    $sqrt: (0, _math.createSqrtFun)(),
    $pow: (0, _math.createPowFun)(),
    $log: (0, _math.createLogFun)(),
    $abs: (0, _math.createAbsFun)(),
    $negate: (0, _math.createNegateFun)(),
    $invert: (0, _math.createInvertFun)(),
    $max: (0, _math.createMaxFun)(),
    $min: (0, _math.createMinFun)()
  },
  $ioLib: {
    $read: (0, _io.createInputFun)(),
    $write: (0, _io.createOutputFun)()
  },
  $strLib: {
    $substring: (0, _strings.createSubstringFun)(),
    $length: (0, _strings.createLengthFun)(),
    $uppercase: (0, _strings.createUppercaseFun)(),
    $lowercase: (0, _strings.createLowercaseFun)(),
    $charAt: (0, _strings.createrCharAtFun)()
  },
  $arrayLib: {
    $numElements: (0, _arrays.createNumElementsFun)(),
    $matrixLines: (0, _arrays.createMatrixLinesFun)(),
    $matrixColumns: (0, _arrays.createMatrixColumnsFun)()
  },
  $langLib: {
    $isReal: (0, _lang.createIsRealFun)(),
    $isInt: (0, _lang.createIsIntFun)(),
    $isBool: (0, _lang.createIsBoolFun)(),
    $castReal: (0, _lang.createCastRealFun)(),
    $castInt: (0, _lang.createCastIntFun)(),
    $castBool: (0, _lang.createCastBoolFun)(),
    $castString: (0, _lang.createCastStringFun)()
  }
};

var funcsObject = concatObjects(libsObject.$ioLib, libsObject.$langLib, libsObject.$strLib, libsObject.$arrayLib);

var LanguageDefinedFunction = exports.LanguageDefinedFunction = Object.freeze({
  getMainFunctionName: function getMainFunctionName() {
    return _languageService.LanguageService.getCurrentLangFuncs().main_function;
  },
  getInternalName: function getInternalName(localName) {
    if (localName.indexOf(".") !== -1) {
      var names = localName.split(".");
      var lib = valueToKey(names[0], _languageService.LanguageService.getCurrentLangLibs());
      var internalName = valueToKey(names[1], _languageService.LanguageService.getCurrentLangFuncs());
      if (lib === null || internalName === null) {
        return null;
      }
      return lib + "." + internalName;
    }
    var funcName = valueToKey(localName, _languageService.LanguageService.getCurrentLangFuncs());
    if (funcName !== null) {
      if (funcsObject[funcName]) {
        return funcName;
      }
    }
    return null;
  },
  getFunction: function getFunction(internalName) {
    if (internalName.indexOf(".") !== -1) {
      var names = internalName.split(".");
      var libName = names[0];
      var funName = names[1];
      return libsObject[libName][funName];
    }
    return funcsObject[internalName];
  },
  getLocalName: function getLocalName(internalName) {
    if (internalName.indexOf(".") !== -1) {
      var names = internalName.split(".");
      var libName = _languageService.LanguageService.getCurrentLangLibs()[names[0]];
      var funName = _languageService.LanguageService.getCurrentLangFuncs()[names[1]];
      return libName + '.' + funName;
    } else if (_languageService.LanguageService.getCurrentLangFuncs()[internalName]) {
      return _languageService.LanguageService.getCurrentLangFuncs()[internalName];
    } else {
      return internalName;
    }
  }
});

/***/ }),

/***/ "./js/processor/error/processorErrorFactory.js":
/*!*****************************************************!*\
  !*** ./js/processor/error/processorErrorFactory.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ProcessorErrorFactory = undefined;

var _runtimeError = __webpack_require__(/*! ./runtimeError */ "./js/processor/error/runtimeError.js");

var _semanticError = __webpack_require__(/*! ./semanticError */ "./js/processor/error/semanticError.js");

var _localizedStringsService = __webpack_require__(/*! ./../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _operators = __webpack_require__(/*! ../../ast/operators */ "./js/ast/operators.js");

function translateType(type, dim) {
  switch (dim) {
    case 0:
      return _localizedStringsService.LocalizedStrings.getUI(type);
    default:
      var transType = _localizedStringsService.LocalizedStrings.getUI(type);
      if (dim === 1) return _localizedStringsService.LocalizedStrings.getUI("vector_string", [transType]);else return _localizedStringsService.LocalizedStrings.getUI("matrix_string", [transType]);
  }
}

function translateOp(op) {
  switch (op.ord) {
    case _operators.Operators.AND.ord:
    case _operators.Operators.OR.ord:
    case _operators.Operators.NOT.ord:
      return _localizedStringsService.LocalizedStrings.getUI(op.value);
    default:
      return op.value;
  }
}

var ProcessorErrorFactory = exports.ProcessorErrorFactory = Object.freeze({
  symbol_not_found_full: function symbol_not_found_full(id, sourceInfo) {
    if (sourceInfo) {
      var context = [id, sourceInfo.line, sourceInfo.column];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("symbol_not_found_full", context));
    } else {
      return ProcessorErrorFactory.symbol_not_found(id);
    }
  },
  symbol_not_found: function symbol_not_found(id) {
    var context = [id];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("symbol_not_found", context));
  },
  function_missing_full: function function_missing_full(id, sourceInfo) {
    if (sourceInfo) {
      var context = [id, sourceInfo.line, sourceInfo.column];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("function_missing_full", context));
    } else {
      return ProcessorErrorFactory.function_missing(id);
    }
  },
  function_missing: function function_missing(id) {
    var context = [id];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("function_missing", context));
  },
  main_missing: function main_missing() {
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("main_missing"));
  }, // TODO: better urgent error message
  array_dimension_not_int_full: function array_dimension_not_int_full(sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("array_dimension_not_int_full", context));
    } else {
      return ProcessorErrorFactory.array_dimension_not_int();
    }
  },
  array_dimension_not_int: function array_dimension_not_int() {
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("array_dimension_not_int"));
  },
  unknown_command_full: function unknown_command_full(sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("unknown_command_full", context));
    } else {
      return ProcessorErrorFactory.unknown_command();
    }
  },
  unknown_command: function unknown_command() {
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("unknown_command"));
  },
  incompatible_types_full: function incompatible_types_full(type, dim, sourceInfo) {
    if (sourceInfo) {
      var context = [translateType(type, dim), sourceInfo.line, sourceInfo.column];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("incompatible_types_full", context));
    } else {
      return ProcessorErrorFactory.incompatible_types(type, dim);
    }
  },
  incompatible_types: function incompatible_types(type, dim) {
    var context = [translateType(type, dim)];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("incompatible_types", context));
  },
  incompatible_types_array_full: function incompatible_types_array_full(exp, type, dim, sourceInfo) {
    if (sourceInfo) {
      var context = [exp, translateType(type, dim), sourceInfo.line, sourceInfo.column];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("incompatible_types_array_full", context));
    } else {
      return ProcessorErrorFactory.incompatible_types_array(exp, type, dim);
    }
  },
  incompatible_types_array: function incompatible_types_array(exp, type, dim) {
    var context = [exp, translateType(type, dim)];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("incompatible_types_array", context));
  },
  loop_condition_type_full: function loop_condition_type_full(sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, sourceInfo.column];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("loop_condition_type_full", context));
    } else {
      return ProcessorErrorFactory.loop_condition_type();
    }
  },
  loop_condition_type: function loop_condition_type() {
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("loop_condition_type"));
  },
  endless_loop_full: function endless_loop_full(sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("endless_loop_full", context));
    } else {
      return ProcessorErrorFactory.endless_loop();
    }
  },
  endless_loop: function endless_loop() {
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("endless_loop"));
  },
  for_condition_type_full: function for_condition_type_full(sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, sourceInfo.column];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("for_condition_type_full", context));
    } else {
      return ProcessorErrorFactory.for_condition_type();
    }
  },
  for_condition_type: function for_condition_type() {
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("for_condition_type"));
  },
  if_condition_type_full: function if_condition_type_full(sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, sourceInfo.column];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("if_condition_type_full", context));
    } else {
      return ProcessorErrorFactory.if_condition_type();
    }
  },
  if_condition_type: function if_condition_type() {
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("if_condition_type"));
  },
  invalid_global_var: function invalid_global_var() {
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_global_var"));
  },
  not_implemented: function not_implemented(id) {
    var context = [id];
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("not_implemented", context));
  },
  invalid_case_type_full: function invalid_case_type_full(exp, type, dim, sourceInfo) {
    if (sourceInfo) {
      var context = [exp, translateType(type, dim), sourceInfo.line, sourceInfo.column];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_case_type_full", context));
    } else {
      return ProcessorErrorFactory.invalid_case_type(exp, type, dim);
    }
  },
  invalid_case_type: function invalid_case_type(exp, type, dim) {
    var context = [exp, translateType(type, dim)];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_case_type", context));
  },
  void_in_expression_full: function void_in_expression_full(id, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, sourceInfo.column, id];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("void_in_expression_full", context));
    } else {
      return ProcessorErrorFactory.void_in_expression(id);
    }
  },
  void_in_expression: function void_in_expression(id) {
    var context = [id];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("void_in_expression", context));
  },
  invalid_array_access_full: function invalid_array_access_full(id, sourceInfo) {
    if (sourceInfo) {
      var context = [id, sourceInfo.line, sourceInfo.column];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_array_access_full", context));
    } else {
      return ProcessorErrorFactory.invalid_array_access(id);
    }
  },
  invalid_array_access: function invalid_array_access(id) {
    var context = [id];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_array_access", context));
  },
  invalid_matrix_access_full: function invalid_matrix_access_full(id, sourceInfo) {
    if (sourceInfo) {
      var context = [id, sourceInfo.line, sourceInfo.column];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_matrix_access_full", context));
    } else {
      return ProcessorErrorFactory.invalid_matrix_access(id);
    }
  },
  invalid_matrix_access: function invalid_matrix_access(id) {
    var context = [id];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_matrix_access", context));
  },
  matrix_column_outbounds_full: function matrix_column_outbounds_full(id, value, columns, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, value, id, columns];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("matrix_column_outbounds_full", context));
    } else {
      return ProcessorErrorFactory.matrix_column_outbounds(id, value, columns);
    }
  },
  matrix_column_outbounds: function matrix_column_outbounds(id, value, columns) {
    var context = [value, id, columns];
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("matrix_column_outbounds", context));
  },
  matrix_line_outbounds_full: function matrix_line_outbounds_full(id, value, lines, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, value, id, lines];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("matrix_line_outbounds_full", context));
    } else {
      return ProcessorErrorFactory.matrix_line_outbounds(id, value, lines);
    }
  },
  matrix_line_outbounds: function matrix_line_outbounds(id, value, lines) {
    var context = [value, id, lines];
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("matrix_line_outbounds", context));
  },
  vector_line_outbounds_full: function vector_line_outbounds_full(id, value, lines, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, value, id, lines];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("vector_line_outbounds_full", context));
    } else {
      return ProcessorErrorFactory.vector_line_outbounds(id, value, lines);
    }
  },
  vector_line_outbounds: function vector_line_outbounds(id, value, lines) {
    var context = [value, id, lines];
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("vector_line_outbounds", context));
  },
  vector_not_matrix_full: function vector_not_matrix_full(id, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, id];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("vector_not_matrix_full", context));
    } else {
      return ProcessorErrorFactory.vector_not_matrix(id);
    }
  },
  vector_not_matrix: function vector_not_matrix(id) {
    var context = [id];
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("vector_not_matrix", context));
  },
  function_no_return: function function_no_return(id) {
    var context = [id];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("function_no_return", context));
  },
  invalid_void_return_full: function invalid_void_return_full(id, type, dim, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, id, translateType(type, dim)];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_void_return_full", context));
    } else {
      return ProcessorErrorFactory.invalid_void_return(id, type, dim);
    }
  },
  invalid_void_return: function invalid_void_return(id, type, dim) {
    var context = [id, translateType(type, dim)];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_void_return_full", context));
  },
  invalid_return_type_full: function invalid_return_type_full(id, type, dim, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, id, translateType(type, dim)];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_return_type_full", context));
    } else {
      return ProcessorErrorFactory.invalid_return_type(id, type, dim);
    }
  },
  invalid_return_type: function invalid_return_type(id, type, dim) {
    var context = [id, translateType(type, dim)];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_return_type", context));
  },
  invalid_parameters_size_full: function invalid_parameters_size_full(id, expected, actual, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, id, expected, actual];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_parameters_size_full", context));
    } else {
      return ProcessorErrorFactory.invalid_parameters_size(id, expected, actual);
    }
  },
  invalid_parameters_size: function invalid_parameters_size(id, expected, actual) {
    var context = [id, expected, actual];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_parameters_size", context));
  },
  invalid_parameter_type_full: function invalid_parameter_type_full(id, exp, sourceInfo) {
    if (sourceInfo) {
      var context = [exp, id, sourceInfo.line];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_parameter_type_full", context));
    } else {
      return ProcessorErrorFactory.invalid_parameter_type(id, exp);
    }
  },
  invalid_parameter_type: function invalid_parameter_type(id, exp) {
    var context = [exp, id];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_parameter_type_full", context));
  },
  invalid_ref_full: function invalid_ref_full(id, exp, sourceInfo) {
    if (sourceInfo) {
      var context = [exp, id, sourceInfo.line];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_ref_full", context));
    } else {
      return ProcessorErrorFactory.invalid_ref(id, exp);
    }
  },
  invalid_ref: function invalid_ref(id, exp) {
    var context = [exp, id];
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("invalid_ref", context));
  },
  unexpected_break_command_full: function unexpected_break_command_full(sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("unexpected_break_command_full", context));
    } else {
      return ProcessorErrorFactory.unexpected_break_command();
    }
  },
  unexpected_break_command: function unexpected_break_command() {
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("unexpected_break_command"));
  },
  invalid_array_literal_type_full: function invalid_array_literal_type_full(exp, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, exp];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_array_literal_type_full", context));
    } else {
      return ProcessorErrorFactory.invalid_array_literal_type(exp);
    }
  },
  invalid_array_literal_type: function invalid_array_literal_type(exp) {
    var context = [exp];
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_array_literal_type", context));
  },
  invalid_array_literal_line_full: function invalid_array_literal_line_full(expected, actual, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, expected, actual];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_array_literal_line_full", context));
    } else {
      return ProcessorErrorFactory.invalid_array_literal_type(expected, actual);
    }
  },
  invalid_array_literal_line: function invalid_array_literal_line(expected, actual) {
    var context = [expected, actual];
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_array_literal_line", context));
  },
  invalid_array_literal_column_full: function invalid_array_literal_column_full(expected, actual, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, expected, actual];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_array_literal_column_full", context));
    } else {
      return ProcessorErrorFactory.invalid_array_literal_column(expected, actual);
    }
  },
  invalid_array_literal_column: function invalid_array_literal_column(expected, actual) {
    var context = [expected, actual];
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_array_literal_column", context));
  },
  invalid_unary_op_full: function invalid_unary_op_full(opName, type, dim, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, translateOp(opName), translateType(type, dim)];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_unary_op_full", context));
    } else {
      return ProcessorErrorFactory.invalid_unary_op(opName, type, dim);
    }
  },
  invalid_unary_op: function invalid_unary_op(opName, type, dim) {
    var context = [translateOp(opName), translateType(type, dim)];
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_unary_op", context));
  },
  invalid_infix_op_full: function invalid_infix_op_full(opName, typeLeft, dimLeft, typeRight, dimRight, sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line, translateOp(opName), translateType(typeLeft, dimLeft), translateType(typeRight, dimRight)];
      return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_infix_op_full", context));
    } else {
      return ProcessorErrorFactory.invalid_infix_op(opName, typeLeft, dimLeft, typeRight, dimRight);
    }
  },
  invalid_infix_op: function invalid_infix_op(opName, typeLeft, dimLeft, typeRight, dimRight) {
    var context = [translateOp(opName), translateType(typeLeft, dimLeft), translateType(typeRight, dimRight)];
    return new _runtimeError.RuntimeError(_localizedStringsService.LocalizedStrings.getError("invalid_infix_op", context));
  },
  array_dimension_not_positive_full: function array_dimension_not_positive_full(sourceInfo) {
    if (sourceInfo) {
      var context = [sourceInfo.line];
      return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("array_dimension_not_positive_full", context));
    } else {
      return ProcessorErrorFactory.array_dimension_not_positive();
    }
  },
  array_dimension_not_positive: function array_dimension_not_positive() {
    return new _semanticError.SemanticError(_localizedStringsService.LocalizedStrings.getError("array_dimension_not_positive"));
  }
});

/***/ }),

/***/ "./js/processor/error/runtimeError.js":
/*!********************************************!*\
  !*** ./js/processor/error/runtimeError.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var RuntimeError = exports.RuntimeError = function (_Error) {
  _inherits(RuntimeError, _Error);

  function RuntimeError() {
    var _ref;

    _classCallCheck(this, RuntimeError);

    for (var _len = arguments.length, msg = Array(_len), _key = 0; _key < _len; _key++) {
      msg[_key] = arguments[_key];
    }

    var _this = _possibleConstructorReturn(this, (_ref = RuntimeError.__proto__ || Object.getPrototypeOf(RuntimeError)).call.apply(_ref, [this].concat(msg)));

    if (Error.captureStackTrace) Error.captureStackTrace(_this, RuntimeError);
    return _this;
  }

  return RuntimeError;
}(Error);

/***/ }),

/***/ "./js/processor/error/semanticError.js":
/*!*********************************************!*\
  !*** ./js/processor/error/semanticError.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var SemanticError = exports.SemanticError = function (_Error) {
  _inherits(SemanticError, _Error);

  function SemanticError() {
    var _ref;

    _classCallCheck(this, SemanticError);

    for (var _len = arguments.length, msg = Array(_len), _key = 0; _key < _len; _key++) {
      msg[_key] = arguments[_key];
    }

    var _this = _possibleConstructorReturn(this, (_ref = SemanticError.__proto__ || Object.getPrototypeOf(SemanticError)).call.apply(_ref, [this].concat(msg)));

    if (Error.captureStackTrace) Error.captureStackTrace(_this, SemanticError);
    return _this;
  }

  return SemanticError;
}(Error);

/***/ }),

/***/ "./js/processor/ivprogProcessor.js":
/*!*****************************************!*\
  !*** ./js/processor/ivprogProcessor.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IVProgProcessor = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _store = __webpack_require__(/*! ./store/store */ "./js/processor/store/store.js");

var _storeObject = __webpack_require__(/*! ./store/storeObject */ "./js/processor/store/storeObject.js");

var _storeObjectArray = __webpack_require__(/*! ./store/storeObjectArray */ "./js/processor/store/storeObjectArray.js");

var _storeObjectRef = __webpack_require__(/*! ./store/storeObjectRef */ "./js/processor/store/storeObjectRef.js");

var _modes = __webpack_require__(/*! ./modes */ "./js/processor/modes.js");

var _context = __webpack_require__(/*! ./context */ "./js/processor/context.js");

var _types = __webpack_require__(/*! ./../typeSystem/types */ "./js/typeSystem/types.js");

var _operators = __webpack_require__(/*! ./../ast/operators */ "./js/ast/operators.js");

var _definedFunctions = __webpack_require__(/*! ./definedFunctions */ "./js/processor/definedFunctions.js");

var _compatibilityTable = __webpack_require__(/*! ./compatibilityTable */ "./js/processor/compatibilityTable.js");

var _commands = __webpack_require__(/*! ./../ast/commands/ */ "./js/ast/commands/index.js");

var Commands = _interopRequireWildcard(_commands);

var _expressions = __webpack_require__(/*! ./../ast/expressions/ */ "./js/ast/expressions/index.js");

var Expressions = _interopRequireWildcard(_expressions);

var _storeObjectArrayAddress = __webpack_require__(/*! ./store/storeObjectArrayAddress */ "./js/processor/store/storeObjectArrayAddress.js");

var _storeObjectArrayAddressRef = __webpack_require__(/*! ./store/storeObjectArrayAddressRef */ "./js/processor/store/storeObjectArrayAddressRef.js");

var _compoundType = __webpack_require__(/*! ./../typeSystem/compoundType */ "./js/typeSystem/compoundType.js");

var _parsers = __webpack_require__(/*! ../typeSystem/parsers */ "./js/typeSystem/parsers.js");

var _config = __webpack_require__(/*! ../util/config */ "./js/util/config.js");

var _decimal = __webpack_require__(/*! decimal.js */ "./node_modules/decimal.js/decimal.js");

var _decimal2 = _interopRequireDefault(_decimal);

var _processorErrorFactory = __webpack_require__(/*! ./error/processorErrorFactory */ "./js/processor/error/processorErrorFactory.js");

var _runtimeError = __webpack_require__(/*! ./error/runtimeError */ "./js/processor/error/runtimeError.js");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var IVProgProcessor = exports.IVProgProcessor = function () {
  _createClass(IVProgProcessor, null, [{
    key: 'LOOP_TIMEOUT',
    get: function get() {
      return _config.Config.loopTimeout;
    },
    set: function set(ms) {
      _config.Config.setConfig({ loopTimeout: ms });
    }
  }, {
    key: 'MAIN_INTERNAL_ID',
    get: function get() {
      return "$main";
    }
  }]);

  function IVProgProcessor(ast) {
    _classCallCheck(this, IVProgProcessor);

    this.ast = ast;
    this.globalStore = new _store.Store("$global");
    this.stores = [this.globalStore];
    this.context = [_context.Context.BASE];
    this.input = null;
    this.forceKill = false;
    this.loopTimers = [];
    this.output = null;
  }

  _createClass(IVProgProcessor, [{
    key: 'registerInput',
    value: function registerInput(input) {
      if (this.input !== null) this.input = null;
      this.input = input;
    }
  }, {
    key: 'registerOutput',
    value: function registerOutput(output) {
      if (this.output !== null) this.output = null;
      this.output = output;
    }
  }, {
    key: 'checkContext',
    value: function checkContext(context) {
      return this.context[this.context.length - 1] === context;
    }
  }, {
    key: 'ignoreSwitchCases',
    value: function ignoreSwitchCases(store) {
      if (store.mode === _modes.Modes.RETURN) {
        return true;
      } else if (store.mode === _modes.Modes.BREAK) {
        return true;
      } else {
        return false;
      }
    }
  }, {
    key: 'prepareState',
    value: function prepareState() {
      if (this.stores !== null) {
        for (var i = 0; i < this.stores.length; i++) {
          delete this.stores[i];
        }
        this.stores = null;
      }
      if (this.globalStore !== null) this.globalStore = null;
      this.globalStore = new _store.Store("$global");
      this.stores = [this.globalStore];
      this.context = [_context.Context.BASE];
    }
  }, {
    key: 'interpretAST',
    value: function interpretAST() {
      var _this = this;

      this.prepareState();
      return this.initGlobal().then(function (_) {
        var mainFunc = _this.findMainFunction();
        if (mainFunc === null) {
          throw _processorErrorFactory.ProcessorErrorFactory.main_missing();
        }
        return _this.runFunction(mainFunc, [], _this.globalStore);
      });
    }
  }, {
    key: 'initGlobal',
    value: function initGlobal() {
      if (!this.checkContext(_context.Context.BASE)) {
        throw _processorErrorFactory.ProcessorErrorFactory.invalid_global_var();
      }
      return this.executeCommands(this.globalStore, this.ast.global);
    }
  }, {
    key: 'findMainFunction',
    value: function findMainFunction() {
      return this.ast.functions.find(function (v) {
        return v.isMain;
      });
    }
  }, {
    key: 'findFunction',
    value: function findFunction(name) {
      if (name.match(/^\$.+$/)) {
        var fun = _definedFunctions.LanguageDefinedFunction.getFunction(name);
        if (!!!fun) {
          throw _processorErrorFactory.ProcessorErrorFactory.not_implemented(name);
        }
        return fun;
      } else {
        var val = this.ast.functions.find(function (v) {
          return v.name === name;
        });
        if (!!!val) {
          // TODO: better error message;
          throw _processorErrorFactory.ProcessorErrorFactory.function_missing(name);
        }
        return val;
      }
    }
  }, {
    key: 'runFunction',
    value: function runFunction(func, actualParameters, store) {
      var _this2 = this;

      var funcName = func.isMain ? IVProgProcessor.MAIN_INTERNAL_ID : func.name;
      var funcStore = new _store.Store(funcName);
      funcStore.extendStore(this.globalStore);
      var returnStoreObject = null;
      if (func.returnType instanceof _compoundType.CompoundType) {
        if (func.returnType.dimensions > 1) {
          returnStoreObject = new _storeObjectArray.StoreObjectArray(func.returnType, -1, -1, [[]]);
        } else {
          returnStoreObject = new _storeObjectArray.StoreObjectArray(func.returnType, -1, null, []);
        }
      } else {
        returnStoreObject = new _storeObject.StoreObject(func.returnType, null);
      }
      funcStore.insertStore('$', returnStoreObject);
      var newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
      return newFuncStore$.then(function (sto) {
        _this2.context.push(_context.Context.FUNCTION);
        _this2.stores.push(sto);
        return _this2.executeCommands(sto, func.variablesDeclarations).then(function (stoWithVars) {
          return _this2.executeCommands(stoWithVars, func.commands);
        }).then(function (finalSto) {
          _this2.stores.pop();
          _this2.context.pop();
          return finalSto;
        });
      });
    }
  }, {
    key: 'associateParameters',
    value: function associateParameters(formalList, actualList, callerStore, calleeStore) {
      var _this3 = this;

      var funcName = calleeStore.name === IVProgProcessor.MAIN_INTERNAL_ID ? _definedFunctions.LanguageDefinedFunction.getMainFunctionName() : calleeStore.name;

      if (formalList.length != actualList.length) {
        throw _processorErrorFactory.ProcessorErrorFactory.invalid_parameters_size(funcName, formalList.length, actualList.length);
      }
      var promises$ = actualList.map(function (actualParameter) {
        return _this3.evaluateExpression(callerStore, actualParameter);
      });
      return Promise.all(promises$).then(function (values) {
        for (var i = 0; i < values.length; i++) {
          var stoObj = values[i];
          var exp = actualList[i];
          var shouldTypeCast = false;
          var formalParameter = formalList[i];
          if (!formalParameter.type.isCompatible(stoObj.type)) {
            if (_config.Config.enable_type_casting && !formalParameter.byRef && _store.Store.canImplicitTypeCast(formalParameter.type, stoObj.type)) {
              shouldTypeCast = true;
            } else {
              throw _processorErrorFactory.ProcessorErrorFactory.invalid_parameter_type(funcName, exp.toString());
            }
          }

          if (formalParameter.byRef && !stoObj.inStore) {
            throw _processorErrorFactory.ProcessorErrorFactory.invalid_ref(funcName, exp.toString());
          }

          if (formalParameter.byRef) {
            var ref = null;
            if (stoObj instanceof _storeObjectArrayAddress.StoreObjectArrayAddress) {
              ref = new _storeObjectArrayAddressRef.StoreObjectArrayAddressRef(stoObj);
            } else {
              ref = new _storeObjectRef.StoreObjectRef(stoObj.id, callerStore);
            }
            calleeStore.insertStore(formalParameter.id, ref);
          } else {
            var realValue = _this3.parseStoreObjectValue(stoObj);
            if (shouldTypeCast) {
              realValue = _store.Store.doImplicitCasting(formalParameter.type, realValue);
            }
            calleeStore.insertStore(formalParameter.id, realValue);
          }
        }
        return calleeStore;
      });
    }
  }, {
    key: 'executeCommands',
    value: function executeCommands(store, cmds) {
      // helper to partially apply a function, in this case executeCommand
      var outerRef = this;
      var partial = function partial(fun, cmd) {
        return function (sto) {
          return fun(sto, cmd);
        };
      };
      return cmds.reduce(function (lastCommand, next) {
        var nextCommand = partial(outerRef.executeCommand.bind(outerRef), next);
        return lastCommand.then(nextCommand);
      }, Promise.resolve(store));
    }
  }, {
    key: 'executeCommand',
    value: function executeCommand(store, cmd) {

      if (this.forceKill) {
        return Promise.reject("FORCED_KILL!");
      } else if (store.mode === _modes.Modes.PAUSE) {
        return Promise.resolve(this.executeCommand(store, cmd));
      } else if (store.mode === _modes.Modes.RETURN) {
        return Promise.resolve(store);
      } else if (this.checkContext(_context.Context.BREAKABLE) && store.mode === _modes.Modes.BREAK) {
        return Promise.resolve(store);
      }

      if (cmd instanceof Commands.Declaration) {
        return this.executeDeclaration(store, cmd);
      } else if (cmd instanceof Commands.ArrayIndexAssign) {
        return this.executeArrayIndexAssign(store, cmd);
      } else if (cmd instanceof Commands.Assign) {
        return this.executeAssign(store, cmd);
      } else if (cmd instanceof Commands.Break) {
        return this.executeBreak(store, cmd);
      } else if (cmd instanceof Commands.Return) {
        return this.executeReturn(store, cmd);
      } else if (cmd instanceof Commands.IfThenElse) {
        return this.executeIfThenElse(store, cmd);
      } else if (cmd instanceof Commands.While) {
        return this.executeWhile(store, cmd);
      } else if (cmd instanceof Commands.DoWhile) {
        return this.executeDoWhile(store, cmd);
      } else if (cmd instanceof Commands.For) {
        return this.executeFor(store, cmd);
      } else if (cmd instanceof Commands.Switch) {
        return this.executeSwitch(store, cmd);
      } else if (cmd instanceof Expressions.FunctionCall) {

        return this.executeFunctionCall(store, cmd);
      } else if (cmd instanceof Commands.SysCall) {
        return this.executeSysCall(store, cmd);
      } else {
        throw _processorErrorFactory.ProcessorErrorFactory.unknown_command(cmd.sourceInfo);
      }
    }
  }, {
    key: 'executeSysCall',
    value: function executeSysCall(store, cmd) {
      var func = cmd.langFunc.bind(this);
      return func(store, cmd);
    }
  }, {
    key: 'executeFunctionCall',
    value: function executeFunctionCall(store, cmd) {
      var func = null;
      if (cmd.isMainCall) {
        func = this.findMainFunction();
      } else {
        func = this.findFunction(cmd.id);
      }
      return this.runFunction(func, cmd.actualParameters, store).then(function (sto) {
        if (!_types.Types.VOID.isCompatible(func.returnType) && sto.mode !== _modes.Modes.RETURN) {
          var funcName = func.name === IVProgProcessor.MAIN_INTERNAL_ID ? _definedFunctions.LanguageDefinedFunction.getMainFunctionName() : func.name;
          return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.function_no_return(funcName));
        } else {
          return store;
        }
      });
    }
  }, {
    key: 'executeSwitch',
    value: function executeSwitch(store, cmd) {
      var _this4 = this;

      this.context.push(_context.Context.BREAKABLE);
      var auxCaseFun = function auxCaseFun(promise, switchExp, aCase) {
        return promise.then(function (result) {
          var sto = result.sto;
          if (_this4.ignoreSwitchCases(sto)) {
            return Promise.resolve(result);
          } else if (result.wasTrue || aCase.isDefault) {
            var $newSto = _this4.executeCommands(result.sto, aCase.commands);
            return $newSto.then(function (nSto) {
              return Promise.resolve({ wasTrue: true, sto: nSto });
            });
          } else {
            var $value = _this4.evaluateExpression(sto, new Expressions.InfixApp(_operators.Operators.EQ, switchExp, aCase.expression));
            return $value.then(function (vl) {
              if (vl.value) {
                var _$newSto = _this4.executeCommands(result.sto, aCase.commands);
                return _$newSto.then(function (nSto) {
                  return Promise.resolve({ wasTrue: true, sto: nSto });
                });
              } else {
                return Promise.resolve({ wasTrue: false, sto: sto });
              }
            });
          }
        });
      };

      try {
        var breakLoop = false;
        var $result = Promise.resolve({ wasTrue: false, sto: store });
        for (var index = 0; index < cmd.cases.length && !breakLoop; index++) {
          var aCase = cmd.cases[index];
          $result = auxCaseFun($result, cmd.expression, aCase);
          $result.then(function (r) {
            return breakLoop = _this4.ignoreSwitchCases(r.sto);
          });
        }
        return $result.then(function (r) {
          _this4.context.pop();
          if (r.sto.mode === _modes.Modes.BREAK) {
            r.sto.mode = _modes.Modes.RUN;
          }
          return r.sto;
        });
      } catch (error) {
        return Promise.reject(error);
      }
    }
  }, {
    key: 'executeFor',
    value: function executeFor(store, cmd) {
      try {
        //BEGIN for -> while rewrite
        var initCmd = cmd.assignment;
        var condition = cmd.condition;
        var increment = cmd.increment;
        var whileBlock = new Commands.CommandBlock([], cmd.commands.concat(increment));
        var forAsWhile = new Commands.While(condition, whileBlock);
        forAsWhile.sourceInfo = cmd.sourceInfo;
        //END for -> while rewrite
        var newCmdList = [initCmd, forAsWhile];
        return this.executeCommands(store, newCmdList);
      } catch (error) {
        return Promise.reject(error);
      }
    }
  }, {
    key: 'executeDoWhile',
    value: function executeDoWhile(store, cmd) {
      var outerRef = this;
      try {
        outerRef.loopTimers.push(Date.now());
        outerRef.context.push(_context.Context.BREAKABLE);
        var $newStore = outerRef.executeCommands(store, cmd.commands);
        return $newStore.then(function (sto) {
          if (sto.mode === _modes.Modes.BREAK) {
            outerRef.context.pop();
            sto.mode = _modes.Modes.RUN;
            outerRef.loopTimers.pop();
            return sto;
          }
          var $value = outerRef.evaluateExpression(sto, cmd.expression);
          return $value.then(function (vl) {
            if (!vl.type.isCompatible(_types.Types.BOOLEAN)) {
              return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo));
            }
            if (vl.value) {
              outerRef.context.pop();
              for (var i = 0; i < outerRef.loopTimers.length; i++) {
                var time = outerRef.loopTimers[i];
                if (Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
                  outerRef.forceKill = true;
                  return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
                }
              }
              return outerRef.executeCommand(sto, cmd);
            } else {
              outerRef.context.pop();
              outerRef.loopTimers.pop();
              return sto;
            }
          });
        });
      } catch (error) {
        return Promise.reject(error);
      }
    }
  }, {
    key: 'executeWhile',
    value: function executeWhile(store, cmd) {
      var outerRef = this;
      try {
        outerRef.loopTimers.push(Date.now());
        outerRef.context.push(_context.Context.BREAKABLE);
        var $value = outerRef.evaluateExpression(store, cmd.expression);
        return $value.then(function (vl) {
          if (vl.type.isCompatible(_types.Types.BOOLEAN)) {
            if (vl.value) {
              var $newStore = outerRef.executeCommands(store, cmd.commands);
              return $newStore.then(function (sto) {
                outerRef.context.pop();
                if (sto.mode === _modes.Modes.BREAK) {
                  outerRef.loopTimers.pop();
                  sto.mode = _modes.Modes.RUN;
                  return sto;
                }
                for (var i = 0; i < outerRef.loopTimers.length; i++) {
                  var time = outerRef.loopTimers[i];
                  if (Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
                    outerRef.forceKill = true;
                    return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
                  }
                }
                return outerRef.executeCommand(sto, cmd);
              });
            } else {
              outerRef.context.pop();
              outerRef.loopTimers.pop();
              return store;
            }
          } else {
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo));
          }
        });
      } catch (error) {
        return Promise.reject(error);
      }
    }
  }, {
    key: 'executeIfThenElse',
    value: function executeIfThenElse(store, cmd) {
      var _this5 = this;

      try {
        var $value = this.evaluateExpression(store, cmd.condition);
        return $value.then(function (vl) {
          if (vl.type.isCompatible(_types.Types.BOOLEAN)) {
            if (vl.value) {
              return _this5.executeCommands(store, cmd.ifTrue.commands);
            } else if (cmd.ifFalse !== null) {
              if (cmd.ifFalse instanceof Commands.IfThenElse) {
                return _this5.executeCommand(store, cmd.ifFalse);
              } else {
                return _this5.executeCommands(store, cmd.ifFalse.commands);
              }
            } else {
              return Promise.resolve(store);
            }
          } else {
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.if_condition_type_full(cmd.sourceInfo));
          }
        });
      } catch (error) {
        return Promise.reject(error);
      }
    }
  }, {
    key: 'executeReturn',
    value: function executeReturn(store, cmd) {
      var _this6 = this;

      try {
        var funcType = store.applyStore('$').type;
        var $value = this.evaluateExpression(store, cmd.expression);
        var funcName = store.name === IVProgProcessor.MAIN_INTERNAL_ID ? _definedFunctions.LanguageDefinedFunction.getMainFunctionName() : store.name;
        return $value.then(function (vl) {

          if (vl === null && funcType.isCompatible(_types.Types.VOID)) {
            return Promise.resolve(store);
          }

          if (vl === null || !funcType.isCompatible(vl.type)) {
            var stringInfo = funcType.stringInfo();
            var info = stringInfo[0];
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.invalid_return_type_full(funcName, info.type, info.dim, cmd.sourceInfo));
          } else {
            var realValue = _this6.parseStoreObjectValue(vl);
            store.updateStore('$', realValue);
            store.mode = _modes.Modes.RETURN;
            return Promise.resolve(store);
          }
        });
      } catch (error) {
        return Promise.reject(error);
      }
    }
  }, {
    key: 'executeBreak',
    value: function executeBreak(store, cmd) {
      if (this.checkContext(_context.Context.BREAKABLE)) {
        store.mode = _modes.Modes.BREAK;
        return Promise.resolve(store);
      } else {
        return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.unexpected_break_command_full(cmd.sourceInfo));
      }
    }
  }, {
    key: 'executeAssign',
    value: function executeAssign(store, cmd) {
      var _this7 = this;

      try {
        var inStore = store.applyStore(cmd.id);
        var $value = this.evaluateExpression(store, cmd.expression);
        return $value.then(function (vl) {
          var realValue = _this7.parseStoreObjectValue(vl);
          if (!inStore.type.isCompatible(realValue.type)) {
            if (_config.Config.enable_type_casting && _store.Store.canImplicitTypeCast(inStore.type, vl.type)) {
              realValue = _store.Store.doImplicitCasting(inStore.type, realValue);
            } else {
              var stringInfo = inStore.type.stringInfo();
              var info = stringInfo[0];
              return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
            }
          }

          store.updateStore(cmd.id, realValue);
          return store;
        });
      } catch (error) {
        return Promise.reject(error);
      }
    }
  }, {
    key: 'executeArrayIndexAssign',
    value: function executeArrayIndexAssign(store, cmd) {
      var _this8 = this;

      var mustBeArray = store.applyStore(cmd.id);
      if (!(mustBeArray.type instanceof _compoundType.CompoundType)) {
        return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo));
      }
      var line$ = this.evaluateExpression(store, cmd.line);
      var column$ = this.evaluateExpression(store, cmd.column);
      var value$ = this.evaluateExpression(store, cmd.expression);
      return Promise.all([line$, column$, value$]).then(function (results) {
        var lineSO = results[0];
        if (!_types.Types.INTEGER.isCompatible(lineSO.type)) {
          return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
        }
        var line = lineSO.number;
        var columnSO = results[1];
        var column = null;
        if (columnSO !== null) {
          if (!_types.Types.INTEGER.isCompatible(columnSO.type)) {
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
          }
          column = columnSO.number;
        }
        var value = _this8.parseStoreObjectValue(results[2]);
        if (line >= mustBeArray.lines) {
          if (mustBeArray.isVector) {
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.vector_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
          } else {
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.matrix_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
          }
        } else if (line < 0) {
          throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
        }
        if (column !== null && mustBeArray.columns === null) {
          return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.vector_not_matrix_full(cmd.id, cmd.sourceInfo));
        }
        if (column !== null) {
          if (column >= mustBeArray.columns) {
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.matrix_column_outbounds_full(cmd.id, column, mustBeArray.columns, cmd.sourceInfo));
          } else if (column < 0) {
            throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
          }
        }

        var newArray = Object.assign(new _storeObjectArray.StoreObjectArray(null, null, null), mustBeArray);
        if (column !== null) {
          if (value.type instanceof _compoundType.CompoundType || !newArray.type.canAccept(value.type)) {
            var type = mustBeArray.type.innerType;
            var stringInfo = type.stringInfo();
            var info = stringInfo[0];
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
          }
          newArray.value[line].value[column] = value;
          store.updateStore(cmd.id, newArray);
        } else {
          if (mustBeArray.columns !== null && value.type instanceof _compoundType.CompoundType || !newArray.type.canAccept(value.type)) {
            var _type = mustBeArray.type;
            var _stringInfo = _type.stringInfo();
            var _info = _stringInfo[0];
            var exp = cmd.expression.toString();
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.incompatible_types_array_full(exp, _info.type, _info.dim - 1, cmd.sourceInfo));
          }
          newArray.value[line] = value;
          store.updateStore(cmd.id, newArray);
        }
        return store;
      });
    }
  }, {
    key: 'executeDeclaration',
    value: function executeDeclaration(store, cmd) {
      try {
        var $value = this.evaluateExpression(store, cmd.initial);
        if (cmd instanceof Commands.ArrayDeclaration) {
          var $lines = this.evaluateExpression(store, cmd.lines);
          var $columns = cmd.columns === null ? null : this.evaluateExpression(store, cmd.columns);
          return Promise.all([$lines, $columns, $value]).then(function (values) {
            var lineSO = values[0];
            if (!_types.Types.INTEGER.isCompatible(lineSO.type)) {
              return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
            }
            var line = lineSO.number;
            if (line < 0) {
              throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
            }
            var columnSO = values[1];
            var column = null;
            if (columnSO !== null) {
              if (!_types.Types.INTEGER.isCompatible(columnSO.type)) {
                return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
              }
              column = columnSO.number;
              if (column < 0) {
                throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
              }
            }
            var value = values[2];
            var temp = new _storeObjectArray.StoreObjectArray(cmd.type, line, column, null);
            store.insertStore(cmd.id, temp);
            var realValue = value;
            if (value !== null) {
              if (value instanceof _storeObjectArrayAddress.StoreObjectArrayAddress) {
                if (value.type instanceof _compoundType.CompoundType) {
                  realValue = Object.assign(new _storeObjectArray.StoreObjectArray(null, null, null), value.refValue);
                } else {
                  realValue = Object.assign(new _storeObject.StoreObject(null, null), value.refValue);
                }
              }
            } else {
              realValue = new _storeObjectArray.StoreObjectArray(cmd.type, line, column, []);
              if (column !== null) {
                for (var i = 0; i < line; i++) {
                  realValue.value.push(new _storeObjectArray.StoreObjectArray(new _compoundType.CompoundType(cmd.type.innerType, 1), column, null, []));
                }
              }
            }
            realValue.readOnly = cmd.isConst;
            store.updateStore(cmd.id, realValue);
            return store;
          });
        } else {
          var temp = new _storeObject.StoreObject(cmd.type, null);
          store.insertStore(cmd.id, temp);
          return $value.then(function (vl) {
            var realValue = vl;
            if (vl !== null) {
              if (!vl.type.isCompatible(cmd.type)) {
                if (_config.Config.enable_type_casting && _store.Store.canImplicitTypeCast(cmd.type, vl.type)) {
                  realValue = _store.Store.doImplicitCasting(cmd.type, realValue);
                } else {
                  var stringInfo = typeInfo.type.stringInfo();
                  var info = stringInfo[0];
                  return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
                }
              }
              if (vl instanceof _storeObjectArrayAddress.StoreObjectArrayAddress) {
                if (vl.type instanceof _compoundType.CompoundType) {
                  return Promise.reject(new Error("!!!Critical Error: Compatibility check failed, a Type accepts a CompoundType"));
                } else {
                  realValue = Object.assign(new _storeObject.StoreObject(null, null), vl.refValue);
                }
              }
            } else {
              realValue = new _storeObject.StoreObject(cmd.type, 0);
            }
            realValue.readOnly = cmd.isConst;
            store.updateStore(cmd.id, realValue);
            return store;
          });
        }
      } catch (e) {
        return Promise.reject(e);
      }
    }
  }, {
    key: 'evaluateExpression',
    value: function evaluateExpression(store, exp) {

      if (exp instanceof Expressions.UnaryApp) {
        return this.evaluateUnaryApp(store, exp);
      } else if (exp instanceof Expressions.InfixApp) {
        return this.evaluateInfixApp(store, exp);
      } else if (exp instanceof Expressions.ArrayAccess) {
        return this.evaluateArrayAccess(store, exp);
      } else if (exp instanceof Expressions.VariableLiteral) {
        return this.evaluateVariableLiteral(store, exp);
      } else if (exp instanceof Expressions.IntLiteral) {
        return this.evaluateLiteral(store, exp);
      } else if (exp instanceof Expressions.RealLiteral) {
        return this.evaluateLiteral(store, exp);
      } else if (exp instanceof Expressions.BoolLiteral) {
        return this.evaluateLiteral(store, exp);
      } else if (exp instanceof Expressions.StringLiteral) {
        return this.evaluateLiteral(store, exp);
      } else if (exp instanceof Expressions.ArrayLiteral) {
        return this.evaluateArrayLiteral(store, exp);
      } else if (exp instanceof Expressions.FunctionCall) {
        return this.evaluateFunctionCall(store, exp);
      }
      return Promise.resolve(null);
    }
  }, {
    key: 'evaluateFunctionCall',
    value: function evaluateFunctionCall(store, exp) {
      if (exp.isMainCall) {
        return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.void_in_expression_full(_definedFunctions.LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
      }
      var func = this.findFunction(exp.id);
      if (_types.Types.VOID.isCompatible(func.returnType)) {
        // TODO: better error message
        return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.void_in_expression_full(exp.id, exp.sourceInfo));
      }
      var $newStore = this.runFunction(func, exp.actualParameters, store);
      return $newStore.then(function (sto) {
        if (sto.mode !== _modes.Modes.RETURN) {
          return Promise.reject(new Error("The function that was called did not had a return command: " + exp.id));
        }
        var val = sto.applyStore('$');
        if (val instanceof _storeObjectArray.StoreObjectArray) {
          return Promise.resolve(Object.assign(new _storeObjectArray.StoreObjectArray(null, null, null, null, null), val));
        } else {
          return Promise.resolve(Object.assign(new _storeObject.StoreObject(null, null), val));
        }
      });
    }
  }, {
    key: 'evaluateArrayLiteral',
    value: function evaluateArrayLiteral(store, exp) {
      var errorHelperFunction = function errorHelperFunction(validationResult, exp) {
        var errorCode = validationResult[0];
        switch (errorCode) {
          case _storeObjectArray.StoreObjectArray.WRONG_COLUMN_NUMBER:
            {
              var columnValue = validationResult[1];
              return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.invalid_array_literal_column_full(arr.columns, columnValue, exp.sourceInfo));
            }
          case _storeObjectArray.StoreObjectArray.WRONG_LINE_NUMBER:
            {
              var lineValue = validationResult[1];
              return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.invalid_array_literal_line_full(arr.lines, lineValue, exp.sourceInfo));
            }
          case _storeObjectArray.StoreObjectArray.WRONG_TYPE:
            {
              var line = null;
              var strExp = null;
              if (validationResult.length > 2) {
                line = validationResult[1];
                var column = validationResult[2];
                strExp = exp.value[line].value[column].toString();
              } else {
                line = validationResult[1];
                strExp = exp.value[line].toString();
              }
              return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.invalid_array_literal_type_full(strExp, exp.sourceInfo));
            }
        }
      };
      if (!exp.isVector) {
        var $matrix = this.evaluateMatrix(store, exp.value);
        return $matrix.then(function (list) {
          var type = new _compoundType.CompoundType(list[0].type.innerType, 2);
          var arr = new _storeObjectArray.StoreObjectArray(type, list.length, list[0].lines, list);
          var checkResult = arr.isValid;
          if (checkResult.length == 0) return Promise.resolve(arr);else {
            return errorHelperFunction(checkResult, exp);
          }
        });
      } else {
        return this.evaluateVector(store, exp.value).then(function (list) {
          var type = new _compoundType.CompoundType(list[0].type, 1);
          var stoArray = new _storeObjectArray.StoreObjectArray(type, list.length, null, list);
          var checkResult = stoArray.isValid;
          if (checkResult.length == 0) return Promise.resolve(stoArray);else {
            return errorHelperFunction(checkResult, exp);
          }
        });
      }
    }
  }, {
    key: 'evaluateVector',
    value: function evaluateVector(store, exps) {
      var _this9 = this;

      return Promise.all(exps.map(function (exp) {
        return _this9.evaluateExpression(store, exp);
      }));
    }
  }, {
    key: 'evaluateMatrix',
    value: function evaluateMatrix(store, exps) {
      var _this10 = this;

      return Promise.all(exps.map(function (vector) {
        var $vector = _this10.evaluateVector(store, vector.value);
        return $vector.then(function (list) {
          var type = new _compoundType.CompoundType(list[0].type, 1);
          return new _storeObjectArray.StoreObjectArray(type, list.length, null, list);
        });
      }));
    }
  }, {
    key: 'evaluateLiteral',
    value: function evaluateLiteral(_, exp) {
      return Promise.resolve(new _storeObject.StoreObject(exp.type, exp.value));
    }
  }, {
    key: 'evaluateVariableLiteral',
    value: function evaluateVariableLiteral(store, exp) {
      try {
        var val = store.applyStore(exp.id);
        if (val instanceof _storeObjectArray.StoreObjectArray) {
          return Promise.resolve(Object.assign(new _storeObjectArray.StoreObjectArray(null, null, null, null), val));
        } else {
          return Promise.resolve(Object.assign(new _storeObject.StoreObject(null, null), val));
        }
      } catch (error) {
        return Promise.reject(error);
      }
    }
  }, {
    key: 'evaluateArrayAccess',
    value: function evaluateArrayAccess(store, exp) {
      var mustBeArray = store.applyStore(exp.id);
      if (!(mustBeArray.type instanceof _compoundType.CompoundType)) {
        return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.invalid_array_access_full(exp.id, exp.sourceInfo));
      }
      var $line = this.evaluateExpression(store, exp.line);
      var $column = this.evaluateExpression(store, exp.column);
      return Promise.all([$line, $column]).then(function (values) {
        var lineSO = values[0];
        var columnSO = values[1];
        if (!_types.Types.INTEGER.isCompatible(lineSO.type)) {
          return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
        }
        var line = lineSO.number;
        var column = null;
        if (columnSO !== null) {
          if (!_types.Types.INTEGER.isCompatible(columnSO.type)) {
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
          }
          column = columnSO.number;
        }

        if (line >= mustBeArray.lines) {
          if (mustBeArray.isVector) {
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.vector_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
          } else {
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.matrix_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
          }
        } else if (line < 0) {
          throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
        }
        if (column !== null && mustBeArray.columns === null) {
          return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.vector_not_matrix_full(exp.id, exp.sourceInfo));
        }
        if (column !== null) {
          if (column >= mustBeArray.columns) {
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.matrix_column_outbounds_full(exp.id, column, mustBeArray.columns, exp.sourceInfo));
          } else if (column < 0) {
            throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
          }
        }
        return Promise.resolve(new _storeObjectArrayAddress.StoreObjectArrayAddress(mustBeArray.id, line, column, store));
      });
    }
  }, {
    key: 'evaluateUnaryApp',
    value: function evaluateUnaryApp(store, unaryApp) {
      var $left = this.evaluateExpression(store, unaryApp.left);
      return $left.then(function (left) {
        var resultType = (0, _compatibilityTable.resultTypeAfterUnaryOp)(unaryApp.op, left.type);
        if (_types.Types.UNDEFINED.isCompatible(resultType)) {
          var stringInfo = left.type.stringInfo();
          var info = stringInfo[0];
          return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.invalid_unary_op_full(unaryApp.op, info.type, info.dim, unaryApp.sourceInfo));
        }
        switch (unaryApp.op.ord) {
          case _operators.Operators.ADD.ord:
            return new _storeObject.StoreObject(resultType, left.value);
          case _operators.Operators.SUB.ord:
            return new _storeObject.StoreObject(resultType, left.value.negated());
          case _operators.Operators.NOT.ord:
            return new _storeObject.StoreObject(resultType, !left.value);
          default:
            return Promise.reject(new _runtimeError.RuntimeError('!!!Critical Invalid UnaryApp ' + unaryApp.op));
        }
      });
    }
  }, {
    key: 'evaluateInfixApp',
    value: function evaluateInfixApp(store, infixApp) {
      var $left = this.evaluateExpression(store, infixApp.left);
      var $right = this.evaluateExpression(store, infixApp.right);
      return Promise.all([$left, $right]).then(function (values) {
        var shouldImplicitCast = false;
        var left = values[0];
        var right = values[1];
        var resultType = (0, _compatibilityTable.resultTypeAfterInfixOp)(infixApp.op, left.type, right.type);
        if (_types.Types.UNDEFINED.isCompatible(resultType)) {
          if (_config.Config.enable_type_casting && _store.Store.canImplicitTypeCast(left.type, right.type)) {
            shouldImplicitCast = true;
          } else {
            var stringInfoLeft = left.type.stringInfo();
            var infoLeft = stringInfoLeft[0];
            var stringInfoRight = right.type.stringInfo();
            var infoRight = stringInfoRight[0];
            return Promise.reject(_processorErrorFactory.ProcessorErrorFactory.invalid_infix_op_full(infixApp.op, infoLeft.type, infoLeft.dim, infoRight.type, infoRight.dim, infixApp.sourceInfo));
          }
        }
        var result = null;
        switch (infixApp.op.ord) {
          case _operators.Operators.ADD.ord:
            {
              if (_types.Types.STRING.isCompatible(left.type)) {
                var rightStr = (0, _parsers.convertToString)(right.value, right.type);
                return new _storeObject.StoreObject(resultType, left.value + rightStr);
              } else if (_types.Types.STRING.isCompatible(right.type)) {
                var leftStr = (0, _parsers.convertToString)(left.value, left.type);
                return new _storeObject.StoreObject(resultType, leftStr + right.value);
              } else {
                return new _storeObject.StoreObject(resultType, left.value.plus(right.value));
              }
            }
          case _operators.Operators.SUB.ord:
            return new _storeObject.StoreObject(resultType, left.value.minus(right.value));
          case _operators.Operators.MULT.ord:
            {
              result = left.value.times(right.value);
              if (result.dp() > _config.Config.decimalPlaces) {
                result = new _decimal2.default(result.toFixed(_config.Config.decimalPlaces));
              }
              return new _storeObject.StoreObject(resultType, result);
            }
          case _operators.Operators.DIV.ord:
            {
              if (_types.Types.INTEGER.isCompatible(resultType)) result = left.value.divToInt(right.value);else result = left.value.div(right.value);
              if (result.dp() > _config.Config.decimalPlaces) {
                result = new _decimal2.default(result.toFixed(_config.Config.decimalPlaces));
              }
              return new _storeObject.StoreObject(resultType, result);
            }
          case _operators.Operators.MOD.ord:
            {
              var leftValue = left.value;
              var rightValue = right.value;
              if (shouldImplicitCast) {
                resultType = _types.Types.INTEGER;
                leftValue = leftValue.trunc();
                rightValue = rightValue.trunc();
              }
              result = leftValue.modulo(rightValue);
              if (result.dp() > _config.Config.decimalPlaces) {
                result = new _decimal2.default(result.toFixed(_config.Config.decimalPlaces));
              }
              return new _storeObject.StoreObject(resultType, result);
            }
          case _operators.Operators.GT.ord:
            {
              var _leftValue = left.value;
              var _rightValue = right.value;
              if (_types.Types.STRING.isCompatible(left.type)) {
                result = left.value.length > right.value.length;
              } else {
                if (shouldImplicitCast) {
                  resultType = _types.Types.BOOLEAN;
                  _leftValue = _leftValue.trunc();
                  _rightValue = _rightValue.trunc();
                }
                result = _leftValue.gt(_rightValue);
              }
              return new _storeObject.StoreObject(resultType, result);
            }
          case _operators.Operators.GE.ord:
            {
              var _leftValue2 = left.value;
              var _rightValue2 = right.value;
              if (_types.Types.STRING.isCompatible(left.type)) {
                result = left.value.length >= right.value.length;
              } else {
                if (shouldImplicitCast) {
                  resultType = _types.Types.BOOLEAN;
                  _leftValue2 = _leftValue2.trunc();
                  _rightValue2 = _rightValue2.trunc();
                }
                result = _leftValue2.gte(_rightValue2);
              }
              return new _storeObject.StoreObject(resultType, result);
            }
          case _operators.Operators.LT.ord:
            {
              var _leftValue3 = left.value;
              var _rightValue3 = right.value;
              if (_types.Types.STRING.isCompatible(left.type)) {
                result = left.value.length < right.value.length;
              } else {
                if (shouldImplicitCast) {
                  resultType = _types.Types.BOOLEAN;
                  _leftValue3 = _leftValue3.trunc();
                  _rightValue3 = _rightValue3.trunc();
                }
                result = _leftValue3.lt(_rightValue3);
              }
              return new _storeObject.StoreObject(resultType, result);
            }
          case _operators.Operators.LE.ord:
            {
              var _leftValue4 = left.value;
              var _rightValue4 = right.value;
              if (_types.Types.STRING.isCompatible(left.type)) {
                result = left.value.length <= right.value.length;
              } else {
                if (shouldImplicitCast) {
                  resultType = _types.Types.BOOLEAN;
                  _leftValue4 = _leftValue4.trunc();
                  _rightValue4 = _rightValue4.trunc();
                }
                result = _leftValue4.lte(_rightValue4);
              }
              return new _storeObject.StoreObject(resultType, result);
            }
          case _operators.Operators.EQ.ord:
            {
              var _leftValue5 = left.value;
              var _rightValue5 = right.value;
              if (_types.Types.INTEGER.isCompatible(left.type) || _types.Types.REAL.isCompatible(left.type)) {
                if (shouldImplicitCast) {
                  resultType = _types.Types.BOOLEAN;
                  _leftValue5 = _leftValue5.trunc();
                  _rightValue5 = _rightValue5.trunc();
                }
                result = _leftValue5.eq(_rightValue5);
              } else {
                result = left.value === right.value;
              }
              return new _storeObject.StoreObject(resultType, result);
            }
          case _operators.Operators.NEQ.ord:
            {
              var _leftValue6 = left.value;
              var _rightValue6 = right.value;
              if (_types.Types.INTEGER.isCompatible(left.type) || _types.Types.REAL.isCompatible(left.type)) {
                if (shouldImplicitCast) {
                  resultType = _types.Types.BOOLEAN;
                  _leftValue6 = _leftValue6.trunc();
                  _rightValue6 = _rightValue6.trunc();
                }
                result = !_leftValue6.eq(_rightValue6);
              } else {
                result = left.value !== right.value;
              }
              return new _storeObject.StoreObject(resultType, result);
            }
          case _operators.Operators.AND.ord:
            return new _storeObject.StoreObject(resultType, left.value && right.value);
          case _operators.Operators.OR.ord:
            return new _storeObject.StoreObject(resultType, left.value || right.value);
          default:
            return Promise.reject(new _runtimeError.RuntimeError('!!!Critical Invalid InfixApp ' + infixApp.op));
        }
      });
    }
  }, {
    key: 'parseStoreObjectValue',
    value: function parseStoreObjectValue(vl) {
      var realValue = vl;
      if (vl instanceof _storeObjectArrayAddress.StoreObjectArrayAddress) {
        if (vl.type instanceof _compoundType.CompoundType) {
          switch (vl.type.dimensions) {
            case 1:
              {
                realValue = new _storeObjectArray.StoreObjectArray(vl.type, vl.value);
                break;
              }
            default:
              {
                throw new _runtimeError.RuntimeError("Three dimensional array address...");
              }
          }
        } else {
          realValue = new _storeObject.StoreObject(vl.type, vl.value);
        }
      }
      return realValue;
    }
  }]);

  return IVProgProcessor;
}();

/***/ }),

/***/ "./js/processor/lib/arrays.js":
/*!************************************!*\
  !*** ./js/processor/lib/arrays.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createNumElementsFun = createNumElementsFun;
exports.createMatrixLinesFun = createMatrixLinesFun;
exports.createMatrixColumnsFun = createMatrixColumnsFun;

var _storeObject = __webpack_require__(/*! ../store/storeObject */ "./js/processor/store/storeObject.js");

var _commands = __webpack_require__(/*! ./../../ast/commands */ "./js/ast/commands/index.js");

var Commands = _interopRequireWildcard(_commands);

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

var _parsers = __webpack_require__(/*! ./../../typeSystem/parsers */ "./js/typeSystem/parsers.js");

var _compoundType = __webpack_require__(/*! ../../typeSystem/compoundType */ "./js/typeSystem/compoundType.js");

var _modes = __webpack_require__(/*! ../modes */ "./js/processor/modes.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

/**
 * num_elements
 * matrix_lines
 * matrix_columns
 */

function createNumElementsFun() {
  var numElementsFun = function numElementsFun(sto, _) {
    var vector = sto.applyStore("vector");
    var temp = new _storeObject.StoreObject(_types.Types.INTEGER, (0, _parsers.toInt)(vector.lines));
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(numElementsFun)]);
  var func = new Commands.Function('$numElements', _types.Types.INTEGER, [new Commands.FormalParameter(new _compoundType.CompoundType(_types.Types.ALL, 1), 'vector', false)], block);
  return func;
}

function createMatrixLinesFun() {
  var matrixLinesFun = function matrixLinesFun(sto, _) {
    var matrix = sto.applyStore("matrix");
    var temp = new _storeObject.StoreObject(_types.Types.INTEGER, (0, _parsers.toInt)(matrix.lines));
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(matrixLinesFun)]);
  var func = new Commands.Function('$matrixLines', _types.Types.INTEGER, [new Commands.FormalParameter(new _compoundType.CompoundType(_types.Types.ALL, 2), 'matrix', false)], block);
  return func;
}

function createMatrixColumnsFun() {
  var matrixColumnsFun = function matrixColumnsFun(sto, _) {
    var matrix = sto.applyStore("matrix");
    var temp = new _storeObject.StoreObject(_types.Types.INTEGER, (0, _parsers.toInt)(matrix.columns));
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(matrixColumnsFun)]);
  var func = new Commands.Function('$matrixColumns', _types.Types.INTEGER, [new Commands.FormalParameter(new _compoundType.CompoundType(_types.Types.ALL, 2), 'matrix', false)], block);
  return func;
}

/***/ }),

/***/ "./js/processor/lib/io.js":
/*!********************************!*\
  !*** ./js/processor/lib/io.js ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createOutputFun = createOutputFun;
exports.createInputFun = createInputFun;

var _storeObject = __webpack_require__(/*! ./../store/storeObject */ "./js/processor/store/storeObject.js");

var _commands = __webpack_require__(/*! ./../../ast/commands */ "./js/ast/commands/index.js");

var Commands = _interopRequireWildcard(_commands);

var _parsers = __webpack_require__(/*! ./../../typeSystem/parsers */ "./js/typeSystem/parsers.js");

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function createOutputFun() {
  var writeFunction = function writeFunction(store, _) {
    var val = store.applyStore('p1');
    this.output.sendOutput((0, _parsers.convertToString)(val.value, val.type));
    return Promise.resolve(store);
  };
  var block = new Commands.CommandBlock([], [new Commands.SysCall(writeFunction)]);
  var func = new Commands.Function('$write', _types.Types.VOID, [new Commands.FormalParameter(_types.Types.ALL, 'p1', false)], block);
  return func;
}

function createInputFun() {
  var readFunction = function readFunction(store, _) {
    var _this = this;

    var request = new Promise(function (resolve, _) {
      _this.input.requestInput(resolve);
    });
    return request.then(function (text) {
      var typeToConvert = store.applyStore('p1').type;
      var stoObj = null;
      if (typeToConvert.isCompatible(_types.Types.INTEGER)) {
        var val = (0, _parsers.toInt)(text);
        stoObj = new _storeObject.StoreObject(_types.Types.INTEGER, val);
      } else if (typeToConvert.isCompatible(_types.Types.REAL)) {
        stoObj = new _storeObject.StoreObject(_types.Types.REAL, (0, _parsers.toReal)(text));
      } else if (typeToConvert.isCompatible(_types.Types.BOOLEAN)) {
        stoObj = new _storeObject.StoreObject(_types.Types.BOOLEAN, (0, _parsers.toBool)(text));
      } else if (typeToConvert.isCompatible(_types.Types.STRING)) {
        stoObj = new _storeObject.StoreObject(_types.Types.STRING, (0, _parsers.toString)(text));
      }
      _this.loopTimers.splice(0, _this.loopTimers.length);
      store.updateStore('p1', stoObj);
      return Promise.resolve(store);
    });
  };
  var block = new Commands.CommandBlock([], [new Commands.SysCall(readFunction)]);
  var func = new Commands.Function('$read', _types.Types.VOID, [new Commands.FormalParameter(_types.Types.ALL, 'p1', true)], block);
  return func;
}

/***/ }),

/***/ "./js/processor/lib/lang.js":
/*!**********************************!*\
  !*** ./js/processor/lib/lang.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createIsRealFun = createIsRealFun;
exports.createIsIntFun = createIsIntFun;
exports.createIsBoolFun = createIsBoolFun;
exports.createCastRealFun = createCastRealFun;
exports.createCastIntFun = createCastIntFun;
exports.createCastBoolFun = createCastBoolFun;
exports.createCastStringFun = createCastStringFun;

var _storeObject = __webpack_require__(/*! ../store/storeObject */ "./js/processor/store/storeObject.js");

var _commands = __webpack_require__(/*! ./../../ast/commands */ "./js/ast/commands/index.js");

var Commands = _interopRequireWildcard(_commands);

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

var _parsers = __webpack_require__(/*! ./../../typeSystem/parsers */ "./js/typeSystem/parsers.js");

var _ivprogParser = __webpack_require__(/*! ../../ast/ivprogParser */ "./js/ast/ivprogParser.js");

var _expressions = __webpack_require__(/*! ../../ast/expressions */ "./js/ast/expressions/index.js");

var _modes = __webpack_require__(/*! ../modes */ "./js/processor/modes.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

/**
 * 
 * is_real
 * is_int
 * is_bool
 * cast_real
 * cast_int
 * cast_bool
 * cast_string
 */

function createIsRealFun() {
  var isRealFun = function isRealFun(sto, _) {
    var str = sto.applyStore("str");
    var parser = _ivprogParser.IVProgParser.createParser(str.value);
    var result = false;
    try {
      var val = parser.parseTerm();
      if (val instanceof _expressions.RealLiteral) {
        result = true;
      }
    } catch (error) {}
    var temp = new _storeObject.StoreObject(_types.Types.BOOLEAN, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(isRealFun)]);
  var func = new Commands.Function('$isReal', _types.Types.BOOLEAN, [new Commands.FormalParameter(_types.Types.STRING, 'str', false)], block);
  return func;
}

function createIsIntFun() {
  var isIntFun = function isIntFun(sto, _) {
    var str = sto.applyStore("str");
    var parser = _ivprogParser.IVProgParser.createParser(str.value);
    var result = false;
    try {
      var val = parser.parseTerm();
      if (val instanceof _expressions.IntLiteral) {
        result = true;
      }
    } catch (error) {}
    var temp = new _storeObject.StoreObject(_types.Types.BOOLEAN, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(isIntFun)]);
  var func = new Commands.Function('$isInt', _types.Types.BOOLEAN, [new Commands.FormalParameter(_types.Types.STRING, 'str', false)], block);
  return func;
}

function createIsBoolFun() {
  var isBoolFun = function isBoolFun(sto, _) {
    var str = sto.applyStore("str");
    var parser = _ivprogParser.IVProgParser.createParser(str.value);
    var result = false;
    try {
      var val = parser.parseTerm();
      if (val instanceof _expressions.BoolLiteral) {
        result = true;
      }
    } catch (error) {}
    var temp = new _storeObject.StoreObject(_types.Types.BOOLEAN, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(isBoolFun)]);
  var func = new Commands.Function('$isBool', _types.Types.BOOLEAN, [new Commands.FormalParameter(_types.Types.STRING, 'str', false)], block);
  return func;
}

function createCastRealFun() {
  var castRealFun = function castRealFun(sto, _) {
    var val = sto.applyStore("val");
    switch (val.type.ord) {
      case _types.Types.INTEGER.ord:
        {
          var temp = new _storeObject.StoreObject(_types.Types.REAL, (0, _parsers.toReal)(val.number));
          sto.mode = _modes.Modes.RETURN;
          return Promise.resolve(sto.updateStore("$", temp));
        }
      case _types.Types.STRING.ord:
        {
          var parser = _ivprogParser.IVProgParser.createParser(val.value);
          try {
            var result = parser.parseTerm();
            if (result instanceof _expressions.RealLiteral) {
              var _temp = new _storeObject.StoreObject(_types.Types.REAL, result.value);
              sto.mode = _modes.Modes.RETURN;
              return Promise.resolve(sto.updateStore("$", _temp));
            }
          } catch (error) {
            return Promise.reject("cannot convert string to real");
          }
        }
    }
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(castRealFun)]);
  var func = new Commands.Function('$castReal', _types.Types.REAL, [new Commands.FormalParameter(_types.Types.ALL, 'val', false)], block);
  return func;
}

function createCastIntFun() {
  var castIntFun = function castIntFun(sto, _) {
    var val = sto.applyStore("val");
    switch (val.type.ord) {
      case _types.Types.REAL.ord:
        {
          var temp = new _storeObject.StoreObject(_types.Types.INTEGER, Math.floor(val.number));
          sto.mode = _modes.Modes.RETURN;
          return Promise.resolve(sto.updateStore("$", temp));
        }
      case _types.Types.STRING.ord:
        {
          var parser = _ivprogParser.IVProgParser.createParser(val.value);
          try {
            var result = parser.parseTerm();
            if (result instanceof _expressions.IntLiteral) {
              var _temp2 = new _storeObject.StoreObject(_types.Types.INTEGER, result.value);
              sto.mode = _modes.Modes.RETURN;
              return Promise.resolve(sto.updateStore("$", _temp2));
            }
          } catch (error) {
            return Promise.reject("cannot convert string to real");
          }
        }
    }
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(castIntFun)]);
  var func = new Commands.Function('$castInt', _types.Types.INTEGER, [new Commands.FormalParameter(_types.Types.ALL, 'val', false)], block);
  return func;
}

function createCastBoolFun() {
  var castBoolFun = function castBoolFun(sto, _) {
    var str = sto.applyStore("str");
    var parser = _ivprogParser.IVProgParser.createParser(str.value);
    try {
      var val = parser.parseTerm();
      if (val instanceof _expressions.BoolLiteral) {
        var temp = new _storeObject.StoreObject(_types.Types.BOOLEAN, val.value);
        sto.mode = _modes.Modes.RETURN;
        return Promise.resolve(sto.updateStore("$", temp));
      }
    } catch (error) {}
    return Promise.reject("cannot convert " + str.value + " to boolean");
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(castBoolFun)]);
  var func = new Commands.Function('$castBool', _types.Types.BOOLEAN, [new Commands.FormalParameter(_types.Types.STRING, 'str', false)], block);
  return func;
}

function createCastStringFun() {
  var castStringFun = function castStringFun(store, _) {
    var val = store.applyStore('str');
    var result = (0, _parsers.convertToString)(val);
    var temp = new _storeObject.StoreObject(_types.Types.STRING, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };
  var block = new Commands.CommandBlock([], [new Commands.SysCall(castStringFun)]);
  var func = new Commands.Function('$castString', _types.Types.STRING, [new Commands.FormalParameter(_types.Types.ALL, 'str', false)], block);
  return func;
}

/***/ }),

/***/ "./js/processor/lib/math.js":
/*!**********************************!*\
  !*** ./js/processor/lib/math.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createSinFun = createSinFun;
exports.createCosFun = createCosFun;
exports.createTanFun = createTanFun;
exports.createSqrtFun = createSqrtFun;
exports.createPowFun = createPowFun;
exports.createLogFun = createLogFun;
exports.createAbsFun = createAbsFun;
exports.createNegateFun = createNegateFun;
exports.createInvertFun = createInvertFun;
exports.createMaxFun = createMaxFun;
exports.createMinFun = createMinFun;

var _storeObject = __webpack_require__(/*! ../store/storeObject */ "./js/processor/store/storeObject.js");

var _commands = __webpack_require__(/*! ./../../ast/commands */ "./js/ast/commands/index.js");

var Commands = _interopRequireWildcard(_commands);

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

var _parsers = __webpack_require__(/*! ./../../typeSystem/parsers */ "./js/typeSystem/parsers.js");

var _decimal = __webpack_require__(/*! decimal.js */ "./node_modules/decimal.js/decimal.js");

var _multiType = __webpack_require__(/*! ../../typeSystem/multiType */ "./js/typeSystem/multiType.js");

var _compoundType = __webpack_require__(/*! ../../typeSystem/compoundType */ "./js/typeSystem/compoundType.js");

var _modes = __webpack_require__(/*! ../modes */ "./js/processor/modes.js");

var _config = __webpack_require__(/*! ../../util/config */ "./js/util/config.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

/**
 * sin
 * cos
 * tan
 * sqrt
 * pow
 * log
 * abs
 * negate
 * invert
 * max
 * min
 */

function convertToRadians(degrees) {
  return degrees.times(_decimal.Decimal.acos(-1)).div(180);
}

function createSinFun() {
  var sinFun = function sinFun(sto, _) {
    var x = sto.applyStore('x');
    var angle = x.value.mod(360);
    var result = null;
    if (angle.eq(90)) {
      result = new _decimal.Decimal(1);
    } else if (angle.eq(180)) {
      result = new _decimal.Decimal(0);
    } else if (angle.eq(270)) {
      result = new _decimal.Decimal(-1);
    } else {
      result = _decimal.Decimal.sin(convertToRadians(angle));
    }
    if (result.dp() > _config.Config.decimalPlaces) {
      result = new _decimal.Decimal(result.toFixed(_config.Config.decimalPlaces));
    }
    var temp = new _storeObject.StoreObject(_types.Types.REAL, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(sinFun)]);
  var func = new Commands.Function('$sin', _types.Types.REAL, [new Commands.FormalParameter(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 'x', false)], block);
  return func;
}

function createCosFun() {
  var cosFun = function cosFun(sto, _) {
    var x = sto.applyStore('x');
    var angle = x.value.mod(360);
    var result = null;
    if (angle.eq(90)) {
      result = new _decimal.Decimal(0);
    } else if (angle.eq(180)) {
      result = new _decimal.Decimal(-1);
    } else if (angle.eq(270)) {
      result = new _decimal.Decimal(0);
    }
    result = _decimal.Decimal.cos(convertToRadians(angle));
    if (result.dp() > _config.Config.decimalPlaces) {
      result = new _decimal.Decimal(result.toFixed(_config.Config.decimalPlaces));
    }
    var temp = new _storeObject.StoreObject(_types.Types.REAL, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(cosFun)]);
  var func = new Commands.Function('$cos', _types.Types.REAL, [new Commands.FormalParameter(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 'x', false)], block);
  return func;
}

function createTanFun() {
  var tanFun = function tanFun(sto, _) {
    var x = sto.applyStore('x');
    var angle = x.value.mod(360);
    if (angle.eq(90) || angle.eq(270)) {
      return Promise.reject("Tangent of " + x.value.toNumber() + "° is undefined.");
    }
    var result = _decimal.Decimal.tan(convertToRadians(angle));
    if (result.dp() > _config.Config.decimalPlaces) {
      result = new _decimal.Decimal(result.toFixed(_config.Config.decimalPlaces));
    }
    var temp = new _storeObject.StoreObject(_types.Types.REAL, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(tanFun)]);
  var func = new Commands.Function('$tan', _types.Types.REAL, [new Commands.FormalParameter(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 'x', false)], block);
  return func;
}

function createSqrtFun() {
  var sqrtFun = function sqrtFun(sto, _) {
    var x = sto.applyStore('x');
    var result = x.value.sqrt();
    if (result.dp() > _config.Config.decimalPlaces) {
      result = new _decimal.Decimal(result.toFixed(_config.Config.decimalPlaces));
    }
    var temp = new _storeObject.StoreObject(_types.Types.REAL, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(sqrtFun)]);
  var func = new Commands.Function('$sqrt', _types.Types.REAL, [new Commands.FormalParameter(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 'x', false)], block);
  return func;
}

function createPowFun() {
  var powFun = function powFun(sto, _) {
    var x = sto.applyStore('x');
    var y = sto.applyStore('y');
    var result = x.value.pow(y.value);
    if (result.dp() > _config.Config.decimalPlaces) {
      result = new _decimal.Decimal(result.toFixed(_config.Config.decimalPlaces));
    }
    var temp = new _storeObject.StoreObject(_types.Types.REAL, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(powFun)]);
  var func = new Commands.Function('$pow', _types.Types.REAL, [new Commands.FormalParameter(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 'x', false), new Commands.FormalParameter(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 'y', false)], block);
  return func;
}

function createLogFun() {
  var logFun = function logFun(sto, _) {
    var x = sto.applyStore('x');
    if (x.value.isNegative()) {
      return Promise.reject("the value passed to log function cannot be negative");
    }
    var result = _decimal.Decimal.log10(x.value);
    if (result.dp() > _config.Config.decimalPlaces) {
      result = new _decimal.Decimal(result.toFixed(_config.Config.decimalPlaces));
    }
    var temp = new _storeObject.StoreObject(_types.Types.REAL, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(logFun)]);
  var func = new Commands.Function('$log', _types.Types.REAL, [new Commands.FormalParameter(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 'x', false)], block);
  return func;
}

function createAbsFun() {
  var absFun = function absFun(sto, _) {
    var x = sto.applyStore('x');
    var result = x.value.abs();
    var temp = new _storeObject.StoreObject(x.type, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(absFun)]);
  var func = new Commands.Function('$abs', new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), [new Commands.FormalParameter(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 'x', false)], block);
  return func;
}

function createNegateFun() {
  var negateFun = function negateFun(sto, _) {
    var x = sto.applyStore('x');
    var result = x.value.negated();
    var temp = new _storeObject.StoreObject(x.type, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(negateFun)]);
  var func = new Commands.Function('$negate', new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), [new Commands.FormalParameter(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 'x', false)], block);
  return func;
}

function createInvertFun() {
  var invertFun = function invertFun(sto, _) {
    var x = sto.applyStore('x');
    var result = (0, _parsers.toReal)(1).dividedBy(x.value);
    if (result.dp() > _config.Config.decimalPlaces) {
      result = new _decimal.Decimal(result.toFixed(_config.Config.decimalPlaces));
    }
    var temp = new _storeObject.StoreObject(_types.Types.REAL, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(invertFun)]);
  var func = new Commands.Function('$invert', _types.Types.REAL, [new Commands.FormalParameter(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 'x', false)], block);
  return func;
}

function createMaxFun() {
  var maxFun = function maxFun(sto, _) {
    var x = sto.applyStore('x');
    var numbers = x.value.map(function (stoObj) {
      return stoObj.value;
    });
    var result = _decimal.Decimal.max.apply(_decimal.Decimal, _toConsumableArray(numbers));
    var temp = new _storeObject.StoreObject(x.type.innerType, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };
  var paramType = new _compoundType.CompoundType(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 1);
  var block = new Commands.CommandBlock([], [new Commands.SysCall(maxFun)]);
  var func = new Commands.Function('$max', new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), [new Commands.FormalParameter(paramType, 'x', false)], block);
  return func;
}

function createMinFun() {
  var minFun = function minFun(sto, _) {
    var x = sto.applyStore('x');
    var numbers = x.value.map(function (stoObj) {
      return stoObj.value;
    });
    var result = _decimal.Decimal.min.apply(_decimal.Decimal, _toConsumableArray(numbers));
    var temp = new _storeObject.StoreObject(x.type.innerType, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore('$', temp));
  };
  var paramType = new _compoundType.CompoundType(new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), 1);
  var block = new Commands.CommandBlock([], [new Commands.SysCall(minFun)]);
  var func = new Commands.Function('$min', new _multiType.MultiType([_types.Types.INTEGER, _types.Types.REAL]), [new Commands.FormalParameter(paramType, 'x', false)], block);
  return func;
}

/***/ }),

/***/ "./js/processor/lib/strings.js":
/*!*************************************!*\
  !*** ./js/processor/lib/strings.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createSubstringFun = createSubstringFun;
exports.createLengthFun = createLengthFun;
exports.createUppercaseFun = createUppercaseFun;
exports.createLowercaseFun = createLowercaseFun;
exports.createrCharAtFun = createrCharAtFun;

var _storeObject = __webpack_require__(/*! ../store/storeObject */ "./js/processor/store/storeObject.js");

var _commands = __webpack_require__(/*! ./../../ast/commands */ "./js/ast/commands/index.js");

var Commands = _interopRequireWildcard(_commands);

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

var _parsers = __webpack_require__(/*! ./../../typeSystem/parsers */ "./js/typeSystem/parsers.js");

var _modes = __webpack_require__(/*! ../modes */ "./js/processor/modes.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

/*
*  substring
*  length
*  uppercase
*  lowercase
*  charAt
**/

function createSubstringFun() {
  var substringFun = function substringFun(sto, _) {
    var str = sto.applyStore("str");
    var start = sto.applyStore("start");
    var end = sto.applyStore("end");
    var result = str.value.substring(start.value, end.value);
    var temp = new _storeObject.StoreObject(_types.Types.STRING, result);
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };

  var block = new Commands.CommandBlock([], [new Commands.SysCall(substringFun)]);
  var func = new Commands.Function('$substring', _types.Types.STRING, [new Commands.FormalParameter(_types.Types.STRING, 'str', false), new Commands.FormalParameter(_types.Types.INTEGER, 'start', false), new Commands.FormalParameter(_types.Types.INTEGER, 'end', false)], block);
  return func;
}

function createLengthFun() {
  var lengthFun = function lengthFun(sto, _) {
    var str = sto.applyStore("str");
    var temp = new _storeObject.StoreObject(_types.Types.INTEGER, (0, _parsers.toInt)(str.value.length));
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };
  var block = new Commands.CommandBlock([], [new Commands.SysCall(lengthFun)]);
  var func = new Commands.Function('$length', _types.Types.INTEGER, [new Commands.FormalParameter(_types.Types.STRING, 'str', false)], block);
  return func;
}

function createUppercaseFun() {
  var uppercaseFun = function uppercaseFun(sto, _) {
    var str = sto.applyStore("str");
    var temp = new _storeObject.StoreObject(_types.Types.STRING, str.value.toUpperCase());
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };
  var block = new Commands.CommandBlock([], [new Commands.SysCall(uppercaseFun)]);
  var func = new Commands.Function('$uppercase', _types.Types.STRING, [new Commands.FormalParameter(_types.Types.STRING, 'str', false)], block);
  return func;
}

function createLowercaseFun() {
  var lowercaseFun = function lowercaseFun(sto, _) {
    var str = sto.applyStore("str");
    var temp = new _storeObject.StoreObject(_types.Types.STRING, str.value.toLowerCase());
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };
  var block = new Commands.CommandBlock([], [new Commands.SysCall(lowercaseFun)]);
  var func = new Commands.Function('$lowercase', _types.Types.STRING, [new Commands.FormalParameter(_types.Types.STRING, 'str', false)], block);
  return func;
}

function createrCharAtFun() {
  var charAtFun = function charAtFun(sto, _) {
    var str = sto.applyStore("str");
    var idx = sto.applyStore("index");
    if (idx.value.toNumber() < 0 || idx.value.toNumber() >= str.value.length) {
      return Promise.reject(new Error("invalid string position"));
    }
    var temp = new _storeObject.StoreObject(_types.Types.STRING, str.value.charAt(idx.value.toNumber()));
    sto.mode = _modes.Modes.RETURN;
    return Promise.resolve(sto.updateStore("$", temp));
  };
  var block = new Commands.CommandBlock([], [new Commands.SysCall(charAtFun)]);
  var func = new Commands.Function('$charAt', _types.Types.STRING, [new Commands.FormalParameter(_types.Types.STRING, 'str', false), new Commands.FormalParameter(_types.Types.INTEGER, 'index', false)], block);
  return func;
}

/***/ }),

/***/ "./js/processor/modes.js":
/*!*******************************!*\
  !*** ./js/processor/modes.js ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var Modes = exports.Modes = Object.freeze({
  RETURN: Symbol('mode:return'),
  BREAK: Symbol('mode:break'),
  PAUSE: Symbol('mode:pause'),
  RUN: Symbol('mode:run')
});

/***/ }),

/***/ "./js/processor/semantic/semanticAnalyser.js":
/*!***************************************************!*\
  !*** ./js/processor/semantic/semanticAnalyser.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SemanticAnalyser = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _processorErrorFactory = __webpack_require__(/*! ./../error/processorErrorFactory */ "./js/processor/error/processorErrorFactory.js");

var _definedFunctions = __webpack_require__(/*! ./../definedFunctions */ "./js/processor/definedFunctions.js");

var _languageService = __webpack_require__(/*! ./../../services/languageService */ "./js/services/languageService.js");

var _commands = __webpack_require__(/*! ../../ast/commands */ "./js/ast/commands/index.js");

var _expressions = __webpack_require__(/*! ../../ast/expressions */ "./js/ast/expressions/index.js");

var _literal = __webpack_require__(/*! ../../ast/expressions/literal */ "./js/ast/expressions/literal.js");

var _compatibilityTable = __webpack_require__(/*! ../compatibilityTable */ "./js/processor/compatibilityTable.js");

var _types = __webpack_require__(/*! ../../typeSystem/types */ "./js/typeSystem/types.js");

var _compoundType = __webpack_require__(/*! ../../typeSystem/compoundType */ "./js/typeSystem/compoundType.js");

var _multiType = __webpack_require__(/*! ../../typeSystem/multiType */ "./js/typeSystem/multiType.js");

var _config = __webpack_require__(/*! ../../util/config */ "./js/util/config.js");

var _store = __webpack_require__(/*! ../store/store */ "./js/processor/store/store.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var SemanticAnalyser = exports.SemanticAnalyser = function () {
  function SemanticAnalyser(ast) {
    _classCallCheck(this, SemanticAnalyser);

    this.ast = ast;
    this.lexerClass = _languageService.LanguageService.getCurrentLexer();
    var lexer = new this.lexerClass(null);
    this.literalNames = lexer.literalNames;
    this.symbolMap = null;
    this.currentFunction = null;
  }

  _createClass(SemanticAnalyser, [{
    key: 'pushMap',
    value: function pushMap() {
      if (this.symbolMap === null) {
        this.symbolMap = { map: {}, next: null };
      } else {
        var n = { map: {}, next: this.symbolMap };
        this.symbolMap = n;
      }
    }
  }, {
    key: 'popMap',
    value: function popMap() {
      if (this.symbolMap !== null) {
        this.symbolMap = this.symbolMap.next;
      }
    }
  }, {
    key: 'insertSymbol',
    value: function insertSymbol(id, typeInfo) {
      this.symbolMap.map[id] = typeInfo;
    }
  }, {
    key: 'findSymbol',
    value: function findSymbol(id, symMap) {
      if (!symMap.map[id]) {
        if (symMap.next) {
          return this.findSymbol(id, symMap.next);
        }
        return null;
      } else {
        return symMap.map[id];
      }
    }
  }, {
    key: 'getMainFunction',
    value: function getMainFunction() {
      return this.ast.functions.find(function (v) {
        return v.isMain;
      });
    }
  }, {
    key: 'findFunction',
    value: function findFunction(name) {
      console.log(name);
      if (name.match(/^\$.+$/)) {
        var fun = _definedFunctions.LanguageDefinedFunction.getFunction(name);
        if (!!!fun) {
          throw _processorErrorFactory.ProcessorErrorFactory.not_implemented(name);
        }
        return fun;
      } else {
        var val = this.ast.functions.find(function (v) {
          return v.name === name;
        });
        if (!!!val) {
          return null;
        }
        return val;
      }
    }
  }, {
    key: 'analyseTree',
    value: function analyseTree() {
      var globalVars = this.ast.global;
      this.pushMap();
      this.assertDeclarations(globalVars);
      var functions = this.ast.functions;
      var mainFunc = functions.filter(function (f) {
        return f.name === null;
      });
      if (mainFunc.length <= 0) {
        throw _processorErrorFactory.ProcessorErrorFactory.main_missing();
      }
      for (var i = 0; i < functions.length; i++) {
        var fun = functions[i];
        this.assertFunction(fun);
      }
      return this.ast;
    }
  }, {
    key: 'assertDeclarations',
    value: function assertDeclarations(list) {
      for (var i = 0; i < list.length; i++) {
        this.assertDeclaration(list[i]);
      }
    }
  }, {
    key: 'assertDeclaration',
    value: function assertDeclaration(declaration) {
      if (declaration instanceof _commands.ArrayDeclaration) {
        if (declaration.initial === null) {
          var lineType = this.evaluateExpressionType(declaration.lines);
          if (!lineType.isCompatible(_types.Types.INTEGER)) {
            throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(declaration.sourceInfo);
          }
          if (declaration.columns !== null) {
            var columnType = this.evaluateExpressionType(declaration.columns);
            if (!columnType.isCompatible(_types.Types.INTEGER)) {
              throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(declaration.sourceInfo);
            }
          }
          this.insertSymbol(declaration.id, { id: declaration.id, lines: declaration.lines, columns: declaration.columns, type: declaration.type });
          return;
        }
        this.evaluateArrayLiteral(declaration.id, declaration.lines, declaration.columns, declaration.type, declaration.initial);
        this.insertSymbol(declaration.id, { id: declaration.id, lines: declaration.lines, columns: declaration.columns, type: declaration.type });
      } else {
        if (declaration.initial === null) {
          this.insertSymbol(declaration.id, { id: declaration.id, type: declaration.type });
          return;
        }
        var resultType = this.evaluateExpressionType(declaration.initial);
        if (resultType instanceof _multiType.MultiType) {
          if (!resultType.isCompatible(declaration.type)) {
            var stringInfo = declaration.type.stringInfo();
            var info = stringInfo[0];
            throw _processorErrorFactory.ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, declaration.sourceInfo);
          }
          this.insertSymbol(declaration.id, { id: declaration.id, type: declaration.type });
        } else if (!declaration.type.isCompatible(resultType) && !_config.Config.enable_type_casting || !declaration.type.isCompatible(resultType) && _config.Config.enable_type_casting && !_store.Store.canImplicitTypeCast(declaration.type, resultType)) {
          var _stringInfo = declaration.type.stringInfo();
          var _info = _stringInfo[0];
          throw _processorErrorFactory.ProcessorErrorFactory.incompatible_types_full(_info.type, _info.dim, declaration.sourceInfo);
        } else {
          this.insertSymbol(declaration.id, { id: declaration.id, type: declaration.type });
        }
      }
    }
  }, {
    key: 'evaluateExpressionType',
    value: function evaluateExpressionType(expression) {
      if (expression instanceof _expressions.UnaryApp) {
        var op = expression.op;
        var resultType = this.evaluateExpressionType(expression.left);
        return (0, _compatibilityTable.resultTypeAfterUnaryOp)(op, resultType);
      } else if (expression instanceof _expressions.InfixApp) {
        var _op = expression.op;
        var resultTypeLeft = this.evaluateExpressionType(expression.left);
        var resultTypeRight = this.evaluateExpressionType(expression.right);
        return (0, _compatibilityTable.resultTypeAfterInfixOp)(_op, resultTypeLeft, resultTypeRight);
      } else if (expression instanceof _literal.Literal) {
        return this.evaluateLiteralType(expression);
      } else if (expression instanceof _expressions.FunctionCall) {
        if (expression.isMainCall) {
          throw _processorErrorFactory.ProcessorErrorFactory.void_in_expression_full(_definedFunctions.LanguageDefinedFunction.getMainFunctionName(), expression.sourceInfo);
        }
        var fun = this.findFunction(expression.id);
        if (fun === null) {
          throw _processorErrorFactory.ProcessorErrorFactory.function_missing_full(expression.id, expression.sourceInfo);
        }
        if (fun.returnType.isCompatible(_types.Types.VOID)) {
          throw _processorErrorFactory.ProcessorErrorFactory.void_in_expression_full(expression.id, expression.sourceInfo);
        }
        this.assertParameters(fun, expression.actualParameters);
        return fun.returnType;
      } else if (expression instanceof _expressions.ArrayAccess) {
        var arrayTypeInfo = this.findSymbol(expression.id, this.symbolMap);
        if (arrayTypeInfo === null) {
          throw _processorErrorFactory.ProcessorErrorFactory.symbol_not_found_full(expression.id, expression.sourceInfo);
        }
        if (!(arrayTypeInfo.type instanceof _compoundType.CompoundType)) {
          throw _processorErrorFactory.ProcessorErrorFactory.invalid_array_access_full(expression.id, expression.sourceInfo);
        }
        var lineType = this.evaluateExpressionType(expression.line);
        if (!lineType.isCompatible(_types.Types.INTEGER)) {
          throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(expression.sourceInfo);
        }
        if (expression.column !== null) {
          if (arrayTypeInfo.columns === null) {
            throw _processorErrorFactory.ProcessorErrorFactory.invalid_matrix_access_full(expression.id, expression.sourceInfo);
          }
          var columnType = this.evaluateExpressionType(expression.column);
          if (!columnType.isCompatible(_types.Types.INTEGER)) {
            throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(expression.sourceInfo);
          }
        }
        var arrType = arrayTypeInfo.type;
        if (expression.column !== null) {
          // indexing matrix
          return arrType.innerType;
        } else {
          if (arrayTypeInfo.columns === null) {
            return arrType.innerType;
          }
          return new _compoundType.CompoundType(arrType.innerType, 1);
        }
      }
    }
  }, {
    key: 'evaluateLiteralType',
    value: function evaluateLiteralType(literal) {
      if (literal instanceof _expressions.IntLiteral) {
        return literal.type;
      } else if (literal instanceof _expressions.RealLiteral) {
        return literal.type;
      } else if (literal instanceof _expressions.StringLiteral) {
        return literal.type;
      } else if (literal instanceof _expressions.BoolLiteral) {
        return literal.type;
      } else if (literal instanceof _expressions.VariableLiteral) {
        var typeInfo = this.findSymbol(literal.id, this.symbolMap);
        if (typeInfo === null) {
          throw _processorErrorFactory.ProcessorErrorFactory.symbol_not_found_full(literal.id, literal.sourceInfo);
        }
        if (typeInfo.type instanceof _compoundType.CompoundType) {
          return typeInfo.type;
        }
        return typeInfo.type;
      } else {
        console.warn("Evaluating type only for an array literal...");
        var last = null;
        if (literal.value.length === 1) {
          last = this.evaluateExpressionType(literal.value[0]);
        } else {
          for (var i = 0; i < literal.value.length; i++) {
            var e = this.evaluateExpressionType(literal.value[i]);
            if (last === null) {
              last = e;
            } else if (!last.isCompatible(e)) {
              var strInfo = last.stringInfo();
              var info = strInfo[0];
              var strExp = literal.toString();
              throw _processorErrorFactory.ProcessorErrorFactory.incompatible_types_array_full(strExp, info.type, info.dim, literal.sourceInfo);
            }
          }
        }
        if (last instanceof _compoundType.CompoundType) {
          return new _compoundType.CompoundType(last.innerType, last.dimensions + 1);
        }
        return new _compoundType.CompoundType(last, 1);
      }
    }
  }, {
    key: 'evaluateArrayLiteral',
    value: function evaluateArrayLiteral(id, lines, columns, type, literal) {
      /* if (literal instanceof ArrayLiteral) {
        const dimType = this.evaluateExpressionType(lines);
        if (!dimType.isCompatible(Types.INTEGER)) {
          throw ProcessorErrorFactory.array_dimension_not_int_full(literal.sourceInfo);
        }
        if ((lines instanceof IntLiteral)) {
          if (!lines.value.eq(literal.value.length)) {
            if(type.dimensions > 1) {
              throw ProcessorErrorFactory.matrix_line_outbounds_full(id, literal.value.length, lines.value.toNumber(), literal.sourceInfo)
            } else {
              throw ProcessorErrorFactory.vector_line_outbounds_full(id, literal.value.length, lines.value.toNumber(), literal.sourceInfo)
            }
          } else if (lines.value.isNeg()) {
            throw ProcessorErrorFactory.array_dimension_not_positive_full(literal.sourceInfo);
          }
        }
        if (columns === null) {
          // it's a vector...
          literal.value.reduce((last, next) => {
            const eType = this.evaluateExpressionType(next);
            if (!last.canAccept(eType)) {
              const strInfo = last.stringInfo();
              const info = strInfo[0];
              const strExp = literal.toString();
              throw ProcessorErrorFactory.incompatible_types_array_full(strExp,info.type, info.dim, literal.sourceInfo);
            }
            return last;
          }, type);
          return true;
        } else {
          const dimType = this.evaluateExpressionType(columns);
          if (!dimType.isCompatible(Types.INTEGER)) {
            throw ProcessorErrorFactory.array_dimension_not_int_full(literal.sourceInfo);
          }
          if ((columns instanceof IntLiteral)) {
            const columnValue = literal.value[0].value.length;
            if (!columns.value.eq(columnValue)) {
              if(type.dimensions > 1) {
                throw ProcessorErrorFactory.matrix_column_outbounds_full(id, literal.value.length, columns.value.toNumber(), literal.sourceInfo)
              } else {
                throw ProcessorErrorFactory.invalid_matrix_access_full(id, literal.sourceInfo);
              }
            } else if (columns.value.isNeg()) {
              throw ProcessorErrorFactory.array_dimension_not_positive_full(literal.sourceInfo);
            }
            for (let i = 0; i < columns; i++) {
              const anotherArray = literal.value[i];
              this.evaluateArrayLiteral(id, columns, null, type, anotherArray)
            }
          }
        }
       } else {
         const resultType = this.evaluateExpressionType(literal);
        if (!(resultType instanceof CompoundType)) {
          const strInfo = type.stringInfo();
          const info = strInfo[0];
          const strExp = literal.toString();
          throw ProcessorErrorFactory.incompatible_types_array_full(strExp,info.type, info.dim, literal.sourceInfo);
        }
        if (!type.isCompatible(resultType)) {
          const strInfo = type.stringInfo();
          const info = strInfo[0];
          const strExp = literal.toString();
          throw ProcessorErrorFactory.incompatible_types_array_full(strExp,info.type, info.dim, literal.sourceInfo);
        }
        return true;
      } */
      return true;
    }
  }, {
    key: 'assertFunction',
    value: function assertFunction(fun) {
      var _this = this;

      this.pushMap();
      this.currentFunction = fun;
      fun.formalParameters.forEach(function (formalParam) {
        if (formalParam.type instanceof _compoundType.CompoundType) {
          if (formalParam.type.dimensions > 1) {
            _this.insertSymbol(formalParam.id, { id: formalParam.id, lines: -1, columns: -1, type: formalParam.type });
          } else {
            _this.insertSymbol(formalParam.id, { id: formalParam.id, lines: -1, columns: null, type: formalParam.type });
          }
        } else {
          _this.insertSymbol(formalParam.id, { id: formalParam.id, type: formalParam.type });
        }
      });
      this.assertDeclarations(fun.variablesDeclarations);
      var optional = fun.returnType.isCompatible(_types.Types.VOID);
      var valid = this.assertReturn(fun, optional);
      if (!valid) {
        throw _processorErrorFactory.ProcessorErrorFactory.function_no_return(fun.name);
      }
      this.popMap();
    }
  }, {
    key: 'assertReturn',
    value: function assertReturn(fun, optional) {
      var _this2 = this;

      return fun.commands.reduce(function (last, next) {
        return _this2.checkCommand(fun.returnType, next, optional) || last;
      }, optional);
    }
  }, {
    key: 'checkCommand',
    value: function checkCommand(type, cmd, optional) {
      if (cmd instanceof _commands.While) {
        var resultType = this.evaluateExpressionType(cmd.expression);
        if (!resultType.isCompatible(_types.Types.BOOLEAN)) {
          throw _processorErrorFactory.ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo);
        }
        this.checkCommands(type, cmd.commands, optional);
        return false;
      } else if (cmd instanceof _commands.For) {
        this.checkCommand(type, cmd.assignment, optional);
        var _resultType = this.evaluateExpressionType(cmd.condition);
        if (!_resultType.isCompatible(_types.Types.BOOLEAN)) {
          throw _processorErrorFactory.ProcessorErrorFactory.for_condition_type_full(cmd.sourceInfo);
        }
        this.checkCommand(type, cmd.increment, optional);
        this.checkCommands(type, cmd.commands, optional);
        return false;
      } else if (cmd instanceof _commands.Switch) {
        var sType = this.evaluateExpressionType(cmd.expression);
        var result = optional;
        var hasDefault = false;
        for (var i = 0; i < cmd.cases.length; i++) {
          var aCase = cmd.cases[i];
          if (aCase.expression !== null) {
            var caseType = this.evaluateExpressionType(aCase.expression);
            if (!sType.isCompatible(caseType)) {
              var strInfo = sType.stringInfo();
              var info = strInfo[0];
              var strExp = aCase.expression.toString();
              throw _processorErrorFactory.ProcessorErrorFactory.invalid_case_type_full(strExp, info.type, info.dim, aCase.sourceInfo);
            }
          } else {
            hasDefault = true;
          }
          result = result && this.checkCommands(type, aCase.commands, result);
        }
        return result && hasDefault;
      } else if (cmd instanceof _commands.ArrayIndexAssign) {
        var typeInfo = this.findSymbol(cmd.id, this.symbolMap);
        if (typeInfo === null) {
          throw _processorErrorFactory.ProcessorErrorFactory.symbol_not_found_full(cmd.id, cmd.sourceInfo);
        }
        if (!(typeInfo.type instanceof _compoundType.CompoundType)) {
          throw _processorErrorFactory.ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo);
        }
        var exp = cmd.expression;
        var lineExp = cmd.line;
        var lineType = this.evaluateExpressionType(lineExp);
        if (!lineType.isCompatible(_types.Types.INTEGER)) {
          throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo);
        }
        var columnExp = cmd.column;
        if (typeInfo.columns === null && columnExp !== null) {
          throw _processorErrorFactory.ProcessorErrorFactory.invalid_matrix_access_full(cmd.id, cmd.sourceInfo);
        } else if (columnExp !== null) {
          var columnType = this.evaluateExpressionType(columnExp);
          if (!columnType.isCompatible(_types.Types.INTEGER)) {
            throw _processorErrorFactory.ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo);
          }
        }
        // exp can be a arrayLiteral, a single value exp or an array access
        if (exp instanceof _expressions.ArrayLiteral) {
          this.evaluateArrayLiteral(cmd.id, typeInfo.lines, columnExp ? typeInfo.columns : null, typeInfo.type, exp);
        } else {
          // cannot properly evaluate since type system is poorly constructed
        }
        return optional;
      } else if (cmd instanceof _commands.Assign) {
        var _typeInfo = this.findSymbol(cmd.id, this.symbolMap);
        if (_typeInfo === null) {
          throw _processorErrorFactory.ProcessorErrorFactory.symbol_not_found_full(cmd.id, cmd.sourceInfo);
        }
        var _exp = cmd.expression;
        if (_exp instanceof _expressions.ArrayLiteral) {
          if (!(_typeInfo.type instanceof _compoundType.CompoundType)) {
            var stringInfo = _typeInfo.type.stringInfo();
            var _info2 = stringInfo[0];
            throw _processorErrorFactory.ProcessorErrorFactory.incompatible_types_full(_info2.type, _info2.dim, cmd.sourceInfo);
          }
          this.evaluateArrayLiteral(cmd.id, _typeInfo.lines, _typeInfo.columns, _typeInfo.type, _exp);
        } else {
          var _resultType2 = this.evaluateExpressionType(_exp);
          if (!_resultType2.isCompatible(_typeInfo.type) && !_config.Config.enable_type_casting || !_resultType2.isCompatible(_typeInfo.type) && _config.Config.enable_type_casting && !_store.Store.canImplicitTypeCast(_typeInfo.type, _resultType2)) {
            var _stringInfo2 = _typeInfo.type.stringInfo();
            var _info3 = _stringInfo2[0];
            throw _processorErrorFactory.ProcessorErrorFactory.incompatible_types_full(_info3.type, _info3.dim, cmd.sourceInfo);
          }
        }
        return optional;
      } else if (cmd instanceof _commands.Break) {
        return optional;
      } else if (cmd instanceof _commands.IfThenElse) {
        var _resultType3 = this.evaluateExpressionType(cmd.condition);
        if (!_resultType3.isCompatible(_types.Types.BOOLEAN)) {
          throw _processorErrorFactory.ProcessorErrorFactory.if_condition_type_full(cmd.sourceInfo);
        }
        if (cmd.ifFalse instanceof _commands.IfThenElse) {
          return this.checkCommands(type, cmd.ifTrue.commands, optional) && this.checkCommand(type, cmd.ifFalse, optional);
        } else {
          return this.checkCommands(type, cmd.ifTrue.commands, optional) && this.checkCommands(type, cmd.ifFalse.commands, optional);
        }
      } else if (cmd instanceof _expressions.FunctionCall) {
        var fun = null;
        if (cmd.isMainCall) {
          fun = this.getMainFunction();
        } else {
          fun = this.findFunction(cmd.id);
        }
        if (fun === null) {
          throw _processorErrorFactory.ProcessorErrorFactory.function_missing_full(cmd.id, cmd.sourceInfo);
        }
        this.assertParameters(fun, cmd.actualParameters);
        return optional;
      } else if (cmd instanceof _commands.Return) {
        var funcName = this.currentFunction.isMain ? _definedFunctions.LanguageDefinedFunction.getMainFunctionName() : this.currentFunction.name;
        if (cmd.expression === null && !type.isCompatible(_types.Types.VOID)) {
          var _stringInfo3 = type.stringInfo();
          var _info4 = _stringInfo3[0];
          throw _processorErrorFactory.ProcessorErrorFactory.invalid_void_return_full(funcName, _info4.type, _info4.dim, cmd.sourceInfo);
        } else if (cmd.expression !== null) {
          var _resultType4 = this.evaluateExpressionType(cmd.expression);
          if (!type.isCompatible(_resultType4)) {
            var _stringInfo4 = type.stringInfo();
            var _info5 = _stringInfo4[0];
            throw _processorErrorFactory.ProcessorErrorFactory.invalid_return_type_full(funcName, _info5.type, _info5.dim, cmd.sourceInfo);
          } else {
            return true;
          }
        } else {
          return true;
        }
      }
    }
  }, {
    key: 'checkCommands',
    value: function checkCommands(type, cmds, optional) {
      var _this3 = this;

      return cmds.reduce(function (last, next) {
        return _this3.checkCommand(type, next, optional) || last;
      }, optional);
    }
  }, {
    key: 'assertParameters',
    value: function assertParameters(fun, actualParametersList) {
      if (fun.formalParameters.length !== actualParametersList.length) {
        throw _processorErrorFactory.ProcessorErrorFactory.invalid_parameters_size_full(fun.name, actualParametersList.length, fun.formalParameters.length, null);
      }
      for (var i = 0; i < actualParametersList.length; i++) {
        var param = actualParametersList[i];
        var formalParam = fun.formalParameters[i];
        var id = formalParam.id;
        if (formalParam.byRef) {
          if (!(param instanceof _expressions.VariableLiteral || param instanceof _expressions.ArrayAccess)) {
            throw _processorErrorFactory.ProcessorErrorFactory.invalid_parameter_type_full(id, param.toString(), param.sourceInfo);
          }
        }
        var resultType = this.evaluateExpressionType(param);
        if (resultType instanceof _multiType.MultiType && formalParam.type instanceof _multiType.MultiType) {
          var shared = 0;
          for (var j = 0; j < resultType.types.length; j++) {
            var element = resultType.types[j];
            if (formalParam.type.types.indexOf(element) !== -1) {
              shared++;
            }
          }
          if (shared <= 0) {
            if (_config.Config.enable_type_casting && !formalParam.byRef) {
              if (resultType.isCompatible(_types.Types.INTEGER) || resultType.isCompatible(_types.Types.REAL)) {
                if (formalParam.type.isCompatible(_types.Types.INTEGER) || formalParam.type.isCompatible(_types.Types.REAL)) {
                  continue;
                }
              }
            }
            throw _processorErrorFactory.ProcessorErrorFactory.invalid_parameter_type_full(id, param.toString(), param.sourceInfo);
          }
        } else if (resultType instanceof _multiType.MultiType) {
          if (!resultType.isCompatible(formalParam.type)) {
            if (_config.Config.enable_type_casting && !formalParam.byRef) {
              if (resultType.isCompatible(_types.Types.INTEGER) || resultType.isCompatible(_types.Types.REAL)) {
                if (formalParam.type.isCompatible(_types.Types.INTEGER) || formalParam.type.isCompatible(_types.Types.REAL)) {
                  continue;
                }
              }
            }
            throw _processorErrorFactory.ProcessorErrorFactory.invalid_parameter_type_full(id, param.toString(), param.sourceInfo);
          }
        } else if (!formalParam.type.isCompatible(resultType)) {
          if (_config.Config.enable_type_casting && !formalParam.byRef) {
            if (_store.Store.canImplicitTypeCast(formalParam.type, resultType)) {
              continue;
            }
          }
          throw _processorErrorFactory.ProcessorErrorFactory.invalid_parameter_type_full(id, param.toString(), param.sourceInfo);
        }
      }
    }
  }]);

  return SemanticAnalyser;
}();

/***/ }),

/***/ "./js/processor/store/store.js":
/*!*************************************!*\
  !*** ./js/processor/store/store.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Store = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _modes = __webpack_require__(/*! ./../modes */ "./js/processor/modes.js");

var _types = __webpack_require__(/*! ./../../typeSystem/types */ "./js/typeSystem/types.js");

var _storeObject = __webpack_require__(/*! ./storeObject */ "./js/processor/store/storeObject.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Store = exports.Store = function () {
  _createClass(Store, null, [{
    key: 'canImplicitTypeCast',
    value: function canImplicitTypeCast(castType, sourceType) {
      if (castType.isCompatible(_types.Types.INTEGER) || castType.isCompatible(_types.Types.REAL)) {
        if (sourceType.isCompatible(_types.Types.INTEGER) || sourceType.isCompatible(_types.Types.REAL)) {
          return true;
        }
      }
      return false;
    }
  }, {
    key: 'doImplicitCasting',
    value: function doImplicitCasting(castType, stoObj) {
      if (!Store.canImplicitTypeCast(castType, stoObj.type)) {
        throw new Error("!!!Critical error: attempted to type cast invalid types");
      }
      if (_types.Types.INTEGER.isCompatible(castType)) {
        return new _storeObject.StoreObject(castType, stoObj.value.trunc());
      } else {
        return new _storeObject.StoreObject(castType, stoObj.value);
      }
    }
  }]);

  function Store(name) {
    _classCallCheck(this, Store);

    this.name = name;
    this.store = {};
    this.nextStore = null;
    this.mode = _modes.Modes.RUN;
  }

  _createClass(Store, [{
    key: 'extendStore',
    value: function extendStore(nextStore) {
      this.nextStore = nextStore;
    }
  }, {
    key: 'applyStore',
    value: function applyStore(id) {
      if (!this.store[id]) {
        if (this.nextStore !== null) {
          return this.nextStore.applyStore(id);
        } else {
          throw new Error('Variable ' + id + ' not found.');
        }
      }
      var val = this.store[id];
      if (val.isRef) {
        return val.getRefObj();
      }
      return this.store[id];
    }
  }, {
    key: 'updateStore',
    value: function updateStore(id, stoObj) {
      if (!this.store[id]) {
        if (this.nextStore !== null) {
          this.nextStore.updateStore(id, stoObj);
          return this;
        } else {
          // TODO: better error message
          throw new Error('Variable ' + id + ' not found.');
        }
      } else {
        var oldObj = this.store[id];
        if (oldObj.readOnly) {
          // TODO: better error message
          throw new Error("Cannot change value of a read only variable: " + id);
        }
        if (oldObj.isRef) {
          oldObj.updateRef(stoObj);
          return this;
        } else if (oldObj.isCompatible(stoObj)) {
          stoObj.setID(id);
          this.store[id] = Object.freeze(stoObj);
          return this;
        } else {
          var oldType = oldObj.type;
          var stoType = stoObj.type;
          // TODO: better error message
          throw new Error(oldType + ' is not compatible with type ' + stoType + ' given');
        }
      }
    }

    //In case of future use of ref, it needs to have a special function to update the storeRefObject
    // and no the StoreObject refferenced by it
    // updateStoreRef(id, stoObjAddress) {...}

  }, {
    key: 'insertStore',
    value: function insertStore(id, stoObj) {
      if (this.store[id]) {
        // TODO: better error message
        throw new Error(id + ' is already defined');
      }
      stoObj.setID(id);
      this.store[id] = Object.freeze(stoObj);
      return this;
    }
  }]);

  return Store;
}();

/***/ }),

/***/ "./js/processor/store/storeObject.js":
/*!*******************************************!*\
  !*** ./js/processor/store/storeObject.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.StoreObject = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _decimal = __webpack_require__(/*! decimal.js */ "./node_modules/decimal.js/decimal.js");

var _decimal2 = _interopRequireDefault(_decimal);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var StoreObject = exports.StoreObject = function () {
  function StoreObject(type, value) {
    var readOnly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

    _classCallCheck(this, StoreObject);

    this._type = type;
    this._value = value;
    this._readOnly = readOnly;
    this._id = null;
  }

  _createClass(StoreObject, [{
    key: 'setID',
    value: function setID(id) {
      this._id = id;
    }
  }, {
    key: 'isCompatible',
    value: function isCompatible(another) {
      if (another instanceof StoreObject) {
        return this.type.isCompatible(another.type);
      }
      return false;
    }
  }, {
    key: 'id',
    get: function get() {
      return this._id;
    }
  }, {
    key: 'inStore',
    get: function get() {
      return this.id !== null;
    }
  }, {
    key: 'type',
    get: function get() {
      return this._type;
    }
  }, {
    key: 'value',
    get: function get() {
      return this._value;
    }
  }, {
    key: 'number',
    get: function get() {
      if (this._value instanceof _decimal2.default) {
        return this._value.toNumber();
      } else {
        return null;
      }
    }
  }, {
    key: 'readOnly',
    get: function get() {
      return this._readOnly;
    },
    set: function set(value) {
      this._readOnly = value;
    }
  }]);

  return StoreObject;
}();

/***/ }),

/***/ "./js/processor/store/storeObjectArray.js":
/*!************************************************!*\
  !*** ./js/processor/store/storeObjectArray.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.StoreObjectArray = undefined;

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _storeObject = __webpack_require__(/*! ./storeObject */ "./js/processor/store/storeObject.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var StoreObjectArray = exports.StoreObjectArray = function (_StoreObject) {
  _inherits(StoreObjectArray, _StoreObject);

  _createClass(StoreObjectArray, null, [{
    key: 'WRONG_LINE_NUMBER',
    get: function get() {
      return 1;
    }
  }, {
    key: 'WRONG_TYPE',
    get: function get() {
      return 2;
    }
  }, {
    key: 'WRONG_COLUMN_NUMBER',
    get: function get() {
      return 3;
    }
  }]);

  function StoreObjectArray(type, lines, columns) {
    var value = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
    var readOnly = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;

    _classCallCheck(this, StoreObjectArray);

    var _this = _possibleConstructorReturn(this, (StoreObjectArray.__proto__ || Object.getPrototypeOf(StoreObjectArray)).call(this, type, value, readOnly));

    _this._lines = lines;
    _this._columns = columns;
    return _this;
  }

  _createClass(StoreObjectArray, [{
    key: 'isCompatible',
    value: function isCompatible(another) {
      if (another instanceof _storeObject.StoreObject) {
        if (this.lines === -1 && another.lines > 0 || this.lines === another.lines) {
          if (this.columns === -1 && another.columns > 0 || this.columns === another.columns) {
            return _get(StoreObjectArray.prototype.__proto__ || Object.getPrototypeOf(StoreObjectArray.prototype), 'isCompatible', this).call(this, another);
          }
        }
      }
      return false;
    }
  }, {
    key: 'lines',
    get: function get() {
      return this._lines;
    }
  }, {
    key: 'columns',
    get: function get() {
      return this._columns;
    }
  }, {
    key: 'isVector',
    get: function get() {
      return this.type.dimensions === 1;
    }
  }, {
    key: 'isValid',
    get: function get() {
      var _this2 = this;

      if (this.value !== null) {
        if (this.isVector) {
          if (this.value.length !== this.lines) {
            return [StoreObjectArray.WRONG_LINE_NUMBER, this.value.length];;
          }
          var mustBeNull = this.value.find(function (v) {
            return !_this2.type.canAccept(v.type);
          });
          if (!!mustBeNull) {
            return [StoreObjectArray.WRONG_TYPE, this.value.indexOf(mustBeNull)];;
          }
        }
        return [];
      } else {
        if (this.lines !== this.value.length) {
          return [StoreObjectArray.WRONG_LINE_NUMBER, this.value.length];
        }
        for (var i = 0; i < this.lines; i++) {
          for (var j = 0; j < this.columns; j++) {
            var arr = this.value[i];
            if (arr.length !== this.columns) {
              return [StoreObjectArray.WRONG_COLUMN_NUMBER, arr.length];
            }
            var _mustBeNull = arr.find(function (v) {
              return !_this2.type.canAccept(v.type);
            });
            if (!!_mustBeNull) {
              return [StoreObjectArray.WRONG_TYPE, i, arr.indexOf(_mustBeNull)];
            }
          }
        }
        return [];
      }
    }
  }]);

  return StoreObjectArray;
}(_storeObject.StoreObject);

/***/ }),

/***/ "./js/processor/store/storeObjectArrayAddress.js":
/*!*******************************************************!*\
  !*** ./js/processor/store/storeObjectArrayAddress.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.StoreObjectArrayAddress = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _storeObject = __webpack_require__(/*! ./storeObject */ "./js/processor/store/storeObject.js");

var _storeObjectArray = __webpack_require__(/*! ./storeObjectArray */ "./js/processor/store/storeObjectArray.js");

var _compoundType = __webpack_require__(/*! ../../typeSystem/compoundType */ "./js/typeSystem/compoundType.js");

var _processorErrorFactory = __webpack_require__(/*! ../error/processorErrorFactory */ "./js/processor/error/processorErrorFactory.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var StoreObjectArrayAddress = exports.StoreObjectArrayAddress = function (_StoreObject) {
  _inherits(StoreObjectArrayAddress, _StoreObject);

  function StoreObjectArrayAddress(refID, line, column, store) {
    _classCallCheck(this, StoreObjectArrayAddress);

    var _this = _possibleConstructorReturn(this, (StoreObjectArrayAddress.__proto__ || Object.getPrototypeOf(StoreObjectArrayAddress)).call(this, null, null, false));

    _this.refID = refID;
    _this.store = store;
    _this.line = line;
    _this.column = column;
    return _this;
  }

  _createClass(StoreObjectArrayAddress, [{
    key: 'getArrayObject',
    value: function getArrayObject() {
      return this.store.applyStore(this.refID);
    }
  }, {
    key: 'updateArrayObject',
    value: function updateArrayObject(stoObj) {
      var anArray = this.getArrayObject();
      var newArray = Object.assign(new _storeObjectArray.StoreObjectArray(null, null, null), anArray);
      if (!stoObj.type.isCompatible(this.type)) {
        throw new Error('Invalid operation: cannot assign the value given to ' + this.refID);
      } else if (this.type instanceof _compoundType.CompoundType && this.type.canAccept(stoObj.type)) {
        throw new Error('Invalid operation: cannot assign the value given to ' + this.refID);
      }
      if (this.column !== null) {
        newArray.value[this.line].value[this.column] = stoObj;
        return newArray;
      } else {
        newArray.value[this.line] = stoObj;
        return newArray;
      }
    }
  }, {
    key: 'isCompatible',
    value: function isCompatible(another) {
      if (this.type.isCompatible(another.type)) {
        if (another.type instanceof _compoundType.CompoundType) {
          return this.lines === another.lines && this.columns === another.columns;
        } else {
          this.refValue.isCompatible(another);
        }
      }
    }
  }, {
    key: 'isRef',
    get: function get() {
      return false;
    }
  }, {
    key: 'inStore',
    get: function get() {
      return true;
    }
  }, {
    key: 'refValue',
    get: function get() {
      var refLine = this.store.applyStore(this.refID).value[this.line];
      if (!refLine) {
        if (this.getArrayObject().isVector) {
          throw _processorErrorFactory.ProcessorErrorFactory.vector_line_outbounds(this.refID, this.line, this.getArrayObject().lines);
        } else {
          throw _processorErrorFactory.ProcessorErrorFactory.matrix_line_outbounds(this.refID, this.line, this.getArrayObject().lines);
        }
      }
      if (this.column !== null) {
        var refColumn = refLine.value[this.column];
        if (!refColumn) {
          if (this.getArrayObject().isVector) {
            throw _processorErrorFactory.ProcessorErrorFactory.vector_not_matrix(this.refID);
          } else {
            throw _processorErrorFactory.ProcessorErrorFactory.matrix_column_outbounds(this.refID, this.column, this.getArrayObject().columns);
          }
        }
        return refColumn;
      }
      return refLine;
    }
  }, {
    key: 'value',
    get: function get() {
      return this.refValue.value;
    }
  }, {
    key: 'type',
    get: function get() {
      return this.refValue.type;
    }
  }, {
    key: 'lines',
    get: function get() {
      if (!(this.type instanceof _compoundType.CompoundType)) {
        return null;
      }
      return this.refValue.value.length;
    }
  }, {
    key: 'columns',
    get: function get() {
      switch (this.type.dimensions) {
        case 2:
          return this.refValue.value[0].value.length;
        default:
          return null;
      }
    }
  }]);

  return StoreObjectArrayAddress;
}(_storeObject.StoreObject);

/***/ }),

/***/ "./js/processor/store/storeObjectArrayAddressRef.js":
/*!**********************************************************!*\
  !*** ./js/processor/store/storeObjectArrayAddressRef.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.StoreObjectArrayAddressRef = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _storeObject = __webpack_require__(/*! ./storeObject */ "./js/processor/store/storeObject.js");

var _decimal = __webpack_require__(/*! decimal.js */ "./node_modules/decimal.js/decimal.js");

var _decimal2 = _interopRequireDefault(_decimal);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var StoreObjectArrayAddressRef = exports.StoreObjectArrayAddressRef = function (_StoreObject) {
  _inherits(StoreObjectArrayAddressRef, _StoreObject);

  function StoreObjectArrayAddressRef(address) {
    _classCallCheck(this, StoreObjectArrayAddressRef);

    var _this = _possibleConstructorReturn(this, (StoreObjectArrayAddressRef.__proto__ || Object.getPrototypeOf(StoreObjectArrayAddressRef)).call(this, null, null, false));

    _this.address = address;
    return _this;
  }

  _createClass(StoreObjectArrayAddressRef, [{
    key: 'getRefObj',
    value: function getRefObj() {
      return this.address.refValue;
    }
  }, {
    key: 'updateRef',
    value: function updateRef(stoObj) {
      var newArray = this.address.updateArrayObject(stoObj);
      this.address.store.updateStore(this.address.refID, newArray);
    }
  }, {
    key: 'isCompatible',
    value: function isCompatible(another) {
      return this.address.isCompatible(another);
    }
  }, {
    key: 'isRef',
    get: function get() {
      return true;
    }
  }, {
    key: 'type',
    get: function get() {
      return this.address.type;
    }
  }, {
    key: 'value',
    get: function get() {
      return this.address.value;
    }
  }, {
    key: 'number',
    get: function get() {
      if (this.value instanceof _decimal2.default) {
        return this.value.toNumber();
      } else {
        return null;
      }
    }
  }]);

  return StoreObjectArrayAddressRef;
}(_storeObject.StoreObject);

/***/ }),

/***/ "./js/processor/store/storeObjectRef.js":
/*!**********************************************!*\
  !*** ./js/processor/store/storeObjectRef.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.StoreObjectRef = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _storeObject = __webpack_require__(/*! ./storeObject */ "./js/processor/store/storeObject.js");

var _decimal = __webpack_require__(/*! decimal.js */ "./node_modules/decimal.js/decimal.js");

var _decimal2 = _interopRequireDefault(_decimal);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var StoreObjectRef = exports.StoreObjectRef = function (_StoreObject) {
  _inherits(StoreObjectRef, _StoreObject);

  function StoreObjectRef(refID, store) {
    _classCallCheck(this, StoreObjectRef);

    var _this = _possibleConstructorReturn(this, (StoreObjectRef.__proto__ || Object.getPrototypeOf(StoreObjectRef)).call(this, null, null, false));

    _this.refID = refID;
    _this.store = store;
    return _this;
  }

  _createClass(StoreObjectRef, [{
    key: 'getRefObj',
    value: function getRefObj() {
      return this.store.applyStore(this.refID);
    }
  }, {
    key: 'updateRef',
    value: function updateRef(stoObj) {
      this.store.updateStore(this.refID, stoObj);
    }
  }, {
    key: 'isCompatible',
    value: function isCompatible(another) {
      return this.store.applyStore(this.refID).isCompatible(another);
    }
  }, {
    key: 'isRef',
    get: function get() {
      return true;
    }
  }, {
    key: 'type',
    get: function get() {
      return this.store.applyStore(this.refID).type;
    }
  }, {
    key: 'value',
    get: function get() {
      return this.store.applyStore(this.refID).value;
    }
  }, {
    key: 'number',
    get: function get() {
      if (this.value instanceof _decimal2.default) {
        return this.value.toNumber();
      } else {
        return null;
      }
    }
  }]);

  return StoreObjectRef;
}(_storeObject.StoreObject);

/***/ }),

/***/ "./js/runner.js":
/*!**********************!*\
  !*** ./js/runner.js ***!
  \**********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.runner = runner;

var _ivprogParser = __webpack_require__(/*! ./ast/ivprogParser */ "./js/ast/ivprogParser.js");

var _ivprogProcessor = __webpack_require__(/*! ./processor/ivprogProcessor */ "./js/processor/ivprogProcessor.js");

var _domConsole = __webpack_require__(/*! ./io/domConsole */ "./js/io/domConsole.js");

var _languageService = __webpack_require__(/*! ./services/languageService */ "./js/services/languageService.js");

var _semanticAnalyser = __webpack_require__(/*! ./processor/semantic/semanticAnalyser */ "./js/processor/semantic/semanticAnalyser.js");

function runner() {
  var ivprogLexer = _languageService.LanguageService.getCurrentLexer();

  // const lexer = new ivprogLexer(new InputStream(input));
  // const stream = new CommonTokenStream(lexer);
  // stream.fill();
  // let i = 1;
  // let token = null;
  // while ((token = stream.LT(i)).type !== ivprogLexer.EOF && token.type !== ivprogLexer.WHITESPACE) {
  //     console.log(`${token.type}-${token.text}`);
  //     console.log('\n')
  //     i++;
  // }
  // const anaSin = new IVProgParser(input, ivprogLexer);
  var editor = new JsonEditor('#json-renderer', {});
  var domConsole = new _domConsole.DOMConsole("#console");
  // proc.interpretAST().then( sto => {
  //   console.log(sto.applyStore('a'));
  // }).catch(e => console.log(e));
  try {
    $('#btn').click(function () {
      var input = $('#input').val();
      var analiser = new _ivprogParser.IVProgParser(input, ivprogLexer);
      try {
        var data = analiser.parseTree();
        var semAna = new _semanticAnalyser.SemanticAnalyser(data);
        var proc = new _ivprogProcessor.IVProgProcessor(semAna.analyseTree());
        proc.registerInput(domConsole);
        domConsole.clear();
        proc.registerOutput(domConsole);
        proc.interpretAST().then(function (sto) {
          return editor.load(sto.store);
        }).catch(function (e) {
          alert(e);console.log(e);
        });
      } catch (error) {
        alert(error);
        console.log(error);
      }
    });
  } catch (a) {
    console.log(a);
  }
}

/***/ }),

/***/ "./js/semantic/semantic.min.js":
/*!*************************************!*\
  !*** ./js/semantic/semantic.min.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/*
* # Semantic UI - 2.3.3
* https://github.com/Semantic-Org/Semantic-UI
* http://www.semantic-ui.com/
*
* Copyright 2014 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
!function (e, t, n, i) {
  e.site = e.fn.site = function (o) {
    var a,
        r,
        s = new Date().getTime(),
        l = [],
        c = arguments[0],
        u = "string" == typeof c,
        d = [].slice.call(arguments, 1),
        f = e.isPlainObject(o) ? e.extend(!0, {}, e.site.settings, o) : e.extend({}, e.site.settings),
        m = f.namespace,
        g = f.error,
        p = "module-" + m,
        h = e(n),
        v = this,
        b = h.data(p);return a = { initialize: function initialize() {
        a.instantiate();
      }, instantiate: function instantiate() {
        a.verbose("Storing instance of site", a), b = a, h.data(p, a);
      }, normalize: function normalize() {
        a.fix.console(), a.fix.requestAnimationFrame();
      }, fix: { console: function (_console) {
          function console() {
            return _console.apply(this, arguments);
          }

          console.toString = function () {
            return _console.toString();
          };

          return console;
        }(function () {
          a.debug("Normalizing window.console"), console !== i && console.log !== i || (a.verbose("Console not available, normalizing events"), a.disable.console()), void 0 !== console.group && void 0 !== console.groupEnd && void 0 !== console.groupCollapsed || (a.verbose("Console group not available, normalizing events"), t.console.group = function () {}, t.console.groupEnd = function () {}, t.console.groupCollapsed = function () {}), void 0 === console.markTimeline && (a.verbose("Mark timeline not available, normalizing events"), t.console.markTimeline = function () {});
        }), consoleClear: function consoleClear() {
          a.debug("Disabling programmatic console clearing"), t.console.clear = function () {};
        }, requestAnimationFrame: function requestAnimationFrame() {
          a.debug("Normalizing requestAnimationFrame"), t.requestAnimationFrame === i && (a.debug("RequestAnimationFrame not available, normalizing event"), t.requestAnimationFrame = t.requestAnimationFrame || t.mozRequestAnimationFrame || t.webkitRequestAnimationFrame || t.msRequestAnimationFrame || function (e) {
            setTimeout(e, 0);
          });
        } }, moduleExists: function moduleExists(t) {
        return e.fn[t] !== i && e.fn[t].settings !== i;
      }, enabled: { modules: function modules(t) {
          var n = [];return t = t || f.modules, e.each(t, function (e, t) {
            a.moduleExists(t) && n.push(t);
          }), n;
        } }, disabled: { modules: function modules(t) {
          var n = [];return t = t || f.modules, e.each(t, function (e, t) {
            a.moduleExists(t) || n.push(t);
          }), n;
        } }, change: { setting: function setting(t, n, o, r) {
          o = "string" == typeof o ? "all" === o ? f.modules : [o] : o || f.modules, r = r === i || r, e.each(o, function (i, o) {
            var s,
                l = !a.moduleExists(o) || e.fn[o].settings.namespace || !1;a.moduleExists(o) && (a.verbose("Changing default setting", t, n, o), e.fn[o].settings[t] = n, r && l && (s = e(":data(module-" + l + ")")).length > 0 && (a.verbose("Modifying existing settings", s), s[o]("setting", t, n)));
          });
        }, settings: function settings(t, n, o) {
          n = "string" == typeof n ? [n] : n || f.modules, o = o === i || o, e.each(n, function (n, i) {
            var r;a.moduleExists(i) && (a.verbose("Changing default setting", t, i), e.extend(!0, e.fn[i].settings, t), o && m && (r = e(":data(module-" + m + ")")).length > 0 && (a.verbose("Modifying existing settings", r), r[i]("setting", t)));
          });
        } }, enable: { console: function console() {
          a.console(!0);
        }, debug: function debug(e, t) {
          e = e || f.modules, a.debug("Enabling debug for modules", e), a.change.setting("debug", !0, e, t);
        }, verbose: function verbose(e, t) {
          e = e || f.modules, a.debug("Enabling verbose debug for modules", e), a.change.setting("verbose", !0, e, t);
        } }, disable: { console: function console() {
          a.console(!1);
        }, debug: function debug(e, t) {
          e = e || f.modules, a.debug("Disabling debug for modules", e), a.change.setting("debug", !1, e, t);
        }, verbose: function verbose(e, t) {
          e = e || f.modules, a.debug("Disabling verbose debug for modules", e), a.change.setting("verbose", !1, e, t);
        } }, console: function console(e) {
        if (e) {
          if (b.cache.console === i) return void a.error(g.console);a.debug("Restoring console function"), t.console = b.cache.console;
        } else a.debug("Disabling console function"), b.cache.console = t.console, t.console = { clear: function clear() {}, error: function error() {}, group: function group() {}, groupCollapsed: function groupCollapsed() {}, groupEnd: function groupEnd() {}, info: function info() {}, log: function log() {}, markTimeline: function markTimeline() {}, warn: function warn() {} };
      }, destroy: function destroy() {
        a.verbose("Destroying previous site for", h), h.removeData(p);
      }, cache: {}, setting: function setting(t, n) {
        if (e.isPlainObject(t)) e.extend(!0, f, t);else {
          if (n === i) return f[t];f[t] = n;
        }
      }, internal: function internal(t, n) {
        if (e.isPlainObject(t)) e.extend(!0, a, t);else {
          if (n === i) return a[t];a[t] = n;
        }
      }, debug: function debug() {
        f.debug && (f.performance ? a.performance.log(arguments) : (a.debug = Function.prototype.bind.call(console.info, console, f.name + ":"), a.debug.apply(console, arguments)));
      }, verbose: function verbose() {
        f.verbose && f.debug && (f.performance ? a.performance.log(arguments) : (a.verbose = Function.prototype.bind.call(console.info, console, f.name + ":"), a.verbose.apply(console, arguments)));
      }, error: function error() {
        a.error = Function.prototype.bind.call(console.error, console, f.name + ":"), a.error.apply(console, arguments);
      }, performance: { log: function log(e) {
          var t, n;f.performance && (n = (t = new Date().getTime()) - (s || t), s = t, l.push({ Element: v, Name: e[0], Arguments: [].slice.call(e, 1) || "", "Execution Time": n })), clearTimeout(a.performance.timer), a.performance.timer = setTimeout(a.performance.display, 500);
        }, display: function display() {
          var t = f.name + ":",
              n = 0;s = !1, clearTimeout(a.performance.timer), e.each(l, function (e, t) {
            n += t["Execution Time"];
          }), t += " " + n + "ms", (console.group !== i || console.table !== i) && l.length > 0 && (console.groupCollapsed(t), console.table ? console.table(l) : e.each(l, function (e, t) {
            console.log(t.Name + ": " + t["Execution Time"] + "ms");
          }), console.groupEnd()), l = [];
        } }, invoke: function invoke(t, n, o) {
        var s,
            l,
            c,
            u = b;return n = n || d, o = v || o, "string" == typeof t && u !== i && (t = t.split(/[\. ]/), s = t.length - 1, e.each(t, function (n, o) {
          var r = n != s ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(u[r]) && n != s) u = u[r];else {
            if (u[r] !== i) return l = u[r], !1;if (!e.isPlainObject(u[o]) || n == s) return u[o] !== i ? (l = u[o], !1) : (a.error(g.method, t), !1);u = u[o];
          }
        })), e.isFunction(l) ? c = l.apply(o, n) : l !== i && (c = l), e.isArray(r) ? r.push(c) : r !== i ? r = [r, c] : c !== i && (r = c), l;
      } }, u ? (b === i && a.initialize(), a.invoke(c)) : (b !== i && a.destroy(), a.initialize()), r !== i ? r : this;
  }, e.site.settings = { name: "Site", namespace: "site", error: { console: "Console cannot be restored, most likely it was overwritten outside of module", method: "The method you called is not defined." }, debug: !1, verbose: !1, performance: !0, modules: ["accordion", "api", "checkbox", "dimmer", "dropdown", "embed", "form", "modal", "nag", "popup", "rating", "shape", "sidebar", "state", "sticky", "tab", "transition", "visit", "visibility"], siteNamespace: "site", namespaceStub: { cache: {}, config: {}, sections: {}, section: {}, utilities: {} } }, e.extend(e.expr[":"], { data: e.expr.createPseudo ? e.expr.createPseudo(function (t) {
      return function (n) {
        return !!e.data(n, t);
      };
    }) : function (t, n, i) {
      return !!e.data(t, i[3]);
    } });
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.form = function (t) {
    var o,
        a = e(this),
        r = a.selector || "",
        s = new Date().getTime(),
        l = [],
        c = arguments[0],
        u = arguments[1],
        d = "string" == typeof c,
        f = [].slice.call(arguments, 1);return a.each(function () {
      var m,
          g,
          p,
          h,
          v,
          b,
          y,
          x,
          C,
          w,
          S,
          k,
          T,
          A,
          R,
          P,
          E = e(this),
          F = this,
          O = [],
          D = !1;(P = { initialize: function initialize() {
          P.get.settings(), d ? (R === i && P.instantiate(), P.invoke(c)) : (R !== i && R.invoke("destroy"), P.verbose("Initializing form validation", E, v), P.bindEvents(), P.set.defaults(), P.instantiate());
        }, instantiate: function instantiate() {
          P.verbose("Storing instance of module", P), R = P, E.data(T, P);
        }, destroy: function destroy() {
          P.verbose("Destroying previous module", R), P.removeEvents(), E.removeData(T);
        }, refresh: function refresh() {
          P.verbose("Refreshing selector cache"), m = E.find(x.field), g = E.find(x.group), p = E.find(x.message), E.find(x.prompt), h = E.find(x.submit), E.find(x.clear), E.find(x.reset);
        }, submit: function submit() {
          P.verbose("Submitting form", E), E.submit();
        }, attachEvents: function attachEvents(t, n) {
          n = n || "submit", e(t).on("click" + A, function (e) {
            P[n](), e.preventDefault();
          });
        }, bindEvents: function bindEvents() {
          P.verbose("Attaching form events"), E.on("submit" + A, P.validate.form).on("blur" + A, x.field, P.event.field.blur).on("click" + A, x.submit, P.submit).on("click" + A, x.reset, P.reset).on("click" + A, x.clear, P.clear), v.keyboardShortcuts && E.on("keydown" + A, x.field, P.event.field.keydown), m.each(function () {
            var t = e(this),
                n = t.prop("type"),
                i = P.get.changeEvent(n, t);e(this).on(i + A, P.event.field.change);
          });
        }, clear: function clear() {
          m.each(function () {
            var t = e(this),
                n = t.parent(),
                i = t.closest(g),
                o = i.find(x.prompt),
                a = t.data(y.defaultValue) || "",
                r = n.is(x.uiCheckbox),
                s = n.is(x.uiDropdown);i.hasClass(C.error) && (P.verbose("Resetting error on field", i), i.removeClass(C.error), o.remove()), s ? (P.verbose("Resetting dropdown value", n, a), n.dropdown("clear")) : r ? t.prop("checked", !1) : (P.verbose("Resetting field value", t, a), t.val(""));
          });
        }, reset: function reset() {
          m.each(function () {
            var t = e(this),
                n = t.parent(),
                o = t.closest(g),
                a = o.find(x.prompt),
                r = t.data(y.defaultValue),
                s = n.is(x.uiCheckbox),
                l = n.is(x.uiDropdown),
                c = o.hasClass(C.error);r !== i && (c && (P.verbose("Resetting error on field", o), o.removeClass(C.error), a.remove()), l ? (P.verbose("Resetting dropdown value", n, r), n.dropdown("restore defaults")) : s ? (P.verbose("Resetting checkbox value", n, r), t.prop("checked", r)) : (P.verbose("Resetting field value", t, r), t.val(r)));
          });
        }, determine: { isValid: function isValid() {
            var t = !0;return e.each(b, function (e, n) {
              P.validate.field(n, e, !0) || (t = !1);
            }), t;
          } }, is: { bracketedRule: function bracketedRule(e) {
            return e.type && e.type.match(v.regExp.bracket);
          }, shorthandFields: function shorthandFields(e) {
            var t = e[Object.keys(e)[0]];return P.is.shorthandRules(t);
          }, shorthandRules: function shorthandRules(t) {
            return "string" == typeof t || e.isArray(t);
          }, empty: function empty(e) {
            return !e || 0 === e.length || (e.is('input[type="checkbox"]') ? !e.is(":checked") : P.is.blank(e));
          }, blank: function blank(t) {
            return "" === e.trim(t.val());
          }, valid: function valid(t) {
            var n = !0;return t ? (P.verbose("Checking if field is valid", t), P.validate.field(b[t], t, !1)) : (P.verbose("Checking if form is valid"), e.each(b, function (e, t) {
              P.is.valid(e) || (n = !1);
            }), n);
          } }, removeEvents: function removeEvents() {
          E.off(A), m.off(A), h.off(A), m.off(A);
        }, event: { field: { keydown: function keydown(t) {
              var n = e(this),
                  i = t.which,
                  o = n.is(x.input),
                  a = n.is(x.checkbox),
                  r = n.closest(x.uiDropdown).length > 0,
                  s = 13;i == 27 && (P.verbose("Escape key pressed blurring field"), n.blur()), t.ctrlKey || i != s || !o || r || a || (D || (n.one("keyup" + A, P.event.field.keyup), P.submit(), P.debug("Enter pressed on input submitting form")), D = !0);
            }, keyup: function keyup() {
              D = !1;
            }, blur: function blur(t) {
              var n = e(this),
                  i = n.closest(g),
                  o = P.get.validation(n);i.hasClass(C.error) ? (P.debug("Revalidating field", n, o), o && P.validate.field(o)) : "blur" == v.on && o && P.validate.field(o);
            }, change: function change(t) {
              var n = e(this),
                  i = n.closest(g),
                  o = P.get.validation(n);o && ("change" == v.on || i.hasClass(C.error) && v.revalidate) && (clearTimeout(P.timer), P.timer = setTimeout(function () {
                P.debug("Revalidating field", n, P.get.validation(n)), P.validate.field(o);
              }, v.delay));
            } } }, get: { ancillaryValue: function ancillaryValue(e) {
            return !(!e.type || !e.value && !P.is.bracketedRule(e)) && (e.value !== i ? e.value : e.type.match(v.regExp.bracket)[1] + "");
          }, ruleName: function ruleName(e) {
            return P.is.bracketedRule(e) ? e.type.replace(e.type.match(v.regExp.bracket)[0], "") : e.type;
          }, changeEvent: function changeEvent(e, t) {
            return "checkbox" == e || "radio" == e || "hidden" == e || t.is("select") ? "change" : P.get.inputEvent();
          }, inputEvent: function inputEvent() {
            return n.createElement("input").oninput !== i ? "input" : n.createElement("input").onpropertychange !== i ? "propertychange" : "keyup";
          }, fieldsFromShorthand: function fieldsFromShorthand(t) {
            var n = {};return e.each(t, function (t, i) {
              "string" == typeof i && (i = [i]), n[t] = { rules: [] }, e.each(i, function (e, i) {
                n[t].rules.push({ type: i });
              });
            }), n;
          }, prompt: function prompt(t, n) {
            var i,
                o,
                a = P.get.ruleName(t),
                r = P.get.ancillaryValue(t),
                s = P.get.field(n.identifier),
                l = s.val(),
                c = e.isFunction(t.prompt) ? t.prompt(l) : t.prompt || v.prompt[a] || v.text.unspecifiedRule,
                u = -1 !== c.search("{value}"),
                d = -1 !== c.search("{name}");return u && (c = c.replace("{value}", s.val())), d && (o = 1 == (i = s.closest(x.group).find("label").eq(0)).length ? i.text() : s.prop("placeholder") || v.text.unspecifiedField, c = c.replace("{name}", o)), c = (c = c.replace("{identifier}", n.identifier)).replace("{ruleValue}", r), t.prompt || P.verbose("Using default validation prompt for type", c, a), c;
          }, settings: function settings() {
            if (e.isPlainObject(t)) {
              var n = Object.keys(t);n.length > 0 && t[n[0]].identifier !== i && t[n[0]].rules !== i ? (v = e.extend(!0, {}, e.fn.form.settings, u), b = e.extend({}, e.fn.form.settings.defaults, t), P.error(v.error.oldSyntax, F), P.verbose("Extending settings from legacy parameters", b, v)) : (t.fields && P.is.shorthandFields(t.fields) && (t.fields = P.get.fieldsFromShorthand(t.fields)), v = e.extend(!0, {}, e.fn.form.settings, t), b = e.extend({}, e.fn.form.settings.defaults, v.fields), P.verbose("Extending settings", b, v));
            } else v = e.fn.form.settings, b = e.fn.form.settings.defaults, P.verbose("Using default form validation", b, v);k = v.namespace, y = v.metadata, x = v.selector, C = v.className, w = v.regExp, S = v.error, T = "module-" + k, A = "." + k, R = E.data(T), P.refresh();
          }, field: function field(t) {
            return P.verbose("Finding field with identifier", t), t = P.escape.string(t), m.filter("#" + t).length > 0 ? m.filter("#" + t) : m.filter('[name="' + t + '"]').length > 0 ? m.filter('[name="' + t + '"]') : m.filter('[name="' + t + '[]"]').length > 0 ? m.filter('[name="' + t + '[]"]') : m.filter("[data-" + y.validate + '="' + t + '"]').length > 0 ? m.filter("[data-" + y.validate + '="' + t + '"]') : e("<input/>");
          }, fields: function fields(t) {
            var n = e();return e.each(t, function (e, t) {
              n = n.add(P.get.field(t));
            }), n;
          }, validation: function validation(t) {
            var n, i;return !!b && (e.each(b, function (e, o) {
              i = o.identifier || e, P.get.field(i)[0] == t[0] && (o.identifier = i, n = o);
            }), n || !1);
          }, value: function value(e) {
            var t = [];return t.push(e), P.get.values.call(F, t)[e];
          }, values: function values(t) {
            var n = {};return (e.isArray(t) ? P.get.fields(t) : m).each(function (t, o) {
              var a = e(o),
                  r = (a.prop("type"), a.prop("name")),
                  s = a.val(),
                  l = a.is(x.checkbox),
                  c = a.is(x.radio),
                  u = -1 !== r.indexOf("[]"),
                  d = !!l && a.is(":checked");r && (u ? (r = r.replace("[]", ""), n[r] || (n[r] = []), l ? d ? n[r].push(s || !0) : n[r].push(!1) : n[r].push(s)) : c ? n[r] !== i && 0 != n[r] || (n[r] = !!d && (s || !0)) : n[r] = l ? !!d && (s || !0) : s);
            }), n;
          } }, has: { field: function field(e) {
            return P.verbose("Checking for existence of a field with identifier", e), "string" != typeof (e = P.escape.string(e)) && P.error(S.identifier, e), m.filter("#" + e).length > 0 || m.filter('[name="' + e + '"]').length > 0 || m.filter("[data-" + y.validate + '="' + e + '"]').length > 0;
          } }, escape: { string: function string(e) {
            return (e = String(e)).replace(w.escape, "\\$&");
          } }, add: { rule: function rule(e, t) {
            P.add.field(e, t);
          }, field: function field(t, n) {
            var i = {};P.is.shorthandRules(n) ? (n = e.isArray(n) ? n : [n], i[t] = { rules: [] }, e.each(n, function (e, n) {
              i[t].rules.push({ type: n });
            })) : i[t] = n, b = e.extend({}, b, i), P.debug("Adding rules", i, b);
          }, fields: function fields(t) {
            var n;n = t && P.is.shorthandFields(t) ? P.get.fieldsFromShorthand(t) : t, b = e.extend({}, b, n);
          }, prompt: function prompt(t, n) {
            var o = P.get.field(t).closest(g),
                a = o.children(x.prompt),
                r = 0 !== a.length;n = "string" == typeof n ? [n] : n, P.verbose("Adding field error state", t), o.addClass(C.error), v.inline && (r || (a = v.templates.prompt(n)).appendTo(o), a.html(n[0]), r ? P.verbose("Inline errors are disabled, no inline error added", t) : v.transition && e.fn.transition !== i && E.transition("is supported") ? (P.verbose("Displaying error with css transition", v.transition), a.transition(v.transition + " in", v.duration)) : (P.verbose("Displaying error with fallback javascript animation"), a.fadeIn(v.duration)));
          }, errors: function errors(e) {
            P.debug("Adding form error messages", e), P.set.error(), p.html(v.templates.error(e));
          } }, remove: { rule: function rule(t, n) {
            var o = e.isArray(n) ? n : [n];if (n == i) return P.debug("Removed all rules"), void (b[t].rules = []);b[t] != i && e.isArray(b[t].rules) && e.each(b[t].rules, function (e, n) {
              -1 !== o.indexOf(n.type) && (P.debug("Removed rule", n.type), b[t].rules.splice(e, 1));
            });
          }, field: function field(t) {
            var n = e.isArray(t) ? t : [t];e.each(n, function (e, t) {
              P.remove.rule(t);
            });
          }, rules: function rules(t, n) {
            e.isArray(t) ? e.each(fields, function (e, t) {
              P.remove.rule(t, n);
            }) : P.remove.rule(t, n);
          }, fields: function fields(e) {
            P.remove.field(e);
          }, prompt: function prompt(t) {
            var n = P.get.field(t).closest(g),
                o = n.children(x.prompt);n.removeClass(C.error), v.inline && o.is(":visible") && (P.verbose("Removing prompt for field", t), v.transition && e.fn.transition !== i && E.transition("is supported") ? o.transition(v.transition + " out", v.duration, function () {
              o.remove();
            }) : o.fadeOut(v.duration, function () {
              o.remove();
            }));
          } }, set: { success: function success() {
            E.removeClass(C.error).addClass(C.success);
          }, defaults: function defaults() {
            m.each(function () {
              var t = e(this),
                  n = t.filter(x.checkbox).length > 0 ? t.is(":checked") : t.val();t.data(y.defaultValue, n);
            });
          }, error: function error() {
            E.removeClass(C.success).addClass(C.error);
          }, value: function value(e, t) {
            var n = {};return n[e] = t, P.set.values.call(F, n);
          }, values: function values(t) {
            e.isEmptyObject(t) || e.each(t, function (t, n) {
              var i,
                  o = P.get.field(t),
                  a = o.parent(),
                  r = e.isArray(n),
                  s = a.is(x.uiCheckbox),
                  l = a.is(x.uiDropdown),
                  c = o.is(x.radio) && s;o.length > 0 && (r && s ? (P.verbose("Selecting multiple", n, o), a.checkbox("uncheck"), e.each(n, function (e, t) {
                i = o.filter('[value="' + t + '"]'), a = i.parent(), i.length > 0 && a.checkbox("check");
              })) : c ? (P.verbose("Selecting radio value", n, o), o.filter('[value="' + n + '"]').parent(x.uiCheckbox).checkbox("check")) : s ? (P.verbose("Setting checkbox value", n, a), !0 === n ? a.checkbox("check") : a.checkbox("uncheck")) : l ? (P.verbose("Setting dropdown value", n, a), a.dropdown("set selected", n)) : (P.verbose("Setting field value", n, o), o.val(n)));
            });
          } }, validate: { form: function form(e, t) {
            var n = P.get.values();if (D) return !1;if (O = [], P.determine.isValid()) {
              if (P.debug("Form has no validation errors, submitting"), P.set.success(), !0 !== t) return v.onSuccess.call(F, e, n);
            } else if (P.debug("Form has errors"), P.set.error(), v.inline || P.add.errors(O), E.data("moduleApi") !== i && e.stopImmediatePropagation(), !0 !== t) return v.onFailure.call(F, O, n);
          }, field: function field(t, n, o) {
            o = o === i || o, "string" == typeof t && (P.verbose("Validating field", t), n = t, t = b[t]);var a = t.identifier || n,
                r = P.get.field(a),
                s = !!t.depends && P.get.field(t.depends),
                l = !0,
                c = [];return t.identifier || (P.debug("Using field name as identifier", a), t.identifier = a), r.prop("disabled") ? (P.debug("Field is disabled. Skipping", a), l = !0) : t.optional && P.is.blank(r) ? (P.debug("Field is optional and blank. Skipping", a), l = !0) : t.depends && P.is.empty(s) ? (P.debug("Field depends on another value that is not present or empty. Skipping", s), l = !0) : t.rules !== i && e.each(t.rules, function (e, n) {
              P.has.field(a) && !P.validate.rule(t, n) && (P.debug("Field is invalid", a, n.type), c.push(P.get.prompt(n, t)), l = !1);
            }), l ? (o && (P.remove.prompt(a, c), v.onValid.call(r)), !0) : (o && (O = O.concat(c), P.add.prompt(a, c), v.onInvalid.call(r, c)), !1);
          }, rule: function rule(t, n) {
            var o = P.get.field(t.identifier),
                a = (n.type, o.val()),
                r = P.get.ancillaryValue(n),
                s = P.get.ruleName(n),
                l = v.rules[s];if (e.isFunction(l)) return a = a === i || "" === a || null === a ? "" : e.trim(a + ""), l.call(o, a, r);P.error(S.noRule, s);
          } }, setting: function setting(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, v, t);else {
            if (n === i) return v[t];v[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, P, t);else {
            if (n === i) return P[t];P[t] = n;
          }
        }, debug: function debug() {
          !v.silent && v.debug && (v.performance ? P.performance.log(arguments) : (P.debug = Function.prototype.bind.call(console.info, console, v.name + ":"), P.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !v.silent && v.verbose && v.debug && (v.performance ? P.performance.log(arguments) : (P.verbose = Function.prototype.bind.call(console.info, console, v.name + ":"), P.verbose.apply(console, arguments)));
        }, error: function error() {
          v.silent || (P.error = Function.prototype.bind.call(console.error, console, v.name + ":"), P.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;v.performance && (n = (t = new Date().getTime()) - (s || t), s = t, l.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: F, "Execution Time": n })), clearTimeout(P.performance.timer), P.performance.timer = setTimeout(P.performance.display, 500);
          }, display: function display() {
            var t = v.name + ":",
                n = 0;s = !1, clearTimeout(P.performance.timer), e.each(l, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", r && (t += " '" + r + "'"), a.length > 1 && (t += " (" + a.length + ")"), (console.group !== i || console.table !== i) && l.length > 0 && (console.groupCollapsed(t), console.table ? console.table(l) : e.each(l, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), l = [];
          } }, invoke: function invoke(t, n, a) {
          var r,
              s,
              l,
              c = R;return n = n || f, a = F || a, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i && (s = c[o], !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(a, n) : s !== i && (l = s), e.isArray(o) ? o.push(l) : o !== i ? o = [o, l] : l !== i && (o = l), s;
        } }).initialize();
    }), o !== i ? o : this;
  }, e.fn.form.settings = { name: "Form", namespace: "form", debug: !1, verbose: !1, performance: !0, fields: !1, keyboardShortcuts: !0, on: "submit", inline: !1, delay: 200, revalidate: !0, transition: "scale", duration: 200, onValid: function onValid() {}, onInvalid: function onInvalid() {}, onSuccess: function onSuccess() {
      return !0;
    }, onFailure: function onFailure() {
      return !1;
    }, metadata: { defaultValue: "default", validate: "validate" }, regExp: { htmlID: /^[a-zA-Z][\w:.-]*$/g, bracket: /\[(.*)\]/i, decimal: /^\d+\.?\d*$/, email: /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i, escape: /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, flags: /^\/(.*)\/(.*)?/, integer: /^\-?\d+$/, number: /^\-?\d*(\.\d+)?$/, url: /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/i }, text: { unspecifiedRule: "Please enter a valid value", unspecifiedField: "This field" }, prompt: { empty: "{name} must have a value", checked: "{name} must be checked", email: "{name} must be a valid e-mail", url: "{name} must be a valid url", regExp: "{name} is not formatted correctly", integer: "{name} must be an integer", decimal: "{name} must be a decimal number", number: "{name} must be set to a number", is: '{name} must be "{ruleValue}"', isExactly: '{name} must be exactly "{ruleValue}"', not: '{name} cannot be set to "{ruleValue}"', notExactly: '{name} cannot be set to exactly "{ruleValue}"', contain: '{name} must contain "{ruleValue}"', containExactly: '{name} must contain exactly "{ruleValue}"', doesntContain: '{name} cannot contain  "{ruleValue}"', doesntContainExactly: '{name} cannot contain exactly "{ruleValue}"', minLength: "{name} must be at least {ruleValue} characters", length: "{name} must be at least {ruleValue} characters", exactLength: "{name} must be exactly {ruleValue} characters", maxLength: "{name} cannot be longer than {ruleValue} characters", match: "{name} must match {ruleValue} field", different: "{name} must have a different value than {ruleValue} field", creditCard: "{name} must be a valid credit card number", minCount: "{name} must have at least {ruleValue} choices", exactCount: "{name} must have exactly {ruleValue} choices", maxCount: "{name} must have {ruleValue} or less choices" }, selector: { checkbox: 'input[type="checkbox"], input[type="radio"]', clear: ".clear", field: "input, textarea, select", group: ".field", input: "input", message: ".error.message", prompt: ".prompt.label", radio: 'input[type="radio"]', reset: '.reset:not([type="reset"])', submit: '.submit:not([type="submit"])', uiCheckbox: ".ui.checkbox", uiDropdown: ".ui.dropdown" }, className: { error: "error", label: "ui prompt label", pressed: "down", success: "success" }, error: { identifier: "You must specify a string identifier for each field", method: "The method you called is not defined.", noRule: "There is no rule matching the one you specified", oldSyntax: "Starting in 2.0 forms now only take a single settings object. Validation settings converted to new syntax automatically." }, templates: { error: function error(t) {
        var n = '<ul class="list">';return e.each(t, function (e, t) {
          n += "<li>" + t + "</li>";
        }), e(n += "</ul>");
      }, prompt: function prompt(t) {
        return e("<div/>").addClass("ui basic red pointing prompt label").html(t[0]);
      } }, rules: { empty: function empty(t) {
        return !(t === i || "" === t || e.isArray(t) && 0 === t.length);
      }, checked: function checked() {
        return e(this).filter(":checked").length > 0;
      }, email: function email(t) {
        return e.fn.form.settings.regExp.email.test(t);
      }, url: function url(t) {
        return e.fn.form.settings.regExp.url.test(t);
      }, regExp: function regExp(t, n) {
        if (n instanceof RegExp) return t.match(n);var i,
            o = n.match(e.fn.form.settings.regExp.flags);return o && (n = o.length >= 2 ? o[1] : n, i = o.length >= 3 ? o[2] : ""), t.match(new RegExp(n, i));
      }, integer: function integer(t, n) {
        var o,
            a,
            r,
            s = e.fn.form.settings.regExp.integer;return n && -1 === ["", ".."].indexOf(n) && (-1 == n.indexOf("..") ? s.test(n) && (o = a = n - 0) : (r = n.split("..", 2), s.test(r[0]) && (o = r[0] - 0), s.test(r[1]) && (a = r[1] - 0))), s.test(t) && (o === i || t >= o) && (a === i || t <= a);
      }, decimal: function decimal(t) {
        return e.fn.form.settings.regExp.decimal.test(t);
      }, number: function number(t) {
        return e.fn.form.settings.regExp.number.test(t);
      }, is: function is(e, t) {
        return t = "string" == typeof t ? t.toLowerCase() : t, (e = "string" == typeof e ? e.toLowerCase() : e) == t;
      }, isExactly: function isExactly(e, t) {
        return e == t;
      }, not: function not(e, t) {
        return (e = "string" == typeof e ? e.toLowerCase() : e) != (t = "string" == typeof t ? t.toLowerCase() : t);
      }, notExactly: function notExactly(e, t) {
        return e != t;
      }, contains: function contains(t, n) {
        return n = n.replace(e.fn.form.settings.regExp.escape, "\\$&"), -1 !== t.search(new RegExp(n, "i"));
      }, containsExactly: function containsExactly(t, n) {
        return n = n.replace(e.fn.form.settings.regExp.escape, "\\$&"), -1 !== t.search(new RegExp(n));
      }, doesntContain: function doesntContain(t, n) {
        return n = n.replace(e.fn.form.settings.regExp.escape, "\\$&"), -1 === t.search(new RegExp(n, "i"));
      }, doesntContainExactly: function doesntContainExactly(t, n) {
        return n = n.replace(e.fn.form.settings.regExp.escape, "\\$&"), -1 === t.search(new RegExp(n));
      }, minLength: function minLength(e, t) {
        return e !== i && e.length >= t;
      }, length: function length(e, t) {
        return e !== i && e.length >= t;
      }, exactLength: function exactLength(e, t) {
        return e !== i && e.length == t;
      }, maxLength: function maxLength(e, t) {
        return e !== i && e.length <= t;
      }, match: function match(t, n) {
        var o;e(this);return e('[data-validate="' + n + '"]').length > 0 ? o = e('[data-validate="' + n + '"]').val() : e("#" + n).length > 0 ? o = e("#" + n).val() : e('[name="' + n + '"]').length > 0 ? o = e('[name="' + n + '"]').val() : e('[name="' + n + '[]"]').length > 0 && (o = e('[name="' + n + '[]"]')), o !== i && t.toString() == o.toString();
      }, different: function different(t, n) {
        var o;e(this);return e('[data-validate="' + n + '"]').length > 0 ? o = e('[data-validate="' + n + '"]').val() : e("#" + n).length > 0 ? o = e("#" + n).val() : e('[name="' + n + '"]').length > 0 ? o = e('[name="' + n + '"]').val() : e('[name="' + n + '[]"]').length > 0 && (o = e('[name="' + n + '[]"]')), o !== i && t.toString() !== o.toString();
      }, creditCard: function creditCard(t, n) {
        var i,
            o,
            a = { visa: { pattern: /^4/, length: [16] }, amex: { pattern: /^3[47]/, length: [15] }, mastercard: { pattern: /^5[1-5]/, length: [16] }, discover: { pattern: /^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/, length: [16] }, unionPay: { pattern: /^(62|88)/, length: [16, 17, 18, 19] }, jcb: { pattern: /^35(2[89]|[3-8][0-9])/, length: [16] }, maestro: { pattern: /^(5018|5020|5038|6304|6759|676[1-3])/, length: [12, 13, 14, 15, 16, 17, 18, 19] }, dinersClub: { pattern: /^(30[0-5]|^36)/, length: [14] }, laser: { pattern: /^(6304|670[69]|6771)/, length: [16, 17, 18, 19] }, visaElectron: { pattern: /^(4026|417500|4508|4844|491(3|7))/, length: [16] } },
            r = {},
            s = !1,
            l = "string" == typeof n && n.split(",");if ("string" == typeof t && 0 !== t.length) {
          if (t = t.replace(/[\-]/g, ""), l && (e.each(l, function (n, i) {
            (o = a[i]) && (r = { length: -1 !== e.inArray(t.length, o.length), pattern: -1 !== t.search(o.pattern) }).length && r.pattern && (s = !0);
          }), !s)) return !1;if ((i = { number: -1 !== e.inArray(t.length, a.unionPay.length), pattern: -1 !== t.search(a.unionPay.pattern) }).number && i.pattern) return !0;for (var c = t.length, u = 0, d = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]], f = 0; c--;) {
            f += d[u][parseInt(t.charAt(c), 10)], u ^= 1;
          }return f % 10 == 0 && f > 0;
        }
      }, minCount: function minCount(e, t) {
        return 0 == t || (1 == t ? "" !== e : e.split(",").length >= t);
      }, exactCount: function exactCount(e, t) {
        return 0 == t ? "" === e : 1 == t ? "" !== e && -1 === e.search(",") : e.split(",").length == t;
      }, maxCount: function maxCount(e, t) {
        return 0 != t && (1 == t ? -1 === e.search(",") : e.split(",").length <= t);
      } } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.accordion = function (n) {
    var o,
        a = e(this),
        r = new Date().getTime(),
        s = [],
        l = arguments[0],
        c = "string" == typeof l,
        u = [].slice.call(arguments, 1);t.requestAnimationFrame || t.mozRequestAnimationFrame || t.webkitRequestAnimationFrame || t.msRequestAnimationFrame;return a.each(function () {
      var d,
          f,
          m = e.isPlainObject(n) ? e.extend(!0, {}, e.fn.accordion.settings, n) : e.extend({}, e.fn.accordion.settings),
          g = m.className,
          p = m.namespace,
          h = m.selector,
          v = m.error,
          b = "." + p,
          y = "module-" + p,
          x = a.selector || "",
          C = e(this),
          w = C.find(h.title),
          S = C.find(h.content),
          k = this,
          T = C.data(y);f = { initialize: function initialize() {
          f.debug("Initializing", C), f.bind.events(), m.observeChanges && f.observeChanges(), f.instantiate();
        }, instantiate: function instantiate() {
          T = f, C.data(y, f);
        }, destroy: function destroy() {
          f.debug("Destroying previous instance", C), C.off(b).removeData(y);
        }, refresh: function refresh() {
          w = C.find(h.title), S = C.find(h.content);
        }, observeChanges: function observeChanges() {
          "MutationObserver" in t && ((d = new MutationObserver(function (e) {
            f.debug("DOM tree modified, updating selector cache"), f.refresh();
          })).observe(k, { childList: !0, subtree: !0 }), f.debug("Setting up mutation observer", d));
        }, bind: { events: function events() {
            f.debug("Binding delegated events"), C.on(m.on + b, h.trigger, f.event.click);
          } }, event: { click: function click() {
            f.toggle.call(this);
          } }, toggle: function toggle(t) {
          var n = t !== i ? "number" == typeof t ? w.eq(t) : e(t).closest(h.title) : e(this).closest(h.title),
              o = n.next(S),
              a = o.hasClass(g.animating),
              r = o.hasClass(g.active),
              s = r && !a,
              l = !r && a;f.debug("Toggling visibility of content", n), s || l ? m.collapsible ? f.close.call(n) : f.debug("Cannot close accordion content collapsing is disabled") : f.open.call(n);
        }, open: function open(t) {
          var n = t !== i ? "number" == typeof t ? w.eq(t) : e(t).closest(h.title) : e(this).closest(h.title),
              o = n.next(S),
              a = o.hasClass(g.animating);o.hasClass(g.active) || a ? f.debug("Accordion already open, skipping", o) : (f.debug("Opening accordion content", n), m.onOpening.call(o), m.onChanging.call(o), m.exclusive && f.closeOthers.call(n), n.addClass(g.active), o.stop(!0, !0).addClass(g.animating), m.animateChildren && (e.fn.transition !== i && C.transition("is supported") ? o.children().transition({ animation: "fade in", queue: !1, useFailSafe: !0, debug: m.debug, verbose: m.verbose, duration: m.duration }) : o.children().stop(!0, !0).animate({ opacity: 1 }, m.duration, f.resetOpacity)), o.slideDown(m.duration, m.easing, function () {
            o.removeClass(g.animating).addClass(g.active), f.reset.display.call(this), m.onOpen.call(this), m.onChange.call(this);
          }));
        }, close: function close(t) {
          var n = t !== i ? "number" == typeof t ? w.eq(t) : e(t).closest(h.title) : e(this).closest(h.title),
              o = n.next(S),
              a = o.hasClass(g.animating),
              r = o.hasClass(g.active);!r && !(!r && a) || r && a || (f.debug("Closing accordion content", o), m.onClosing.call(o), m.onChanging.call(o), n.removeClass(g.active), o.stop(!0, !0).addClass(g.animating), m.animateChildren && (e.fn.transition !== i && C.transition("is supported") ? o.children().transition({ animation: "fade out", queue: !1, useFailSafe: !0, debug: m.debug, verbose: m.verbose, duration: m.duration }) : o.children().stop(!0, !0).animate({ opacity: 0 }, m.duration, f.resetOpacity)), o.slideUp(m.duration, m.easing, function () {
            o.removeClass(g.animating).removeClass(g.active), f.reset.display.call(this), m.onClose.call(this), m.onChange.call(this);
          }));
        }, closeOthers: function closeOthers(t) {
          var n,
              o,
              a,
              r = t !== i ? w.eq(t) : e(this).closest(h.title),
              s = r.parents(h.content).prev(h.title),
              l = r.closest(h.accordion),
              c = h.title + "." + g.active + ":visible",
              u = h.content + "." + g.active + ":visible";m.closeNested ? a = (n = l.find(c).not(s)).next(S) : (n = l.find(c).not(s), o = l.find(u).find(c).not(s), a = (n = n.not(o)).next(S)), n.length > 0 && (f.debug("Exclusive enabled, closing other content", n), n.removeClass(g.active), a.removeClass(g.animating).stop(!0, !0), m.animateChildren && (e.fn.transition !== i && C.transition("is supported") ? a.children().transition({ animation: "fade out", useFailSafe: !0, debug: m.debug, verbose: m.verbose, duration: m.duration }) : a.children().stop(!0, !0).animate({ opacity: 0 }, m.duration, f.resetOpacity)), a.slideUp(m.duration, m.easing, function () {
            e(this).removeClass(g.active), f.reset.display.call(this);
          }));
        }, reset: { display: function display() {
            f.verbose("Removing inline display from element", this), e(this).css("display", ""), "" === e(this).attr("style") && e(this).attr("style", "").removeAttr("style");
          }, opacity: function opacity() {
            f.verbose("Removing inline opacity from element", this), e(this).css("opacity", ""), "" === e(this).attr("style") && e(this).attr("style", "").removeAttr("style");
          } }, setting: function setting(t, n) {
          if (f.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, m, t);else {
            if (n === i) return m[t];e.isPlainObject(m[t]) ? e.extend(!0, m[t], n) : m[t] = n;
          }
        }, internal: function internal(t, n) {
          if (f.debug("Changing internal", t, n), n === i) return f[t];e.isPlainObject(t) ? e.extend(!0, f, t) : f[t] = n;
        }, debug: function debug() {
          !m.silent && m.debug && (m.performance ? f.performance.log(arguments) : (f.debug = Function.prototype.bind.call(console.info, console, m.name + ":"), f.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !m.silent && m.verbose && m.debug && (m.performance ? f.performance.log(arguments) : (f.verbose = Function.prototype.bind.call(console.info, console, m.name + ":"), f.verbose.apply(console, arguments)));
        }, error: function error() {
          m.silent || (f.error = Function.prototype.bind.call(console.error, console, m.name + ":"), f.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;m.performance && (n = (t = new Date().getTime()) - (r || t), r = t, s.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: k, "Execution Time": n })), clearTimeout(f.performance.timer), f.performance.timer = setTimeout(f.performance.display, 500);
          }, display: function display() {
            var t = m.name + ":",
                n = 0;r = !1, clearTimeout(f.performance.timer), e.each(s, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", x && (t += " '" + x + "'"), (console.group !== i || console.table !== i) && s.length > 0 && (console.groupCollapsed(t), console.table ? console.table(s) : e.each(s, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), s = [];
          } }, invoke: function invoke(t, n, a) {
          var r,
              s,
              l,
              c = T;return n = n || u, a = k || a, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i ? (s = c[o], !1) : (f.error(v.method, t), !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(a, n) : s !== i && (l = s), e.isArray(o) ? o.push(l) : o !== i ? o = [o, l] : l !== i && (o = l), s;
        } }, c ? (T === i && f.initialize(), f.invoke(l)) : (T !== i && T.invoke("destroy"), f.initialize());
    }), o !== i ? o : this;
  }, e.fn.accordion.settings = { name: "Accordion", namespace: "accordion", silent: !1, debug: !1, verbose: !1, performance: !0, on: "click", observeChanges: !0, exclusive: !0, collapsible: !0, closeNested: !1, animateChildren: !0, duration: 350, easing: "easeOutQuad", onOpening: function onOpening() {}, onClosing: function onClosing() {}, onChanging: function onChanging() {}, onOpen: function onOpen() {}, onClose: function onClose() {}, onChange: function onChange() {}, error: { method: "The method you called is not defined" }, className: { active: "active", animating: "animating" }, selector: { accordion: ".accordion", title: ".title", trigger: ".title", content: ".content" } }, e.extend(e.easing, { easeOutQuad: function easeOutQuad(e, t, n, i, o) {
      return -i * (t /= o) * (t - 2) + n;
    } });
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.checkbox = function (o) {
    var a,
        r = e(this),
        s = r.selector || "",
        l = new Date().getTime(),
        c = [],
        u = arguments[0],
        d = "string" == typeof u,
        f = [].slice.call(arguments, 1);return r.each(function () {
      var r,
          m,
          g = e.extend(!0, {}, e.fn.checkbox.settings, o),
          p = g.className,
          h = g.namespace,
          v = g.selector,
          b = g.error,
          y = "." + h,
          x = "module-" + h,
          C = e(this),
          w = e(this).children(v.label),
          S = e(this).children(v.input),
          k = S[0],
          T = !1,
          A = !1,
          R = C.data(x),
          P = this;m = { initialize: function initialize() {
          m.verbose("Initializing checkbox", g), m.create.label(), m.bind.events(), m.set.tabbable(), m.hide.input(), m.observeChanges(), m.instantiate(), m.setup();
        }, instantiate: function instantiate() {
          m.verbose("Storing instance of module", m), R = m, C.data(x, m);
        }, destroy: function destroy() {
          m.verbose("Destroying module"), m.unbind.events(), m.show.input(), C.removeData(x);
        }, fix: { reference: function reference() {
            C.is(v.input) && (m.debug("Behavior called on <input> adjusting invoked element"), C = C.closest(v.checkbox), m.refresh());
          } }, setup: function setup() {
          m.set.initialLoad(), m.is.indeterminate() ? (m.debug("Initial value is indeterminate"), m.indeterminate()) : m.is.checked() ? (m.debug("Initial value is checked"), m.check()) : (m.debug("Initial value is unchecked"), m.uncheck()), m.remove.initialLoad();
        }, refresh: function refresh() {
          w = C.children(v.label), S = C.children(v.input), k = S[0];
        }, hide: { input: function input() {
            m.verbose("Modifying <input> z-index to be unselectable"), S.addClass(p.hidden);
          } }, show: { input: function input() {
            m.verbose("Modifying <input> z-index to be selectable"), S.removeClass(p.hidden);
          } }, observeChanges: function observeChanges() {
          "MutationObserver" in t && ((r = new MutationObserver(function (e) {
            m.debug("DOM tree modified, updating selector cache"), m.refresh();
          })).observe(P, { childList: !0, subtree: !0 }), m.debug("Setting up mutation observer", r));
        }, attachEvents: function attachEvents(t, n) {
          var i = e(t);n = e.isFunction(m[n]) ? m[n] : m.toggle, i.length > 0 ? (m.debug("Attaching checkbox events to element", t, n), i.on("click" + y, n)) : m.error(b.notFound);
        }, event: { click: function click(t) {
            var n = e(t.target);n.is(v.input) ? m.verbose("Using default check action on initialized checkbox") : n.is(v.link) ? m.debug("Clicking link inside checkbox, skipping toggle") : (m.toggle(), S.focus(), t.preventDefault());
          }, keydown: function keydown(e) {
            var t = e.which,
                n = 13,
                i = 32;t == 27 ? (m.verbose("Escape key pressed blurring field"), S.blur(), A = !0) : e.ctrlKey || t != i && t != n ? A = !1 : (m.verbose("Enter/space key pressed, toggling checkbox"), m.toggle(), A = !0);
          }, keyup: function keyup(e) {
            A && e.preventDefault();
          } }, check: function check() {
          m.should.allowCheck() && (m.debug("Checking checkbox", S), m.set.checked(), m.should.ignoreCallbacks() || (g.onChecked.call(k), g.onChange.call(k)));
        }, uncheck: function uncheck() {
          m.should.allowUncheck() && (m.debug("Unchecking checkbox"), m.set.unchecked(), m.should.ignoreCallbacks() || (g.onUnchecked.call(k), g.onChange.call(k)));
        }, indeterminate: function indeterminate() {
          m.should.allowIndeterminate() ? m.debug("Checkbox is already indeterminate") : (m.debug("Making checkbox indeterminate"), m.set.indeterminate(), m.should.ignoreCallbacks() || (g.onIndeterminate.call(k), g.onChange.call(k)));
        }, determinate: function determinate() {
          m.should.allowDeterminate() ? m.debug("Checkbox is already determinate") : (m.debug("Making checkbox determinate"), m.set.determinate(), m.should.ignoreCallbacks() || (g.onDeterminate.call(k), g.onChange.call(k)));
        }, enable: function enable() {
          m.is.enabled() ? m.debug("Checkbox is already enabled") : (m.debug("Enabling checkbox"), m.set.enabled(), g.onEnable.call(k), g.onEnabled.call(k));
        }, disable: function disable() {
          m.is.disabled() ? m.debug("Checkbox is already disabled") : (m.debug("Disabling checkbox"), m.set.disabled(), g.onDisable.call(k), g.onDisabled.call(k));
        }, get: { radios: function radios() {
            var t = m.get.name();return e('input[name="' + t + '"]').closest(v.checkbox);
          }, otherRadios: function otherRadios() {
            return m.get.radios().not(C);
          }, name: function name() {
            return S.attr("name");
          } }, is: { initialLoad: function initialLoad() {
            return T;
          }, radio: function radio() {
            return S.hasClass(p.radio) || "radio" == S.attr("type");
          }, indeterminate: function indeterminate() {
            return S.prop("indeterminate") !== i && S.prop("indeterminate");
          }, checked: function checked() {
            return S.prop("checked") !== i && S.prop("checked");
          }, disabled: function disabled() {
            return S.prop("disabled") !== i && S.prop("disabled");
          }, enabled: function enabled() {
            return !m.is.disabled();
          }, determinate: function determinate() {
            return !m.is.indeterminate();
          }, unchecked: function unchecked() {
            return !m.is.checked();
          } }, should: { allowCheck: function allowCheck() {
            return m.is.determinate() && m.is.checked() && !m.should.forceCallbacks() ? (m.debug("Should not allow check, checkbox is already checked"), !1) : !1 !== g.beforeChecked.apply(k) || (m.debug("Should not allow check, beforeChecked cancelled"), !1);
          }, allowUncheck: function allowUncheck() {
            return m.is.determinate() && m.is.unchecked() && !m.should.forceCallbacks() ? (m.debug("Should not allow uncheck, checkbox is already unchecked"), !1) : !1 !== g.beforeUnchecked.apply(k) || (m.debug("Should not allow uncheck, beforeUnchecked cancelled"), !1);
          }, allowIndeterminate: function allowIndeterminate() {
            return m.is.indeterminate() && !m.should.forceCallbacks() ? (m.debug("Should not allow indeterminate, checkbox is already indeterminate"), !1) : !1 !== g.beforeIndeterminate.apply(k) || (m.debug("Should not allow indeterminate, beforeIndeterminate cancelled"), !1);
          }, allowDeterminate: function allowDeterminate() {
            return m.is.determinate() && !m.should.forceCallbacks() ? (m.debug("Should not allow determinate, checkbox is already determinate"), !1) : !1 !== g.beforeDeterminate.apply(k) || (m.debug("Should not allow determinate, beforeDeterminate cancelled"), !1);
          }, forceCallbacks: function forceCallbacks() {
            return m.is.initialLoad() && g.fireOnInit;
          }, ignoreCallbacks: function ignoreCallbacks() {
            return T && !g.fireOnInit;
          } }, can: { change: function change() {
            return !(C.hasClass(p.disabled) || C.hasClass(p.readOnly) || S.prop("disabled") || S.prop("readonly"));
          }, uncheck: function uncheck() {
            return "boolean" == typeof g.uncheckable ? g.uncheckable : !m.is.radio();
          } }, set: { initialLoad: function initialLoad() {
            T = !0;
          }, checked: function checked() {
            m.verbose("Setting class to checked"), C.removeClass(p.indeterminate).addClass(p.checked), m.is.radio() && m.uncheckOthers(), m.is.indeterminate() || !m.is.checked() ? (m.verbose("Setting state to checked", k), S.prop("indeterminate", !1).prop("checked", !0), m.trigger.change()) : m.debug("Input is already checked, skipping input property change");
          }, unchecked: function unchecked() {
            m.verbose("Removing checked class"), C.removeClass(p.indeterminate).removeClass(p.checked), m.is.indeterminate() || !m.is.unchecked() ? (m.debug("Setting state to unchecked"), S.prop("indeterminate", !1).prop("checked", !1), m.trigger.change()) : m.debug("Input is already unchecked");
          }, indeterminate: function indeterminate() {
            m.verbose("Setting class to indeterminate"), C.addClass(p.indeterminate), m.is.indeterminate() ? m.debug("Input is already indeterminate, skipping input property change") : (m.debug("Setting state to indeterminate"), S.prop("indeterminate", !0), m.trigger.change());
          }, determinate: function determinate() {
            m.verbose("Removing indeterminate class"), C.removeClass(p.indeterminate), m.is.determinate() ? m.debug("Input is already determinate, skipping input property change") : (m.debug("Setting state to determinate"), S.prop("indeterminate", !1));
          }, disabled: function disabled() {
            m.verbose("Setting class to disabled"), C.addClass(p.disabled), m.is.disabled() ? m.debug("Input is already disabled, skipping input property change") : (m.debug("Setting state to disabled"), S.prop("disabled", "disabled"), m.trigger.change());
          }, enabled: function enabled() {
            m.verbose("Removing disabled class"), C.removeClass(p.disabled), m.is.enabled() ? m.debug("Input is already enabled, skipping input property change") : (m.debug("Setting state to enabled"), S.prop("disabled", !1), m.trigger.change());
          }, tabbable: function tabbable() {
            m.verbose("Adding tabindex to checkbox"), S.attr("tabindex") === i && S.attr("tabindex", 0);
          } }, remove: { initialLoad: function initialLoad() {
            T = !1;
          } }, trigger: { change: function change() {
            var e = n.createEvent("HTMLEvents"),
                t = S[0];t && (m.verbose("Triggering native change event"), e.initEvent("change", !0, !1), t.dispatchEvent(e));
          } }, create: { label: function label() {
            S.prevAll(v.label).length > 0 ? (S.prev(v.label).detach().insertAfter(S), m.debug("Moving existing label", w)) : m.has.label() || (w = e("<label>").insertAfter(S), m.debug("Creating label", w));
          } }, has: { label: function label() {
            return w.length > 0;
          } }, bind: { events: function events() {
            m.verbose("Attaching checkbox events"), C.on("click" + y, m.event.click).on("keydown" + y, v.input, m.event.keydown).on("keyup" + y, v.input, m.event.keyup);
          } }, unbind: { events: function events() {
            m.debug("Removing events"), C.off(y);
          } }, uncheckOthers: function uncheckOthers() {
          var e = m.get.otherRadios();m.debug("Unchecking other radios", e), e.removeClass(p.checked);
        }, toggle: function toggle() {
          m.can.change() ? m.is.indeterminate() || m.is.unchecked() ? (m.debug("Currently unchecked"), m.check()) : m.is.checked() && m.can.uncheck() && (m.debug("Currently checked"), m.uncheck()) : m.is.radio() || m.debug("Checkbox is read-only or disabled, ignoring toggle");
        }, setting: function setting(t, n) {
          if (m.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, g, t);else {
            if (n === i) return g[t];e.isPlainObject(g[t]) ? e.extend(!0, g[t], n) : g[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, m, t);else {
            if (n === i) return m[t];m[t] = n;
          }
        }, debug: function debug() {
          !g.silent && g.debug && (g.performance ? m.performance.log(arguments) : (m.debug = Function.prototype.bind.call(console.info, console, g.name + ":"), m.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !g.silent && g.verbose && g.debug && (g.performance ? m.performance.log(arguments) : (m.verbose = Function.prototype.bind.call(console.info, console, g.name + ":"), m.verbose.apply(console, arguments)));
        }, error: function error() {
          g.silent || (m.error = Function.prototype.bind.call(console.error, console, g.name + ":"), m.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;g.performance && (n = (t = new Date().getTime()) - (l || t), l = t, c.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: P, "Execution Time": n })), clearTimeout(m.performance.timer), m.performance.timer = setTimeout(m.performance.display, 500);
          }, display: function display() {
            var t = g.name + ":",
                n = 0;l = !1, clearTimeout(m.performance.timer), e.each(c, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", s && (t += " '" + s + "'"), (console.group !== i || console.table !== i) && c.length > 0 && (console.groupCollapsed(t), console.table ? console.table(c) : e.each(c, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), c = [];
          } }, invoke: function invoke(t, n, o) {
          var r,
              s,
              l,
              c = R;return n = n || f, o = P || o, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i ? (s = c[o], !1) : (m.error(b.method, t), !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(o, n) : s !== i && (l = s), e.isArray(a) ? a.push(l) : a !== i ? a = [a, l] : l !== i && (a = l), s;
        } }, d ? (R === i && m.initialize(), m.invoke(u)) : (R !== i && R.invoke("destroy"), m.initialize());
    }), a !== i ? a : this;
  }, e.fn.checkbox.settings = { name: "Checkbox", namespace: "checkbox", silent: !1, debug: !1, verbose: !0, performance: !0, uncheckable: "auto", fireOnInit: !1, onChange: function onChange() {}, beforeChecked: function beforeChecked() {}, beforeUnchecked: function beforeUnchecked() {}, beforeDeterminate: function beforeDeterminate() {}, beforeIndeterminate: function beforeIndeterminate() {}, onChecked: function onChecked() {}, onUnchecked: function onUnchecked() {}, onDeterminate: function onDeterminate() {}, onIndeterminate: function onIndeterminate() {}, onEnable: function onEnable() {}, onDisable: function onDisable() {}, onEnabled: function onEnabled() {}, onDisabled: function onDisabled() {}, className: { checked: "checked", indeterminate: "indeterminate", disabled: "disabled", hidden: "hidden", radio: "radio", readOnly: "read-only" }, error: { method: "The method you called is not defined" }, selector: { checkbox: ".ui.checkbox", label: "label, .box", input: 'input[type="checkbox"], input[type="radio"]', link: "a[href]" } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.dimmer = function (t) {
    var o,
        a = e(this),
        r = new Date().getTime(),
        s = [],
        l = arguments[0],
        c = "string" == typeof l,
        u = [].slice.call(arguments, 1);return a.each(function () {
      var d,
          f,
          m,
          g = e.isPlainObject(t) ? e.extend(!0, {}, e.fn.dimmer.settings, t) : e.extend({}, e.fn.dimmer.settings),
          p = g.selector,
          h = g.namespace,
          v = g.className,
          b = g.error,
          y = "." + h,
          x = "module-" + h,
          C = a.selector || "",
          w = "ontouchstart" in n.documentElement ? "touchstart" : "click",
          S = e(this),
          k = this,
          T = S.data(x);(m = { preinitialize: function preinitialize() {
          m.is.dimmer() ? (f = S.parent(), d = S) : (f = S, d = m.has.dimmer() ? g.dimmerName ? f.find(p.dimmer).filter("." + g.dimmerName) : f.find(p.dimmer) : m.create(), m.set.variation());
        }, initialize: function initialize() {
          m.debug("Initializing dimmer", g), m.bind.events(), m.set.dimmable(), m.instantiate();
        }, instantiate: function instantiate() {
          m.verbose("Storing instance of module", m), T = m, S.data(x, T);
        }, destroy: function destroy() {
          m.verbose("Destroying previous module", d), m.unbind.events(), m.remove.variation(), f.off(y);
        }, bind: { events: function events() {
            m.is.page() && f.get(0).addEventListener("touchmove", m.event.preventScroll, { passive: !1 }), "hover" == g.on ? f.on("mouseenter" + y, m.show).on("mouseleave" + y, m.hide) : "click" == g.on && f.on(w + y, m.toggle), m.is.page() && (m.debug("Setting as a page dimmer", f), m.set.pageDimmer()), m.is.closable() && (m.verbose("Adding dimmer close event", d), f.on(w + y, p.dimmer, m.event.click));
          } }, unbind: { events: function events() {
            m.is.page() && f.get(0).removeEventListener("touchmove", m.event.preventScroll, { passive: !1 }), S.removeData(x), f.off(y);
          } }, event: { click: function click(t) {
            m.verbose("Determining if event occured on dimmer", t), (0 === d.find(t.target).length || e(t.target).is(p.content)) && (m.hide(), t.stopImmediatePropagation());
          }, preventScroll: function preventScroll(e) {
            e.preventDefault();
          } }, addContent: function addContent(t) {
          var n = e(t);m.debug("Add content to dimmer", n), n.parent()[0] !== d[0] && n.detach().appendTo(d);
        }, create: function create() {
          var t = e(g.template.dimmer());return g.dimmerName && (m.debug("Creating named dimmer", g.dimmerName), t.addClass(g.dimmerName)), t.appendTo(f), t;
        }, show: function show(t) {
          t = e.isFunction(t) ? t : function () {}, m.debug("Showing dimmer", d, g), m.is.dimmed() && !m.is.animating() || !m.is.enabled() ? m.debug("Dimmer is already shown or disabled") : (m.animate.show(t), g.onShow.call(k), g.onChange.call(k));
        }, hide: function hide(t) {
          t = e.isFunction(t) ? t : function () {}, m.is.dimmed() || m.is.animating() ? (m.debug("Hiding dimmer", d), m.animate.hide(t), g.onHide.call(k), g.onChange.call(k)) : m.debug("Dimmer is not visible");
        }, toggle: function toggle() {
          m.verbose("Toggling dimmer visibility", d), m.is.dimmed() ? m.hide() : m.show();
        }, animate: { show: function show(t) {
            t = e.isFunction(t) ? t : function () {}, g.useCSS && e.fn.transition !== i && d.transition("is supported") ? ("auto" !== g.opacity && m.set.opacity(), d.transition({ displayType: "flex", animation: g.transition + " in", queue: !1, duration: m.get.duration(), useFailSafe: !0, onStart: function onStart() {
                m.set.dimmed();
              }, onComplete: function onComplete() {
                m.set.active(), t();
              } })) : (m.verbose("Showing dimmer animation with javascript"), m.set.dimmed(), "auto" == g.opacity && (g.opacity = .8), d.stop().css({ opacity: 0, width: "100%", height: "100%" }).fadeTo(m.get.duration(), g.opacity, function () {
              d.removeAttr("style"), m.set.active(), t();
            }));
          }, hide: function hide(t) {
            t = e.isFunction(t) ? t : function () {}, g.useCSS && e.fn.transition !== i && d.transition("is supported") ? (m.verbose("Hiding dimmer with css"), d.transition({ displayType: "flex", animation: g.transition + " out", queue: !1, duration: m.get.duration(), useFailSafe: !0, onStart: function onStart() {
                m.remove.dimmed();
              }, onComplete: function onComplete() {
                m.remove.active(), t();
              } })) : (m.verbose("Hiding dimmer with javascript"), m.remove.dimmed(), d.stop().fadeOut(m.get.duration(), function () {
              m.remove.active(), d.removeAttr("style"), t();
            }));
          } }, get: { dimmer: function dimmer() {
            return d;
          }, duration: function duration() {
            return "object" == _typeof(g.duration) ? m.is.active() ? g.duration.hide : g.duration.show : g.duration;
          } }, has: { dimmer: function dimmer() {
            return g.dimmerName ? S.find(p.dimmer).filter("." + g.dimmerName).length > 0 : S.find(p.dimmer).length > 0;
          } }, is: { active: function active() {
            return d.hasClass(v.active);
          }, animating: function animating() {
            return d.is(":animated") || d.hasClass(v.animating);
          }, closable: function closable() {
            return "auto" == g.closable ? "hover" != g.on : g.closable;
          }, dimmer: function dimmer() {
            return S.hasClass(v.dimmer);
          }, dimmable: function dimmable() {
            return S.hasClass(v.dimmable);
          }, dimmed: function dimmed() {
            return f.hasClass(v.dimmed);
          }, disabled: function disabled() {
            return f.hasClass(v.disabled);
          }, enabled: function enabled() {
            return !m.is.disabled();
          }, page: function page() {
            return f.is("body");
          }, pageDimmer: function pageDimmer() {
            return d.hasClass(v.pageDimmer);
          } }, can: { show: function show() {
            return !d.hasClass(v.disabled);
          } }, set: { opacity: function opacity(e) {
            var t = d.css("background-color"),
                n = t.split(","),
                i = n && 3 == n.length,
                o = n && 4 == n.length;e = 0 === g.opacity ? 0 : g.opacity || e, i || o ? (n[3] = e + ")", t = n.join(",")) : t = "rgba(0, 0, 0, " + e + ")", m.debug("Setting opacity to", e), d.css("background-color", t);
          }, active: function active() {
            d.addClass(v.active);
          }, dimmable: function dimmable() {
            f.addClass(v.dimmable);
          }, dimmed: function dimmed() {
            f.addClass(v.dimmed);
          }, pageDimmer: function pageDimmer() {
            d.addClass(v.pageDimmer);
          }, disabled: function disabled() {
            d.addClass(v.disabled);
          }, variation: function variation(e) {
            (e = e || g.variation) && d.addClass(e);
          } }, remove: { active: function active() {
            d.removeClass(v.active);
          }, dimmed: function dimmed() {
            f.removeClass(v.dimmed);
          }, disabled: function disabled() {
            d.removeClass(v.disabled);
          }, variation: function variation(e) {
            (e = e || g.variation) && d.removeClass(e);
          } }, setting: function setting(t, n) {
          if (m.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, g, t);else {
            if (n === i) return g[t];e.isPlainObject(g[t]) ? e.extend(!0, g[t], n) : g[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, m, t);else {
            if (n === i) return m[t];m[t] = n;
          }
        }, debug: function debug() {
          !g.silent && g.debug && (g.performance ? m.performance.log(arguments) : (m.debug = Function.prototype.bind.call(console.info, console, g.name + ":"), m.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !g.silent && g.verbose && g.debug && (g.performance ? m.performance.log(arguments) : (m.verbose = Function.prototype.bind.call(console.info, console, g.name + ":"), m.verbose.apply(console, arguments)));
        }, error: function error() {
          g.silent || (m.error = Function.prototype.bind.call(console.error, console, g.name + ":"), m.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;g.performance && (n = (t = new Date().getTime()) - (r || t), r = t, s.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: k, "Execution Time": n })), clearTimeout(m.performance.timer), m.performance.timer = setTimeout(m.performance.display, 500);
          }, display: function display() {
            var t = g.name + ":",
                n = 0;r = !1, clearTimeout(m.performance.timer), e.each(s, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", C && (t += " '" + C + "'"), a.length > 1 && (t += " (" + a.length + ")"), (console.group !== i || console.table !== i) && s.length > 0 && (console.groupCollapsed(t), console.table ? console.table(s) : e.each(s, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), s = [];
          } }, invoke: function invoke(t, n, a) {
          var r,
              s,
              l,
              c = T;return n = n || u, a = k || a, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i ? (s = c[o], !1) : (m.error(b.method, t), !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(a, n) : s !== i && (l = s), e.isArray(o) ? o.push(l) : o !== i ? o = [o, l] : l !== i && (o = l), s;
        } }).preinitialize(), c ? (T === i && m.initialize(), m.invoke(l)) : (T !== i && T.invoke("destroy"), m.initialize());
    }), o !== i ? o : this;
  }, e.fn.dimmer.settings = { name: "Dimmer", namespace: "dimmer", silent: !1, debug: !1, verbose: !1, performance: !0, dimmerName: !1, variation: !1, closable: "auto", useCSS: !0, transition: "fade", on: !1, opacity: "auto", duration: { show: 500, hide: 500 }, onChange: function onChange() {}, onShow: function onShow() {}, onHide: function onHide() {}, error: { method: "The method you called is not defined." }, className: { active: "active", animating: "animating", dimmable: "dimmable", dimmed: "dimmed", dimmer: "dimmer", disabled: "disabled", hide: "hide", pageDimmer: "page", show: "show" }, selector: { dimmer: "> .ui.dimmer", content: ".ui.dimmer > .content, .ui.dimmer > .content > .center" }, template: { dimmer: function dimmer() {
        return e("<div />").attr("class", "ui dimmer");
      } } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.dropdown = function (o) {
    var a,
        r = e(this),
        s = e(n),
        l = r.selector || "",
        c = "ontouchstart" in n.documentElement,
        u = new Date().getTime(),
        d = [],
        f = arguments[0],
        m = "string" == typeof f,
        g = [].slice.call(arguments, 1);return r.each(function (p) {
      var h,
          v,
          b,
          y,
          x,
          C,
          w,
          S,
          k = e.isPlainObject(o) ? e.extend(!0, {}, e.fn.dropdown.settings, o) : e.extend({}, e.fn.dropdown.settings),
          T = k.className,
          A = k.message,
          R = k.fields,
          P = k.keys,
          E = k.metadata,
          F = k.namespace,
          O = k.regExp,
          D = k.selector,
          q = k.error,
          j = k.templates,
          z = "." + F,
          I = "module-" + F,
          M = e(this),
          L = e(k.context),
          V = M.find(D.text),
          N = M.find(D.search),
          H = M.find(D.sizer),
          U = M.find(D.input),
          W = M.find(D.icon),
          B = M.prev().find(D.text).length > 0 ? M.prev().find(D.text) : M.prev(),
          Q = M.children(D.menu),
          X = Q.find(D.item),
          $ = !1,
          Y = !1,
          Z = !1,
          K = this,
          J = M.data(I);S = { initialize: function initialize() {
          S.debug("Initializing dropdown", k), S.is.alreadySetup() ? S.setup.reference() : (S.setup.layout(), k.values && S.change.values(k.values), S.refreshData(), S.save.defaults(), S.restore.selected(), S.create.id(), S.bind.events(), S.observeChanges(), S.instantiate());
        }, instantiate: function instantiate() {
          S.verbose("Storing instance of dropdown", S), J = S, M.data(I, S);
        }, destroy: function destroy() {
          S.verbose("Destroying previous dropdown", M), S.remove.tabbable(), M.off(z).removeData(I), Q.off(z), s.off(y), S.disconnect.menuObserver(), S.disconnect.selectObserver();
        }, observeChanges: function observeChanges() {
          "MutationObserver" in t && (C = new MutationObserver(S.event.select.mutation), w = new MutationObserver(S.event.menu.mutation), S.debug("Setting up mutation observer", C, w), S.observe.select(), S.observe.menu());
        }, disconnect: { menuObserver: function menuObserver() {
            w && w.disconnect();
          }, selectObserver: function selectObserver() {
            C && C.disconnect();
          } }, observe: { select: function select() {
            S.has.input() && C.observe(M[0], { childList: !0, subtree: !0 });
          }, menu: function menu() {
            S.has.menu() && w.observe(Q[0], { childList: !0, subtree: !0 });
          } }, create: { id: function id() {
            x = (Math.random().toString(16) + "000000000").substr(2, 8), y = "." + x, S.verbose("Creating unique id for element", x);
          }, userChoice: function userChoice(t) {
            var n, o, a;return !!(t = t || S.get.userValues()) && (t = e.isArray(t) ? t : [t], e.each(t, function (t, r) {
              !1 === S.get.item(r) && (a = k.templates.addition(S.add.variables(A.addResult, r)), o = e("<div />").html(a).attr("data-" + E.value, r).attr("data-" + E.text, r).addClass(T.addition).addClass(T.item), k.hideAdditions && o.addClass(T.hidden), n = n === i ? o : n.add(o), S.verbose("Creating user choices for value", r, o));
            }), n);
          }, userLabels: function userLabels(t) {
            var n = S.get.userValues();n && (S.debug("Adding user labels", n), e.each(n, function (e, t) {
              S.verbose("Adding custom user value"), S.add.label(t, t);
            }));
          }, menu: function menu() {
            Q = e("<div />").addClass(T.menu).appendTo(M);
          }, sizer: function sizer() {
            H = e("<span />").addClass(T.sizer).insertAfter(N);
          } }, search: function search(e) {
          e = e !== i ? e : S.get.query(), S.verbose("Searching for query", e), S.has.minCharacters(e) ? S.filter(e) : S.hide();
        }, select: { firstUnfiltered: function firstUnfiltered() {
            S.verbose("Selecting first non-filtered element"), S.remove.selectedItem(), X.not(D.unselectable).not(D.addition + D.hidden).eq(0).addClass(T.selected);
          }, nextAvailable: function nextAvailable(e) {
            var t = (e = e.eq(0)).nextAll(D.item).not(D.unselectable).eq(0),
                n = e.prevAll(D.item).not(D.unselectable).eq(0);t.length > 0 ? (S.verbose("Moving selection to", t), t.addClass(T.selected)) : (S.verbose("Moving selection to", n), n.addClass(T.selected));
          } }, setup: { api: function api() {
            var e = { debug: k.debug, urlData: { value: S.get.value(), query: S.get.query() }, on: !1 };S.verbose("First request, initializing API"), M.api(e);
          }, layout: function layout() {
            M.is("select") && (S.setup.select(), S.setup.returnedObject()), S.has.menu() || S.create.menu(), S.is.search() && !S.has.search() && (S.verbose("Adding search input"), N = e("<input />").addClass(T.search).prop("autocomplete", "off").insertBefore(V)), S.is.multiple() && S.is.searchSelection() && !S.has.sizer() && S.create.sizer(), k.allowTab && S.set.tabbable();
          }, select: function select() {
            var t = S.get.selectValues();S.debug("Dropdown initialized on a select", t), M.is("select") && (U = M), U.parent(D.dropdown).length > 0 ? (S.debug("UI dropdown already exists. Creating dropdown menu only"), M = U.closest(D.dropdown), S.has.menu() || S.create.menu(), Q = M.children(D.menu), S.setup.menu(t)) : (S.debug("Creating entire dropdown from select"), M = e("<div />").attr("class", U.attr("class")).addClass(T.selection).addClass(T.dropdown).html(j.dropdown(t)).insertBefore(U), U.hasClass(T.multiple) && !1 === U.prop("multiple") && (S.error(q.missingMultiple), U.prop("multiple", !0)), U.is("[multiple]") && S.set.multiple(), U.prop("disabled") && (S.debug("Disabling dropdown"), M.addClass(T.disabled)), U.removeAttr("class").detach().prependTo(M)), S.refresh();
          }, menu: function menu(e) {
            Q.html(j.menu(e, R)), X = Q.find(D.item);
          }, reference: function reference() {
            S.debug("Dropdown behavior was called on select, replacing with closest dropdown"), M = M.parent(D.dropdown), J = M.data(I), K = M.get(0), S.refresh(), S.setup.returnedObject();
          }, returnedObject: function returnedObject() {
            var e = r.slice(0, p),
                t = r.slice(p + 1);r = e.add(M).add(t);
          } }, refresh: function refresh() {
          S.refreshSelectors(), S.refreshData();
        }, refreshItems: function refreshItems() {
          X = Q.find(D.item);
        }, refreshSelectors: function refreshSelectors() {
          S.verbose("Refreshing selector cache"), V = M.find(D.text), N = M.find(D.search), U = M.find(D.input), W = M.find(D.icon), B = M.prev().find(D.text).length > 0 ? M.prev().find(D.text) : M.prev(), Q = M.children(D.menu), X = Q.find(D.item);
        }, refreshData: function refreshData() {
          S.verbose("Refreshing cached metadata"), X.removeData(E.text).removeData(E.value);
        }, clearData: function clearData() {
          S.verbose("Clearing metadata"), X.removeData(E.text).removeData(E.value), M.removeData(E.defaultText).removeData(E.defaultValue).removeData(E.placeholderText);
        }, toggle: function toggle() {
          S.verbose("Toggling menu visibility"), S.is.active() ? S.hide() : S.show();
        }, show: function show(t) {
          if (t = e.isFunction(t) ? t : function () {}, !S.can.show() && S.is.remote() && (S.debug("No API results retrieved, searching before show"), S.queryRemote(S.get.query(), S.show)), S.can.show() && !S.is.active()) {
            if (S.debug("Showing dropdown"), !S.has.message() || S.has.maxSelections() || S.has.allResultsFiltered() || S.remove.message(), S.is.allFiltered()) return !0;!1 !== k.onShow.call(K) && S.animate.show(function () {
              S.can.click() && S.bind.intent(), S.has.menuSearch() && S.focusSearch(), S.set.visible(), t.call(K);
            });
          }
        }, hide: function hide(t) {
          t = e.isFunction(t) ? t : function () {}, S.is.active() && !S.is.animatingOutward() && (S.debug("Hiding dropdown"), !1 !== k.onHide.call(K) && S.animate.hide(function () {
            S.remove.visible(), t.call(K);
          }));
        }, hideOthers: function hideOthers() {
          S.verbose("Finding other dropdowns to hide"), r.not(M).has(D.menu + "." + T.visible).dropdown("hide");
        }, hideMenu: function hideMenu() {
          S.verbose("Hiding menu  instantaneously"), S.remove.active(), S.remove.visible(), Q.transition("hide");
        }, hideSubMenus: function hideSubMenus() {
          var e = Q.children(D.item).find(D.menu);S.verbose("Hiding sub menus", e), e.transition("hide");
        }, bind: { events: function events() {
            c && S.bind.touchEvents(), S.bind.keyboardEvents(), S.bind.inputEvents(), S.bind.mouseEvents();
          }, touchEvents: function touchEvents() {
            S.debug("Touch device detected binding additional touch events"), S.is.searchSelection() || S.is.single() && M.on("touchstart" + z, S.event.test.toggle), Q.on("touchstart" + z, D.item, S.event.item.mouseenter);
          }, keyboardEvents: function keyboardEvents() {
            S.verbose("Binding keyboard events"), M.on("keydown" + z, S.event.keydown), S.has.search() && M.on(S.get.inputEvent() + z, D.search, S.event.input), S.is.multiple() && s.on("keydown" + y, S.event.document.keydown);
          }, inputEvents: function inputEvents() {
            S.verbose("Binding input change events"), M.on("change" + z, D.input, S.event.change);
          }, mouseEvents: function mouseEvents() {
            S.verbose("Binding mouse events"), S.is.multiple() && M.on("click" + z, D.label, S.event.label.click).on("click" + z, D.remove, S.event.remove.click), S.is.searchSelection() ? (M.on("mousedown" + z, S.event.mousedown).on("mouseup" + z, S.event.mouseup).on("mousedown" + z, D.menu, S.event.menu.mousedown).on("mouseup" + z, D.menu, S.event.menu.mouseup).on("click" + z, D.icon, S.event.icon.click).on("focus" + z, D.search, S.event.search.focus).on("click" + z, D.search, S.event.search.focus).on("blur" + z, D.search, S.event.search.blur).on("click" + z, D.text, S.event.text.focus), S.is.multiple() && M.on("click" + z, S.event.click)) : ("click" == k.on ? M.on("click" + z, D.icon, S.event.icon.click).on("click" + z, S.event.test.toggle) : "hover" == k.on ? M.on("mouseenter" + z, S.delay.show).on("mouseleave" + z, S.delay.hide) : M.on(k.on + z, S.toggle), M.on("mousedown" + z, S.event.mousedown).on("mouseup" + z, S.event.mouseup).on("focus" + z, S.event.focus), S.has.menuSearch() ? M.on("blur" + z, D.search, S.event.search.blur) : M.on("blur" + z, S.event.blur)), Q.on("mouseenter" + z, D.item, S.event.item.mouseenter).on("mouseleave" + z, D.item, S.event.item.mouseleave).on("click" + z, D.item, S.event.item.click);
          }, intent: function intent() {
            S.verbose("Binding hide intent event to document"), c && s.on("touchstart" + y, S.event.test.touch).on("touchmove" + y, S.event.test.touch), s.on("click" + y, S.event.test.hide);
          } }, unbind: { intent: function intent() {
            S.verbose("Removing hide intent event from document"), c && s.off("touchstart" + y).off("touchmove" + y), s.off("click" + y);
          } }, filter: function filter(e) {
          var t = e !== i ? e : S.get.query(),
              n = function n() {
            S.is.multiple() && S.filterActive(), (e || !e && 0 == S.get.activeItem().length) && S.select.firstUnfiltered(), S.has.allResultsFiltered() ? k.onNoResults.call(K, t) ? k.allowAdditions ? k.hideAdditions && (S.verbose("User addition with no menu, setting empty style"), S.set.empty(), S.hideMenu()) : (S.verbose("All items filtered, showing message", t), S.add.message(A.noResults)) : (S.verbose("All items filtered, hiding dropdown", t), S.hideMenu()) : (S.remove.empty(), S.remove.message()), k.allowAdditions && S.add.userSuggestion(e), S.is.searchSelection() && S.can.show() && S.is.focusedOnSearch() && S.show();
          };k.useLabels && S.has.maxSelections() || (k.apiSettings ? S.can.useAPI() ? S.queryRemote(t, function () {
            k.filterRemoteData && S.filterItems(t), n();
          }) : S.error(q.noAPI) : (S.filterItems(t), n()));
        }, queryRemote: function queryRemote(t, n) {
          var i = { errorDuration: !1, cache: "local", throttle: k.throttle, urlData: { query: t }, onError: function onError() {
              S.add.message(A.serverError), n();
            }, onFailure: function onFailure() {
              S.add.message(A.serverError), n();
            }, onSuccess: function onSuccess(t) {
              var i = t[R.remoteValues];e.isArray(i) && i.length > 0 ? (S.remove.message(), S.setup.menu({ values: t[R.remoteValues] })) : S.add.message(A.noResults), n();
            } };M.api("get request") || S.setup.api(), i = e.extend(!0, {}, i, k.apiSettings), M.api("setting", i).api("query");
        }, filterItems: function filterItems(t) {
          var n = t !== i ? t : S.get.query(),
              o = null,
              a = S.escape.string(n),
              r = new RegExp("^" + a, "igm");S.has.query() && (o = [], S.verbose("Searching for matching values", n), X.each(function () {
            var t,
                i,
                a = e(this);if ("both" == k.match || "text" == k.match) {
              if (-1 !== (t = String(S.get.choiceText(a, !1))).search(r)) return o.push(this), !0;if ("exact" === k.fullTextSearch && S.exactSearch(n, t)) return o.push(this), !0;if (!0 === k.fullTextSearch && S.fuzzySearch(n, t)) return o.push(this), !0;
            }if ("both" == k.match || "value" == k.match) {
              if (-1 !== (i = String(S.get.choiceValue(a, t))).search(r)) return o.push(this), !0;if ("exact" === k.fullTextSearch && S.exactSearch(n, i)) return o.push(this), !0;if (!0 === k.fullTextSearch && S.fuzzySearch(n, i)) return o.push(this), !0;
            }
          })), S.debug("Showing only matched items", n), S.remove.filteredItem(), o && X.not(o).addClass(T.filtered);
        }, fuzzySearch: function fuzzySearch(e, t) {
          var n = t.length,
              i = e.length;if (e = e.toLowerCase(), t = t.toLowerCase(), i > n) return !1;if (i === n) return e === t;e: for (var o = 0, a = 0; o < i; o++) {
            for (var r = e.charCodeAt(o); a < n;) {
              if (t.charCodeAt(a++) === r) continue e;
            }return !1;
          }return !0;
        }, exactSearch: function exactSearch(e, t) {
          return e = e.toLowerCase(), (t = t.toLowerCase()).indexOf(e) > -1;
        }, filterActive: function filterActive() {
          k.useLabels && X.filter("." + T.active).addClass(T.filtered);
        }, focusSearch: function focusSearch(e) {
          S.has.search() && !S.is.focusedOnSearch() && (e ? (M.off("focus" + z, D.search), N.focus(), M.on("focus" + z, D.search, S.event.search.focus)) : N.focus());
        }, forceSelection: function forceSelection() {
          var e = X.not(T.filtered).filter("." + T.selected).eq(0),
              t = X.not(T.filtered).filter("." + T.active).eq(0),
              n = e.length > 0 ? e : t;if (n.length > 0 && !S.is.multiple()) return S.debug("Forcing partial selection to selected item", n), void S.event.item.click.call(n, {}, !0);k.allowAdditions ? (S.set.selected(S.get.query()), S.remove.searchTerm()) : S.remove.searchTerm();
        }, change: { values: function values(t) {
            k.allowAdditions || S.clear(), S.debug("Creating dropdown with specified values", t), S.setup.menu({ values: t }), e.each(t, function (e, t) {
              if (1 == t.selected) return S.debug("Setting initial selection to", t.value), S.set.selected(t.value), !0;
            });
          } }, event: { change: function change() {
            Z || (S.debug("Input changed, updating selection"), S.set.selected());
          }, focus: function focus() {
            k.showOnFocus && !$ && S.is.hidden() && !v && S.show();
          }, blur: function blur(e) {
            v = n.activeElement === this, $ || v || (S.remove.activeLabel(), S.hide());
          }, mousedown: function mousedown() {
            S.is.searchSelection() ? b = !0 : $ = !0;
          }, mouseup: function mouseup() {
            S.is.searchSelection() ? b = !1 : $ = !1;
          }, click: function click(t) {
            e(t.target).is(M) && (S.is.focusedOnSearch() ? S.show() : S.focusSearch());
          }, search: { focus: function focus() {
              $ = !0, S.is.multiple() && S.remove.activeLabel(), k.showOnFocus && S.search();
            }, blur: function blur(e) {
              v = n.activeElement === this, S.is.searchSelection() && !b && (Y || v || (k.forceSelection && S.forceSelection(), S.hide())), b = !1;
            } }, icon: { click: function click(e) {
              S.toggle();
            } }, text: { focus: function focus(e) {
              $ = !0, S.focusSearch();
            } }, input: function input(e) {
            (S.is.multiple() || S.is.searchSelection()) && S.set.filtered(), clearTimeout(S.timer), S.timer = setTimeout(S.search, k.delay.search);
          }, label: { click: function click(t) {
              var n = e(this),
                  i = M.find(D.label),
                  o = i.filter("." + T.active),
                  a = n.nextAll("." + T.active),
                  r = n.prevAll("." + T.active),
                  s = a.length > 0 ? n.nextUntil(a).add(o).add(n) : n.prevUntil(r).add(o).add(n);t.shiftKey ? (o.removeClass(T.active), s.addClass(T.active)) : t.ctrlKey ? n.toggleClass(T.active) : (o.removeClass(T.active), n.addClass(T.active)), k.onLabelSelect.apply(this, i.filter("." + T.active));
            } }, remove: { click: function click() {
              var t = e(this).parent();t.hasClass(T.active) ? S.remove.activeLabels() : S.remove.activeLabels(t);
            } }, test: { toggle: function toggle(e) {
              var t = S.is.multiple() ? S.show : S.toggle;S.is.bubbledLabelClick(e) || S.is.bubbledIconClick(e) || S.determine.eventOnElement(e, t) && e.preventDefault();
            }, touch: function touch(e) {
              S.determine.eventOnElement(e, function () {
                "touchstart" == e.type ? S.timer = setTimeout(function () {
                  S.hide();
                }, k.delay.touch) : "touchmove" == e.type && clearTimeout(S.timer);
              }), e.stopPropagation();
            }, hide: function hide(e) {
              S.determine.eventInModule(e, S.hide);
            } }, select: { mutation: function mutation(t) {
              S.debug("<select> modified, recreating menu");var n = !1;e.each(t, function (t, i) {
                if (e(i.target).is("select") || e(i.addedNodes).is("select")) return n = !0, !0;
              }), n && (S.disconnect.selectObserver(), S.refresh(), S.setup.select(), S.set.selected(), S.observe.select());
            } }, menu: { mutation: function mutation(t) {
              var n = t[0],
                  i = n.addedNodes ? e(n.addedNodes[0]) : e(!1),
                  o = n.removedNodes ? e(n.removedNodes[0]) : e(!1),
                  a = i.add(o),
                  r = a.is(D.addition) || a.closest(D.addition).length > 0,
                  s = a.is(D.message) || a.closest(D.message).length > 0;r || s ? (S.debug("Updating item selector cache"), S.refreshItems()) : (S.debug("Menu modified, updating selector cache"), S.refresh());
            }, mousedown: function mousedown() {
              Y = !0;
            }, mouseup: function mouseup() {
              Y = !1;
            } }, item: { mouseenter: function mouseenter(t) {
              var n = e(t.target),
                  i = e(this),
                  o = i.children(D.menu),
                  a = i.siblings(D.item).children(D.menu),
                  r = o.length > 0;!(o.find(n).length > 0) && r && (clearTimeout(S.itemTimer), S.itemTimer = setTimeout(function () {
                S.verbose("Showing sub-menu", o), e.each(a, function () {
                  S.animate.hide(!1, e(this));
                }), S.animate.show(!1, o);
              }, k.delay.show), t.preventDefault());
            }, mouseleave: function mouseleave(t) {
              var n = e(this).children(D.menu);n.length > 0 && (clearTimeout(S.itemTimer), S.itemTimer = setTimeout(function () {
                S.verbose("Hiding sub-menu", n), S.animate.hide(!1, n);
              }, k.delay.hide));
            }, click: function click(t, i) {
              var o = e(this),
                  a = e(t ? t.target : ""),
                  r = o.find(D.menu),
                  s = S.get.choiceText(o),
                  l = S.get.choiceValue(o, s),
                  c = r.length > 0,
                  u = r.find(a).length > 0;S.has.menuSearch() && e(n.activeElement).blur(), u || c && !k.allowCategorySelection || (S.is.searchSelection() && (k.allowAdditions && S.remove.userAddition(), S.remove.searchTerm(), S.is.focusedOnSearch() || 1 == i || S.focusSearch(!0)), k.useLabels || (S.remove.filteredItem(), S.set.scrollPosition(o)), S.determine.selectAction.call(this, s, l));
            } }, document: { keydown: function keydown(e) {
              var t = e.which;if (S.is.inObject(t, P)) {
                var n = M.find(D.label),
                    i = n.filter("." + T.active),
                    o = (i.data(E.value), n.index(i)),
                    a = n.length,
                    r = i.length > 0,
                    s = i.length > 1,
                    l = 0 === o,
                    c = o + 1 == a,
                    u = S.is.searchSelection(),
                    d = S.is.focusedOnSearch(),
                    f = S.is.focused(),
                    m = d && 0 === S.get.caretPosition();if (u && !r && !d) return;t == P.leftArrow ? !f && !m || r ? r && (e.shiftKey ? S.verbose("Adding previous label to selection") : (S.verbose("Selecting previous label"), n.removeClass(T.active)), l && !s ? i.addClass(T.active) : i.prev(D.siblingLabel).addClass(T.active).end(), e.preventDefault()) : (S.verbose("Selecting previous label"), n.last().addClass(T.active)) : t == P.rightArrow ? (f && !r && n.first().addClass(T.active), r && (e.shiftKey ? S.verbose("Adding next label to selection") : (S.verbose("Selecting next label"), n.removeClass(T.active)), c ? u ? d ? n.removeClass(T.active) : S.focusSearch() : s ? i.next(D.siblingLabel).addClass(T.active) : i.addClass(T.active) : i.next(D.siblingLabel).addClass(T.active), e.preventDefault())) : t == P.deleteKey || t == P.backspace ? r ? (S.verbose("Removing active labels"), c && u && !d && S.focusSearch(), i.last().next(D.siblingLabel).addClass(T.active), S.remove.activeLabels(i), e.preventDefault()) : m && !r && t == P.backspace && (S.verbose("Removing last label on input backspace"), i = n.last().addClass(T.active), S.remove.activeLabels(i)) : i.removeClass(T.active);
              }
            } }, keydown: function keydown(e) {
            var t = e.which;if (S.is.inObject(t, P)) {
              var n,
                  i = X.not(D.unselectable).filter("." + T.selected).eq(0),
                  o = Q.children("." + T.active).eq(0),
                  a = i.length > 0 ? i : o,
                  r = a.length > 0 ? a.siblings(":not(." + T.filtered + ")").addBack() : Q.children(":not(." + T.filtered + ")"),
                  s = a.children(D.menu),
                  l = a.closest(D.menu),
                  c = l.hasClass(T.visible) || l.hasClass(T.animating) || l.parent(D.menu).length > 0,
                  u = s.length > 0,
                  d = a.length > 0,
                  f = a.not(D.unselectable).length > 0,
                  m = t == P.delimiter && k.allowAdditions && S.is.multiple();if (k.allowAdditions && k.hideAdditions && (t == P.enter || m) && f && (S.verbose("Selecting item from keyboard shortcut", a), S.event.item.click.call(a, e), S.is.searchSelection() && S.remove.searchTerm()), S.is.visible()) {
                if ((t == P.enter || m) && (t == P.enter && d && u && !k.allowCategorySelection ? (S.verbose("Pressed enter on unselectable category, opening sub menu"), t = P.rightArrow) : f && (S.verbose("Selecting item from keyboard shortcut", a), S.event.item.click.call(a, e), S.is.searchSelection() && S.remove.searchTerm()), e.preventDefault()), d && (t == P.leftArrow && l[0] !== Q[0] && (S.verbose("Left key pressed, closing sub-menu"), S.animate.hide(!1, l), a.removeClass(T.selected), l.closest(D.item).addClass(T.selected), e.preventDefault()), t == P.rightArrow && u && (S.verbose("Right key pressed, opening sub-menu"), S.animate.show(!1, s), a.removeClass(T.selected), s.find(D.item).eq(0).addClass(T.selected), e.preventDefault())), t == P.upArrow) {
                  if (n = d && c ? a.prevAll(D.item + ":not(" + D.unselectable + ")").eq(0) : X.eq(0), r.index(n) < 0) return S.verbose("Up key pressed but reached top of current menu"), void e.preventDefault();S.verbose("Up key pressed, changing active item"), a.removeClass(T.selected), n.addClass(T.selected), S.set.scrollPosition(n), k.selectOnKeydown && S.is.single() && S.set.selectedItem(n), e.preventDefault();
                }if (t == P.downArrow) {
                  if (0 === (n = d && c ? n = a.nextAll(D.item + ":not(" + D.unselectable + ")").eq(0) : X.eq(0)).length) return S.verbose("Down key pressed but reached bottom of current menu"), void e.preventDefault();S.verbose("Down key pressed, changing active item"), X.removeClass(T.selected), n.addClass(T.selected), S.set.scrollPosition(n), k.selectOnKeydown && S.is.single() && S.set.selectedItem(n), e.preventDefault();
                }t == P.pageUp && (S.scrollPage("up"), e.preventDefault()), t == P.pageDown && (S.scrollPage("down"), e.preventDefault()), t == P.escape && (S.verbose("Escape key pressed, closing dropdown"), S.hide());
              } else m && e.preventDefault(), t != P.downArrow || S.is.visible() || (S.verbose("Down key pressed, showing dropdown"), S.show(), e.preventDefault());
            } else S.has.search() || S.set.selectedLetter(String.fromCharCode(t));
          } }, trigger: { change: function change() {
            var e = n.createEvent("HTMLEvents"),
                t = U[0];t && (S.verbose("Triggering native change event"), e.initEvent("change", !0, !1), t.dispatchEvent(e));
          } }, determine: { selectAction: function selectAction(t, n) {
            S.verbose("Determining action", k.action), e.isFunction(S.action[k.action]) ? (S.verbose("Triggering preset action", k.action, t, n), S.action[k.action].call(K, t, n, this)) : e.isFunction(k.action) ? (S.verbose("Triggering user action", k.action, t, n), k.action.call(K, t, n, this)) : S.error(q.action, k.action);
          }, eventInModule: function eventInModule(t, i) {
            var o = e(t.target),
                a = o.closest(n.documentElement).length > 0,
                r = o.closest(M).length > 0;return i = e.isFunction(i) ? i : function () {}, a && !r ? (S.verbose("Triggering event", i), i(), !0) : (S.verbose("Event occurred in dropdown, canceling callback"), !1);
          }, eventOnElement: function eventOnElement(t, i) {
            var o = e(t.target),
                a = o.closest(D.siblingLabel),
                r = n.body.contains(t.target),
                s = 0 === M.find(a).length,
                l = 0 === o.closest(Q).length;return i = e.isFunction(i) ? i : function () {}, r && s && l ? (S.verbose("Triggering event", i), i(), !0) : (S.verbose("Event occurred in dropdown menu, canceling callback"), !1);
          } }, action: { nothing: function nothing() {}, activate: function activate(t, n, o) {
            if (n = n !== i ? n : t, S.can.activate(e(o))) {
              if (S.set.selected(n, e(o)), S.is.multiple() && !S.is.allFiltered()) return;S.hideAndClear();
            }
          }, select: function select(t, n, o) {
            if (n = n !== i ? n : t, S.can.activate(e(o))) {
              if (S.set.value(n, t, e(o)), S.is.multiple() && !S.is.allFiltered()) return;S.hideAndClear();
            }
          }, combo: function combo(t, n, o) {
            n = n !== i ? n : t, S.set.selected(n, e(o)), S.hideAndClear();
          }, hide: function hide(e, t, n) {
            S.set.value(t, e), S.hideAndClear();
          } }, get: { id: function id() {
            return x;
          }, defaultText: function defaultText() {
            return M.data(E.defaultText);
          }, defaultValue: function defaultValue() {
            return M.data(E.defaultValue);
          }, placeholderText: function placeholderText() {
            return "auto" != k.placeholder && "string" == typeof k.placeholder ? k.placeholder : M.data(E.placeholderText) || "";
          }, text: function text() {
            return V.text();
          }, query: function query() {
            return e.trim(N.val());
          }, searchWidth: function searchWidth(e) {
            return e = e !== i ? e : N.val(), H.text(e), Math.ceil(H.width() + 1);
          }, selectionCount: function selectionCount() {
            var t = S.get.values();return S.is.multiple() ? e.isArray(t) ? t.length : 0 : "" !== S.get.value() ? 1 : 0;
          }, transition: function transition(e) {
            return "auto" == k.transition ? S.is.upward(e) ? "slide up" : "slide down" : k.transition;
          }, userValues: function userValues() {
            var t = S.get.values();return !!t && (t = e.isArray(t) ? t : [t], e.grep(t, function (e) {
              return !1 === S.get.item(e);
            }));
          }, uniqueArray: function uniqueArray(t) {
            return e.grep(t, function (n, i) {
              return e.inArray(n, t) === i;
            });
          }, caretPosition: function caretPosition() {
            var e,
                t,
                i = N.get(0);return "selectionStart" in i ? i.selectionStart : n.selection ? (i.focus(), t = (e = n.selection.createRange()).text.length, e.moveStart("character", -i.value.length), e.text.length - t) : void 0;
          }, value: function value() {
            var t = U.length > 0 ? U.val() : M.data(E.value),
                n = e.isArray(t) && 1 === t.length && "" === t[0];return t === i || n ? "" : t;
          }, values: function values() {
            var e = S.get.value();return "" === e ? "" : !S.has.selectInput() && S.is.multiple() ? "string" == typeof e ? e.split(k.delimiter) : "" : e;
          }, remoteValues: function remoteValues() {
            var t = S.get.values(),
                n = !1;return t && ("string" == typeof t && (t = [t]), e.each(t, function (e, t) {
              var i = S.read.remoteData(t);S.verbose("Restoring value from session data", i, t), i && (n || (n = {}), n[t] = i);
            })), n;
          }, choiceText: function choiceText(t, n) {
            if (n = n !== i ? n : k.preserveHTML, t) return t.find(D.menu).length > 0 && (S.verbose("Retrieving text of element with sub-menu"), (t = t.clone()).find(D.menu).remove(), t.find(D.menuIcon).remove()), t.data(E.text) !== i ? t.data(E.text) : n ? e.trim(t.html()) : e.trim(t.text());
          }, choiceValue: function choiceValue(t, n) {
            return n = n || S.get.choiceText(t), !!t && (t.data(E.value) !== i ? String(t.data(E.value)) : "string" == typeof n ? e.trim(n.toLowerCase()) : String(n));
          }, inputEvent: function inputEvent() {
            var e = N[0];return !!e && (e.oninput !== i ? "input" : e.onpropertychange !== i ? "propertychange" : "keyup");
          }, selectValues: function selectValues() {
            var t = { values: [] };return M.find("option").each(function () {
              var n = e(this),
                  o = n.html(),
                  a = n.attr("disabled"),
                  r = n.attr("value") !== i ? n.attr("value") : o;"auto" === k.placeholder && "" === r ? t.placeholder = o : t.values.push({ name: o, value: r, disabled: a });
            }), k.placeholder && "auto" !== k.placeholder && (S.debug("Setting placeholder value to", k.placeholder), t.placeholder = k.placeholder), k.sortSelect ? (t.values.sort(function (e, t) {
              return e.name > t.name ? 1 : -1;
            }), S.debug("Retrieved and sorted values from select", t)) : S.debug("Retrieved values from select", t), t;
          }, activeItem: function activeItem() {
            return X.filter("." + T.active);
          }, selectedItem: function selectedItem() {
            var e = X.not(D.unselectable).filter("." + T.selected);return e.length > 0 ? e : X.eq(0);
          }, itemWithAdditions: function itemWithAdditions(e) {
            var t = S.get.item(e),
                n = S.create.userChoice(e);return n && n.length > 0 && (t = t.length > 0 ? t.add(n) : n), t;
          }, item: function item(t, n) {
            var o,
                a,
                r = !1;return t = t !== i ? t : S.get.values() !== i ? S.get.values() : S.get.text(), o = a ? t.length > 0 : t !== i && null !== t, a = S.is.multiple() && e.isArray(t), n = "" === t || 0 === t || n || !1, o && X.each(function () {
              var o = e(this),
                  s = S.get.choiceText(o),
                  l = S.get.choiceValue(o, s);if (null !== l && l !== i) if (a) -1 === e.inArray(String(l), t) && -1 === e.inArray(s, t) || (r = r ? r.add(o) : o);else if (n) {
                if (S.verbose("Ambiguous dropdown value using strict type check", o, t), l === t || s === t) return r = o, !0;
              } else if (String(l) == String(t) || s == t) return S.verbose("Found select item by value", l, t), r = o, !0;
            }), r;
          } }, check: { maxSelections: function maxSelections(e) {
            return !k.maxSelections || ((e = e !== i ? e : S.get.selectionCount()) >= k.maxSelections ? (S.debug("Maximum selection count reached"), k.useLabels && (X.addClass(T.filtered), S.add.message(A.maxSelections)), !0) : (S.verbose("No longer at maximum selection count"), S.remove.message(), S.remove.filteredItem(), S.is.searchSelection() && S.filterItems(), !1));
          } }, restore: { defaults: function defaults() {
            S.clear(), S.restore.defaultText(), S.restore.defaultValue();
          }, defaultText: function defaultText() {
            var e = S.get.defaultText();e === S.get.placeholderText ? (S.debug("Restoring default placeholder text", e), S.set.placeholderText(e)) : (S.debug("Restoring default text", e), S.set.text(e));
          }, placeholderText: function placeholderText() {
            S.set.placeholderText();
          }, defaultValue: function defaultValue() {
            var e = S.get.defaultValue();e !== i && (S.debug("Restoring default value", e), "" !== e ? (S.set.value(e), S.set.selected()) : (S.remove.activeItem(), S.remove.selectedItem()));
          }, labels: function labels() {
            k.allowAdditions && (k.useLabels || (S.error(q.labels), k.useLabels = !0), S.debug("Restoring selected values"), S.create.userLabels()), S.check.maxSelections();
          }, selected: function selected() {
            S.restore.values(), S.is.multiple() ? (S.debug("Restoring previously selected values and labels"), S.restore.labels()) : S.debug("Restoring previously selected values");
          }, values: function values() {
            S.set.initialLoad(), k.apiSettings && k.saveRemoteData && S.get.remoteValues() ? S.restore.remoteValues() : S.set.selected(), S.remove.initialLoad();
          }, remoteValues: function remoteValues() {
            var t = S.get.remoteValues();S.debug("Recreating selected from session data", t), t && (S.is.single() ? e.each(t, function (e, t) {
              S.set.text(t);
            }) : e.each(t, function (e, t) {
              S.add.label(e, t);
            }));
          } }, read: { remoteData: function remoteData(e) {
            var n;if (t.Storage !== i) return (n = sessionStorage.getItem(e)) !== i && n;S.error(q.noStorage);
          } }, save: { defaults: function defaults() {
            S.save.defaultText(), S.save.placeholderText(), S.save.defaultValue();
          }, defaultValue: function defaultValue() {
            var e = S.get.value();S.verbose("Saving default value as", e), M.data(E.defaultValue, e);
          }, defaultText: function defaultText() {
            var e = S.get.text();S.verbose("Saving default text as", e), M.data(E.defaultText, e);
          }, placeholderText: function placeholderText() {
            var e;!1 !== k.placeholder && V.hasClass(T.placeholder) && (e = S.get.text(), S.verbose("Saving placeholder text as", e), M.data(E.placeholderText, e));
          }, remoteData: function remoteData(e, n) {
            t.Storage !== i ? (S.verbose("Saving remote data to session storage", n, e), sessionStorage.setItem(n, e)) : S.error(q.noStorage);
          } }, clear: function clear() {
          S.is.multiple() && k.useLabels ? S.remove.labels() : (S.remove.activeItem(), S.remove.selectedItem()), S.set.placeholderText(), S.clearValue();
        }, clearValue: function clearValue() {
          S.set.value("");
        }, scrollPage: function scrollPage(e, t) {
          var n,
              i,
              o = t || S.get.selectedItem(),
              a = o.closest(D.menu),
              r = a.outerHeight(),
              s = a.scrollTop(),
              l = X.eq(0).outerHeight(),
              c = Math.floor(r / l),
              u = (a.prop("scrollHeight"), "up" == e ? s - l * c : s + l * c),
              d = X.not(D.unselectable);i = "up" == e ? d.index(o) - c : d.index(o) + c, (n = ("up" == e ? i >= 0 : i < d.length) ? d.eq(i) : "up" == e ? d.first() : d.last()).length > 0 && (S.debug("Scrolling page", e, n), o.removeClass(T.selected), n.addClass(T.selected), k.selectOnKeydown && S.is.single() && S.set.selectedItem(n), a.scrollTop(u));
        }, set: { filtered: function filtered() {
            var e = S.is.multiple(),
                t = S.is.searchSelection(),
                n = e && t,
                i = t ? S.get.query() : "",
                o = "string" == typeof i && i.length > 0,
                a = S.get.searchWidth(),
                r = "" !== i;e && o && (S.verbose("Adjusting input width", a, k.glyphWidth), N.css("width", a)), o || n && r ? (S.verbose("Hiding placeholder text"), V.addClass(T.filtered)) : (!e || n && !r) && (S.verbose("Showing placeholder text"), V.removeClass(T.filtered));
          }, empty: function empty() {
            M.addClass(T.empty);
          }, loading: function loading() {
            M.addClass(T.loading);
          }, placeholderText: function placeholderText(e) {
            e = e || S.get.placeholderText(), S.debug("Setting placeholder text", e), S.set.text(e), V.addClass(T.placeholder);
          }, tabbable: function tabbable() {
            S.is.searchSelection() ? (S.debug("Added tabindex to searchable dropdown"), N.val("").attr("tabindex", 0), Q.attr("tabindex", -1)) : (S.debug("Added tabindex to dropdown"), M.attr("tabindex") === i && (M.attr("tabindex", 0), Q.attr("tabindex", -1)));
          }, initialLoad: function initialLoad() {
            S.verbose("Setting initial load"), h = !0;
          }, activeItem: function activeItem(e) {
            k.allowAdditions && e.filter(D.addition).length > 0 ? e.addClass(T.filtered) : e.addClass(T.active);
          }, partialSearch: function partialSearch(e) {
            var t = S.get.query().length;N.val(e.substr(0, t));
          }, scrollPosition: function scrollPosition(e, t) {
            var n, o, a, r, s, l;n = (e = e || S.get.selectedItem()).closest(D.menu), o = e && e.length > 0, t = t !== i && t, e && n.length > 0 && o && (e.position().top, n.addClass(T.loading), a = (r = n.scrollTop()) - n.offset().top + e.offset().top, t || (l = r + n.height() < a + 5, s = a - 5 < r), S.debug("Scrolling to active item", a), (t || s || l) && n.scrollTop(a), n.removeClass(T.loading));
          }, text: function text(e) {
            "select" !== k.action && ("combo" == k.action ? (S.debug("Changing combo button text", e, B), k.preserveHTML ? B.html(e) : B.text(e)) : (e !== S.get.placeholderText() && V.removeClass(T.placeholder), S.debug("Changing text", e, V), V.removeClass(T.filtered), k.preserveHTML ? V.html(e) : V.text(e)));
          }, selectedItem: function selectedItem(e) {
            var t = S.get.choiceValue(e),
                n = S.get.choiceText(e, !1),
                i = S.get.choiceText(e, !0);S.debug("Setting user selection to item", e), S.remove.activeItem(), S.set.partialSearch(n), S.set.activeItem(e), S.set.selected(t, e), S.set.text(i);
          }, selectedLetter: function selectedLetter(t) {
            var n,
                i = X.filter("." + T.selected),
                o = !1;i.length > 0 && S.has.firstLetter(i, t) && (n = i.nextAll(X).eq(0), S.has.firstLetter(n, t) && (o = n)), o || X.each(function () {
              if (S.has.firstLetter(e(this), t)) return o = e(this), !1;
            }), o && (S.verbose("Scrolling to next value with letter", t), S.set.scrollPosition(o), i.removeClass(T.selected), o.addClass(T.selected), k.selectOnKeydown && S.is.single() && S.set.selectedItem(o));
          }, direction: function direction(e) {
            "auto" == k.direction ? (S.remove.upward(), S.can.openDownward(e) ? S.remove.upward(e) : S.set.upward(e), S.is.leftward(e) || S.can.openRightward(e) || S.set.leftward(e)) : "upward" == k.direction && S.set.upward(e);
          }, upward: function upward(e) {
            (e || M).addClass(T.upward);
          }, leftward: function leftward(e) {
            (e || Q).addClass(T.leftward);
          }, value: function value(e, t, n) {
            var o = S.escape.value(e),
                a = U.length > 0,
                r = S.get.values(),
                s = e !== i ? String(e) : e;if (a) {
              if (!k.allowReselection && s == r && (S.verbose("Skipping value update already same value", e, r), !S.is.initialLoad())) return;S.is.single() && S.has.selectInput() && S.can.extendSelect() && (S.debug("Adding user option", e), S.add.optionValue(e)), S.debug("Updating input value", o, r), Z = !0, U.val(o), !1 === k.fireOnInit && S.is.initialLoad() ? S.debug("Input native change event ignored on initial load") : S.trigger.change(), Z = !1;
            } else S.verbose("Storing value in metadata", o, U), o !== r && M.data(E.value, s);!1 === k.fireOnInit && S.is.initialLoad() ? S.verbose("No callback on initial load", k.onChange) : k.onChange.call(K, e, t, n);
          }, active: function active() {
            M.addClass(T.active);
          }, multiple: function multiple() {
            M.addClass(T.multiple);
          }, visible: function visible() {
            M.addClass(T.visible);
          }, exactly: function exactly(e, t) {
            S.debug("Setting selected to exact values"), S.clear(), S.set.selected(e, t);
          }, selected: function selected(t, n) {
            var i = S.is.multiple();(n = k.allowAdditions ? n || S.get.itemWithAdditions(t) : n || S.get.item(t)) && (S.debug("Setting selected menu item to", n), S.is.multiple() && S.remove.searchWidth(), S.is.single() ? (S.remove.activeItem(), S.remove.selectedItem()) : k.useLabels && S.remove.selectedItem(), n.each(function () {
              var t = e(this),
                  o = S.get.choiceText(t),
                  a = S.get.choiceValue(t, o),
                  r = t.hasClass(T.filtered),
                  s = t.hasClass(T.active),
                  l = t.hasClass(T.addition),
                  c = i && 1 == n.length;i ? !s || l ? (k.apiSettings && k.saveRemoteData && S.save.remoteData(o, a), k.useLabels ? (S.add.label(a, o, c), S.add.value(a, o, t), S.set.activeItem(t), S.filterActive(), S.select.nextAvailable(n)) : (S.add.value(a, o, t), S.set.text(S.add.variables(A.count)), S.set.activeItem(t))) : r || (S.debug("Selected active value, removing label"), S.remove.selected(a)) : (k.apiSettings && k.saveRemoteData && S.save.remoteData(o, a), S.set.text(o), S.set.value(a, o, t), t.addClass(T.active).addClass(T.selected));
            }));
          } }, add: { label: function label(t, n, i) {
            var o,
                a = S.is.searchSelection() ? N : V,
                r = S.escape.value(t);k.ignoreCase && (r = r.toLowerCase()), o = e("<a />").addClass(T.label).attr("data-" + E.value, r).html(j.label(r, n)), o = k.onLabelCreate.call(o, r, n), S.has.label(t) ? S.debug("User selection already exists, skipping", r) : (k.label.variation && o.addClass(k.label.variation), !0 === i ? (S.debug("Animating in label", o), o.addClass(T.hidden).insertBefore(a).transition(k.label.transition, k.label.duration)) : (S.debug("Adding selection label", o), o.insertBefore(a)));
          }, message: function message(t) {
            var n = Q.children(D.message),
                i = k.templates.message(S.add.variables(t));n.length > 0 ? n.html(i) : n = e("<div/>").html(i).addClass(T.message).appendTo(Q);
          }, optionValue: function optionValue(t) {
            var n = S.escape.value(t);U.find('option[value="' + S.escape.string(n) + '"]').length > 0 || (S.disconnect.selectObserver(), S.is.single() && (S.verbose("Removing previous user addition"), U.find("option." + T.addition).remove()), e("<option/>").prop("value", n).addClass(T.addition).html(t).appendTo(U), S.verbose("Adding user addition as an <option>", t), S.observe.select());
          }, userSuggestion: function userSuggestion(e) {
            var t,
                n = Q.children(D.addition),
                i = S.get.item(e),
                o = i && i.not(D.addition).length,
                a = n.length > 0;k.useLabels && S.has.maxSelections() || ("" === e || o ? n.remove() : (a ? (n.data(E.value, e).data(E.text, e).attr("data-" + E.value, e).attr("data-" + E.text, e).removeClass(T.filtered), k.hideAdditions || (t = k.templates.addition(S.add.variables(A.addResult, e)), n.html(t)), S.verbose("Replacing user suggestion with new value", n)) : ((n = S.create.userChoice(e)).prependTo(Q), S.verbose("Adding item choice to menu corresponding with user choice addition", n)), k.hideAdditions && !S.is.allFiltered() || n.addClass(T.selected).siblings().removeClass(T.selected), S.refreshItems()));
          }, variables: function variables(e, t) {
            var n,
                i,
                o = -1 !== e.search("{count}"),
                a = -1 !== e.search("{maxCount}"),
                r = -1 !== e.search("{term}");return S.verbose("Adding templated variables to message", e), o && (n = S.get.selectionCount(), e = e.replace("{count}", n)), a && (n = S.get.selectionCount(), e = e.replace("{maxCount}", k.maxSelections)), r && (i = t || S.get.query(), e = e.replace("{term}", i)), e;
          }, value: function value(t, n, i) {
            var o,
                a = S.get.values();S.has.value(t) ? S.debug("Value already selected") : "" !== t ? (e.isArray(a) ? (o = a.concat([t]), o = S.get.uniqueArray(o)) : o = [t], S.has.selectInput() ? S.can.extendSelect() && (S.debug("Adding value to select", t, o, U), S.add.optionValue(t)) : (o = o.join(k.delimiter), S.debug("Setting hidden input to delimited value", o, U)), !1 === k.fireOnInit && S.is.initialLoad() ? S.verbose("Skipping onadd callback on initial load", k.onAdd) : k.onAdd.call(K, t, n, i), S.set.value(o, t, n, i), S.check.maxSelections()) : S.debug("Cannot select blank values from multiselect");
          } }, remove: { active: function active() {
            M.removeClass(T.active);
          }, activeLabel: function activeLabel() {
            M.find(D.label).removeClass(T.active);
          }, empty: function empty() {
            M.removeClass(T.empty);
          }, loading: function loading() {
            M.removeClass(T.loading);
          }, initialLoad: function initialLoad() {
            h = !1;
          }, upward: function upward(e) {
            (e || M).removeClass(T.upward);
          }, leftward: function leftward(e) {
            (e || Q).removeClass(T.leftward);
          }, visible: function visible() {
            M.removeClass(T.visible);
          }, activeItem: function activeItem() {
            X.removeClass(T.active);
          }, filteredItem: function filteredItem() {
            k.useLabels && S.has.maxSelections() || (k.useLabels && S.is.multiple() ? X.not("." + T.active).removeClass(T.filtered) : X.removeClass(T.filtered), S.remove.empty());
          }, optionValue: function optionValue(e) {
            var t = S.escape.value(e),
                n = U.find('option[value="' + S.escape.string(t) + '"]');n.length > 0 && n.hasClass(T.addition) && (C && (C.disconnect(), S.verbose("Temporarily disconnecting mutation observer")), n.remove(), S.verbose("Removing user addition as an <option>", t), C && C.observe(U[0], { childList: !0, subtree: !0 }));
          }, message: function message() {
            Q.children(D.message).remove();
          }, searchWidth: function searchWidth() {
            N.css("width", "");
          }, searchTerm: function searchTerm() {
            S.verbose("Cleared search term"), N.val(""), S.set.filtered();
          }, userAddition: function userAddition() {
            X.filter(D.addition).remove();
          }, selected: function selected(t, n) {
            if (!(n = k.allowAdditions ? n || S.get.itemWithAdditions(t) : n || S.get.item(t))) return !1;n.each(function () {
              var t = e(this),
                  n = S.get.choiceText(t),
                  i = S.get.choiceValue(t, n);S.is.multiple() ? k.useLabels ? (S.remove.value(i, n, t), S.remove.label(i)) : (S.remove.value(i, n, t), 0 === S.get.selectionCount() ? S.set.placeholderText() : S.set.text(S.add.variables(A.count))) : S.remove.value(i, n, t), t.removeClass(T.filtered).removeClass(T.active), k.useLabels && t.removeClass(T.selected);
            });
          }, selectedItem: function selectedItem() {
            X.removeClass(T.selected);
          }, value: function value(e, t, n) {
            var i,
                o = S.get.values();S.has.selectInput() ? (S.verbose("Input is <select> removing selected option", e), i = S.remove.arrayValue(e, o), S.remove.optionValue(e)) : (S.verbose("Removing from delimited values", e), i = (i = S.remove.arrayValue(e, o)).join(k.delimiter)), !1 === k.fireOnInit && S.is.initialLoad() ? S.verbose("No callback on initial load", k.onRemove) : k.onRemove.call(K, e, t, n), S.set.value(i, t, n), S.check.maxSelections();
          }, arrayValue: function arrayValue(t, n) {
            return e.isArray(n) || (n = [n]), n = e.grep(n, function (e) {
              return t != e;
            }), S.verbose("Removed value from delimited string", t, n), n;
          }, label: function label(e, t) {
            var n = M.find(D.label).filter("[data-" + E.value + '="' + S.escape.string(e) + '"]');S.verbose("Removing label", n), n.remove();
          }, activeLabels: function activeLabels(e) {
            e = e || M.find(D.label).filter("." + T.active), S.verbose("Removing active label selections", e), S.remove.labels(e);
          }, labels: function labels(t) {
            t = t || M.find(D.label), S.verbose("Removing labels", t), t.each(function () {
              var t = e(this),
                  n = t.data(E.value),
                  o = n !== i ? String(n) : n,
                  a = S.is.userValue(o);!1 !== k.onLabelRemove.call(t, n) ? (S.remove.message(), a ? (S.remove.value(o), S.remove.label(o)) : S.remove.selected(o)) : S.debug("Label remove callback cancelled removal");
            });
          }, tabbable: function tabbable() {
            S.is.searchSelection() ? (S.debug("Searchable dropdown initialized"), N.removeAttr("tabindex"), Q.removeAttr("tabindex")) : (S.debug("Simple selection dropdown initialized"), M.removeAttr("tabindex"), Q.removeAttr("tabindex"));
          } }, has: { menuSearch: function menuSearch() {
            return S.has.search() && N.closest(Q).length > 0;
          }, search: function search() {
            return N.length > 0;
          }, sizer: function sizer() {
            return H.length > 0;
          }, selectInput: function selectInput() {
            return U.is("select");
          }, minCharacters: function minCharacters(e) {
            return !k.minCharacters || (e = e !== i ? String(e) : String(S.get.query())).length >= k.minCharacters;
          }, firstLetter: function firstLetter(e, t) {
            var n;return !(!e || 0 === e.length || "string" != typeof t) && (n = S.get.choiceText(e, !1), (t = t.toLowerCase()) == String(n).charAt(0).toLowerCase());
          }, input: function input() {
            return U.length > 0;
          }, items: function items() {
            return X.length > 0;
          }, menu: function menu() {
            return Q.length > 0;
          }, message: function message() {
            return 0 !== Q.children(D.message).length;
          }, label: function label(e) {
            var t = S.escape.value(e),
                n = M.find(D.label);return k.ignoreCase && (t = t.toLowerCase()), n.filter("[data-" + E.value + '="' + S.escape.string(t) + '"]').length > 0;
          }, maxSelections: function maxSelections() {
            return k.maxSelections && S.get.selectionCount() >= k.maxSelections;
          }, allResultsFiltered: function allResultsFiltered() {
            var e = X.not(D.addition);return e.filter(D.unselectable).length === e.length;
          }, userSuggestion: function userSuggestion() {
            return Q.children(D.addition).length > 0;
          }, query: function query() {
            return "" !== S.get.query();
          }, value: function value(e) {
            return k.ignoreCase ? S.has.valueIgnoringCase(e) : S.has.valueMatchingCase(e);
          }, valueMatchingCase: function valueMatchingCase(t) {
            var n = S.get.values();return !!(e.isArray(n) ? n && -1 !== e.inArray(t, n) : n == t);
          }, valueIgnoringCase: function valueIgnoringCase(t) {
            var n = S.get.values(),
                i = !1;return e.isArray(n) || (n = [n]), e.each(n, function (e, n) {
              if (String(t).toLowerCase() == String(n).toLowerCase()) return i = !0, !1;
            }), i;
          } }, is: { active: function active() {
            return M.hasClass(T.active);
          }, animatingInward: function animatingInward() {
            return Q.transition("is inward");
          }, animatingOutward: function animatingOutward() {
            return Q.transition("is outward");
          }, bubbledLabelClick: function bubbledLabelClick(t) {
            return e(t.target).is("select, input") && M.closest("label").length > 0;
          }, bubbledIconClick: function bubbledIconClick(t) {
            return e(t.target).closest(W).length > 0;
          }, alreadySetup: function alreadySetup() {
            return M.is("select") && M.parent(D.dropdown).data(I) !== i && 0 === M.prev().length;
          }, animating: function animating(e) {
            return e ? e.transition && e.transition("is animating") : Q.transition && Q.transition("is animating");
          }, leftward: function leftward(e) {
            return (e || Q).hasClass(T.leftward);
          }, disabled: function disabled() {
            return M.hasClass(T.disabled);
          }, focused: function focused() {
            return n.activeElement === M[0];
          }, focusedOnSearch: function focusedOnSearch() {
            return n.activeElement === N[0];
          }, allFiltered: function allFiltered() {
            return (S.is.multiple() || S.has.search()) && !(0 == k.hideAdditions && S.has.userSuggestion()) && !S.has.message() && S.has.allResultsFiltered();
          }, hidden: function hidden(e) {
            return !S.is.visible(e);
          }, initialLoad: function initialLoad() {
            return h;
          }, inObject: function inObject(t, n) {
            var i = !1;return e.each(n, function (e, n) {
              if (n == t) return i = !0, !0;
            }), i;
          }, multiple: function multiple() {
            return M.hasClass(T.multiple);
          }, remote: function remote() {
            return k.apiSettings && S.can.useAPI();
          }, single: function single() {
            return !S.is.multiple();
          }, selectMutation: function selectMutation(t) {
            var n = !1;return e.each(t, function (t, i) {
              if (i.target && e(i.target).is("select")) return n = !0, !0;
            }), n;
          }, search: function search() {
            return M.hasClass(T.search);
          }, searchSelection: function searchSelection() {
            return S.has.search() && 1 === N.parent(D.dropdown).length;
          }, selection: function selection() {
            return M.hasClass(T.selection);
          }, userValue: function userValue(t) {
            return -1 !== e.inArray(t, S.get.userValues());
          }, upward: function upward(e) {
            return (e || M).hasClass(T.upward);
          }, visible: function visible(e) {
            return e ? e.hasClass(T.visible) : Q.hasClass(T.visible);
          }, verticallyScrollableContext: function verticallyScrollableContext() {
            var e = L.get(0) !== t && L.css("overflow-y");return "auto" == e || "scroll" == e;
          }, horizontallyScrollableContext: function horizontallyScrollableContext() {
            var e = L.get(0) !== t && L.css("overflow-X");return "auto" == e || "scroll" == e;
          } }, can: { activate: function activate(e) {
            return !!k.useLabels || !S.has.maxSelections() || !(!S.has.maxSelections() || !e.hasClass(T.active));
          }, openDownward: function openDownward(e) {
            var n,
                i,
                o = e || Q,
                a = !0;return o.addClass(T.loading), i = { context: { offset: L.get(0) === t ? { top: 0, left: 0 } : L.offset(), scrollTop: L.scrollTop(), height: L.outerHeight() }, menu: { offset: o.offset(), height: o.outerHeight() } }, S.is.verticallyScrollableContext() && (i.menu.offset.top += i.context.scrollTop), (n = { above: i.context.scrollTop <= i.menu.offset.top - i.context.offset.top - i.menu.height, below: i.context.scrollTop + i.context.height >= i.menu.offset.top - i.context.offset.top + i.menu.height }).below ? (S.verbose("Dropdown can fit in context downward", n), a = !0) : n.below || n.above ? (S.verbose("Dropdown cannot fit below, opening upward", n), a = !1) : (S.verbose("Dropdown cannot fit in either direction, favoring downward", n), a = !0), o.removeClass(T.loading), a;
          }, openRightward: function openRightward(e) {
            var n,
                i,
                o = e || Q,
                a = !0;return o.addClass(T.loading), i = { context: { offset: L.get(0) === t ? { top: 0, left: 0 } : L.offset(), scrollLeft: L.scrollLeft(), width: L.outerWidth() }, menu: { offset: o.offset(), width: o.outerWidth() } }, S.is.horizontallyScrollableContext() && (i.menu.offset.left += i.context.scrollLeft), (n = i.menu.offset.left - i.context.offset.left + i.menu.width >= i.context.scrollLeft + i.context.width) && (S.verbose("Dropdown cannot fit in context rightward", n), a = !1), o.removeClass(T.loading), a;
          }, click: function click() {
            return c || "click" == k.on;
          }, extendSelect: function extendSelect() {
            return k.allowAdditions || k.apiSettings;
          }, show: function show() {
            return !S.is.disabled() && (S.has.items() || S.has.message());
          }, useAPI: function useAPI() {
            return e.fn.api !== i;
          } }, animate: { show: function show(t, n) {
            var o,
                a = n || Q,
                r = n ? function () {} : function () {
              S.hideSubMenus(), S.hideOthers(), S.set.active();
            };t = e.isFunction(t) ? t : function () {}, S.verbose("Doing menu show animation", a), S.set.direction(n), o = S.get.transition(n), S.is.selection() && S.set.scrollPosition(S.get.selectedItem(), !0), (S.is.hidden(a) || S.is.animating(a)) && ("none" == o ? (r(), a.transition("show"), t.call(K)) : e.fn.transition !== i && M.transition("is supported") ? a.transition({ animation: o + " in", debug: k.debug, verbose: k.verbose, duration: k.duration, queue: !0, onStart: r, onComplete: function onComplete() {
                t.call(K);
              } }) : S.error(q.noTransition, o));
          }, hide: function hide(t, n) {
            var o = n || Q,
                a = (n ? k.duration : k.duration, n ? function () {} : function () {
              S.can.click() && S.unbind.intent(), S.remove.active();
            }),
                r = S.get.transition(n);t = e.isFunction(t) ? t : function () {}, (S.is.visible(o) || S.is.animating(o)) && (S.verbose("Doing menu hide animation", o), "none" == r ? (a(), o.transition("hide"), t.call(K)) : e.fn.transition !== i && M.transition("is supported") ? o.transition({ animation: r + " out", duration: k.duration, debug: k.debug, verbose: k.verbose, queue: !1, onStart: a, onComplete: function onComplete() {
                t.call(K);
              } }) : S.error(q.transition));
          } }, hideAndClear: function hideAndClear() {
          S.remove.searchTerm(), S.has.maxSelections() || (S.has.search() ? S.hide(function () {
            S.remove.filteredItem();
          }) : S.hide());
        }, delay: { show: function show() {
            S.verbose("Delaying show event to ensure user intent"), clearTimeout(S.timer), S.timer = setTimeout(S.show, k.delay.show);
          }, hide: function hide() {
            S.verbose("Delaying hide event to ensure user intent"), clearTimeout(S.timer), S.timer = setTimeout(S.hide, k.delay.hide);
          } }, escape: { value: function value(t) {
            var n = e.isArray(t),
                i = "string" == typeof t,
                o = !i && !n,
                a = i && -1 !== t.search(O.quote),
                r = [];return o || !a ? t : (S.debug("Encoding quote values for use in select", t), n ? (e.each(t, function (e, t) {
              r.push(t.replace(O.quote, "&quot;"));
            }), r) : t.replace(O.quote, "&quot;"));
          }, string: function string(e) {
            return (e = String(e)).replace(O.escape, "\\$&");
          } }, setting: function setting(t, n) {
          if (S.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, k, t);else {
            if (n === i) return k[t];e.isPlainObject(k[t]) ? e.extend(!0, k[t], n) : k[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, S, t);else {
            if (n === i) return S[t];S[t] = n;
          }
        }, debug: function debug() {
          !k.silent && k.debug && (k.performance ? S.performance.log(arguments) : (S.debug = Function.prototype.bind.call(console.info, console, k.name + ":"), S.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !k.silent && k.verbose && k.debug && (k.performance ? S.performance.log(arguments) : (S.verbose = Function.prototype.bind.call(console.info, console, k.name + ":"), S.verbose.apply(console, arguments)));
        }, error: function error() {
          k.silent || (S.error = Function.prototype.bind.call(console.error, console, k.name + ":"), S.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;k.performance && (n = (t = new Date().getTime()) - (u || t), u = t, d.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: K, "Execution Time": n })), clearTimeout(S.performance.timer), S.performance.timer = setTimeout(S.performance.display, 500);
          }, display: function display() {
            var t = k.name + ":",
                n = 0;u = !1, clearTimeout(S.performance.timer), e.each(d, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", l && (t += " '" + l + "'"), (console.group !== i || console.table !== i) && d.length > 0 && (console.groupCollapsed(t), console.table ? console.table(d) : e.each(d, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), d = [];
          } }, invoke: function invoke(t, n, o) {
          var r,
              s,
              l,
              c = J;return n = n || g, o = K || o, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i ? (s = c[o], !1) : (S.error(q.method, t), !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(o, n) : s !== i && (l = s), e.isArray(a) ? a.push(l) : a !== i ? a = [a, l] : l !== i && (a = l), s;
        } }, m ? (J === i && S.initialize(), S.invoke(f)) : (J !== i && J.invoke("destroy"), S.initialize());
    }), a !== i ? a : r;
  }, e.fn.dropdown.settings = { silent: !1, debug: !1, verbose: !1, performance: !0, on: "click", action: "activate", values: !1, apiSettings: !1, selectOnKeydown: !0, minCharacters: 0, filterRemoteData: !1, saveRemoteData: !0, throttle: 200, context: t, direction: "auto", keepOnScreen: !0, match: "both", fullTextSearch: !1, placeholder: "auto", preserveHTML: !0, sortSelect: !1, forceSelection: !0, allowAdditions: !1, ignoreCase: !1, hideAdditions: !0, maxSelections: !1, useLabels: !0, delimiter: ",", showOnFocus: !0, allowReselection: !1, allowTab: !0, allowCategorySelection: !1, fireOnInit: !1, transition: "auto", duration: 200, glyphWidth: 1.037, label: { transition: "scale", duration: 200, variation: !1 }, delay: { hide: 300, show: 200, search: 20, touch: 50 }, onChange: function onChange(e, t, n) {}, onAdd: function onAdd(e, t, n) {}, onRemove: function onRemove(e, t, n) {}, onLabelSelect: function onLabelSelect(e) {}, onLabelCreate: function onLabelCreate(t, n) {
      return e(this);
    }, onLabelRemove: function onLabelRemove(e) {
      return !0;
    }, onNoResults: function onNoResults(e) {
      return !0;
    }, onShow: function onShow() {}, onHide: function onHide() {}, name: "Dropdown", namespace: "dropdown", message: { addResult: "Add <b>{term}</b>", count: "{count} selected", maxSelections: "Max {maxCount} selections", noResults: "No results found.", serverError: "There was an error contacting the server" }, error: { action: "You called a dropdown action that was not defined", alreadySetup: "Once a select has been initialized behaviors must be called on the created ui dropdown", labels: "Allowing user additions currently requires the use of labels.", missingMultiple: "<select> requires multiple property to be set to correctly preserve multiple values", method: "The method you called is not defined.", noAPI: "The API module is required to load resources remotely", noStorage: "Saving remote data requires session storage", noTransition: "This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>" }, regExp: { escape: /[-[\]{}()*+?.,\\^$|#\s]/g, quote: /"/g }, metadata: { defaultText: "defaultText", defaultValue: "defaultValue", placeholderText: "placeholder", text: "text", value: "value" }, fields: { remoteValues: "results", values: "values", disabled: "disabled", name: "name", value: "value", text: "text" }, keys: { backspace: 8, delimiter: 188, deleteKey: 46, enter: 13, escape: 27, pageUp: 33, pageDown: 34, leftArrow: 37, upArrow: 38, rightArrow: 39, downArrow: 40 }, selector: { addition: ".addition", dropdown: ".ui.dropdown", hidden: ".hidden", icon: "> .dropdown.icon", input: '> input[type="hidden"], > select', item: ".item", label: "> .label", remove: "> .label > .delete.icon", siblingLabel: ".label", menu: ".menu", message: ".message", menuIcon: ".dropdown.icon", search: "input.search, .menu > .search > input, .menu input.search", sizer: "> input.sizer", text: "> .text:not(.icon)", unselectable: ".disabled, .filtered" }, className: { active: "active", addition: "addition", animating: "animating", disabled: "disabled", empty: "empty", dropdown: "ui dropdown", filtered: "filtered", hidden: "hidden transition", item: "item", label: "ui label", loading: "loading", menu: "menu", message: "message", multiple: "multiple", placeholder: "default", sizer: "sizer", search: "search", selected: "selected", selection: "selection", upward: "upward", leftward: "left", visible: "visible" } }, e.fn.dropdown.settings.templates = { dropdown: function dropdown(t) {
      var n = t.placeholder || !1,
          i = (t.values, "");return i += '<i class="dropdown icon"></i>', t.placeholder ? i += '<div class="default text">' + n + "</div>" : i += '<div class="text"></div>', i += '<div class="menu">', e.each(t.values, function (e, t) {
        i += t.disabled ? '<div class="disabled item" data-value="' + t.value + '">' + t.name + "</div>" : '<div class="item" data-value="' + t.value + '">' + t.name + "</div>";
      }), i += "</div>";
    }, menu: function menu(t, n) {
      var i = t[n.values] || {},
          o = "";return e.each(i, function (e, t) {
        var i = t[n.text] ? 'data-text="' + t[n.text] + '"' : "",
            a = t[n.disabled] ? "disabled " : "";o += '<div class="' + a + 'item" data-value="' + t[n.value] + '"' + i + ">", o += t[n.name], o += "</div>";
      }), o;
    }, label: function label(e, t) {
      return t + '<i class="delete icon"></i>';
    }, message: function message(e) {
      return e;
    }, addition: function addition(e) {
      return e;
    } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.embed = function (n) {
    var o,
        a = e(this),
        r = a.selector || "",
        s = new Date().getTime(),
        l = [],
        c = arguments[0],
        u = "string" == typeof c,
        d = [].slice.call(arguments, 1);return a.each(function () {
      var f,
          m = e.isPlainObject(n) ? e.extend(!0, {}, e.fn.embed.settings, n) : e.extend({}, e.fn.embed.settings),
          g = m.selector,
          p = m.className,
          h = m.sources,
          v = m.error,
          b = m.metadata,
          y = m.namespace,
          x = m.templates,
          C = "." + y,
          w = "module-" + y,
          S = (e(t), e(this)),
          k = (S.find(g.placeholder), S.find(g.icon), S.find(g.embed)),
          T = this,
          A = S.data(w);f = { initialize: function initialize() {
          f.debug("Initializing embed"), f.determine.autoplay(), f.create(), f.bind.events(), f.instantiate();
        }, instantiate: function instantiate() {
          f.verbose("Storing instance of module", f), A = f, S.data(w, f);
        }, destroy: function destroy() {
          f.verbose("Destroying previous instance of embed"), f.reset(), S.removeData(w).off(C);
        }, refresh: function refresh() {
          f.verbose("Refreshing selector cache"), S.find(g.placeholder), S.find(g.icon), k = S.find(g.embed);
        }, bind: { events: function events() {
            f.has.placeholder() && (f.debug("Adding placeholder events"), S.on("click" + C, g.placeholder, f.createAndShow).on("click" + C, g.icon, f.createAndShow));
          } }, create: function create() {
          f.get.placeholder() ? f.createPlaceholder() : f.createAndShow();
        }, createPlaceholder: function createPlaceholder(e) {
          var t = f.get.icon(),
              n = f.get.url();f.generate.embed(n);e = e || f.get.placeholder(), S.html(x.placeholder(e, t)), f.debug("Creating placeholder for embed", e, t);
        }, createEmbed: function createEmbed(t) {
          f.refresh(), t = t || f.get.url(), k = e("<div/>").addClass(p.embed).html(f.generate.embed(t)).appendTo(S), m.onCreate.call(T, t), f.debug("Creating embed object", k);
        }, changeEmbed: function changeEmbed(e) {
          k.html(f.generate.embed(e));
        }, createAndShow: function createAndShow() {
          f.createEmbed(), f.show();
        }, change: function change(e, t, n) {
          f.debug("Changing video to ", e, t, n), S.data(b.source, e).data(b.id, t), n ? S.data(b.url, n) : S.removeData(b.url), f.has.embed() ? f.changeEmbed() : f.create();
        }, reset: function reset() {
          f.debug("Clearing embed and showing placeholder"), f.remove.active(), f.remove.embed(), f.showPlaceholder(), m.onReset.call(T);
        }, show: function show() {
          f.debug("Showing embed"), f.set.active(), m.onDisplay.call(T);
        }, hide: function hide() {
          f.debug("Hiding embed"), f.showPlaceholder();
        }, showPlaceholder: function showPlaceholder() {
          f.debug("Showing placeholder image"), f.remove.active(), m.onPlaceholderDisplay.call(T);
        }, get: { id: function id() {
            return m.id || S.data(b.id);
          }, placeholder: function placeholder() {
            return m.placeholder || S.data(b.placeholder);
          }, icon: function icon() {
            return m.icon ? m.icon : S.data(b.icon) !== i ? S.data(b.icon) : f.determine.icon();
          }, source: function source(e) {
            return m.source ? m.source : S.data(b.source) !== i ? S.data(b.source) : f.determine.source();
          }, type: function type() {
            var e = f.get.source();return h[e] !== i && h[e].type;
          }, url: function url() {
            return m.url ? m.url : S.data(b.url) !== i ? S.data(b.url) : f.determine.url();
          } }, determine: { autoplay: function autoplay() {
            f.should.autoplay() && (m.autoplay = !0);
          }, source: function source(t) {
            var n = !1;return (t = t || f.get.url()) && e.each(h, function (e, i) {
              if (-1 !== t.search(i.domain)) return n = e, !1;
            }), n;
          }, icon: function icon() {
            var e = f.get.source();return h[e] !== i && h[e].icon;
          }, url: function url() {
            var e,
                t = m.id || S.data(b.id),
                n = m.source || S.data(b.source);return (e = h[n] !== i && h[n].url.replace("{id}", t)) && S.data(b.url, e), e;
          } }, set: { active: function active() {
            S.addClass(p.active);
          } }, remove: { active: function active() {
            S.removeClass(p.active);
          }, embed: function embed() {
            k.empty();
          } }, encode: { parameters: function parameters(e) {
            var t,
                n = [];for (t in e) {
              n.push(encodeURIComponent(t) + "=" + encodeURIComponent(e[t]));
            }return n.join("&amp;");
          } }, generate: { embed: function embed(e) {
            f.debug("Generating embed html");var t,
                n,
                i = f.get.source();return (e = f.get.url(e)) ? (n = f.generate.parameters(i), t = x.iframe(e, n)) : f.error(v.noURL, S), t;
          }, parameters: function parameters(t, n) {
            var o = h[t] && h[t].parameters !== i ? h[t].parameters(m) : {};return (n = n || m.parameters) && (o = e.extend({}, o, n)), o = m.onEmbed(o), f.encode.parameters(o);
          } }, has: { embed: function embed() {
            return k.length > 0;
          }, placeholder: function placeholder() {
            return m.placeholder || S.data(b.placeholder);
          } }, should: { autoplay: function autoplay() {
            return "auto" === m.autoplay ? m.placeholder || S.data(b.placeholder) !== i : m.autoplay;
          } }, is: { video: function video() {
            return "video" == f.get.type();
          } }, setting: function setting(t, n) {
          if (f.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, m, t);else {
            if (n === i) return m[t];e.isPlainObject(m[t]) ? e.extend(!0, m[t], n) : m[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, f, t);else {
            if (n === i) return f[t];f[t] = n;
          }
        }, debug: function debug() {
          !m.silent && m.debug && (m.performance ? f.performance.log(arguments) : (f.debug = Function.prototype.bind.call(console.info, console, m.name + ":"), f.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !m.silent && m.verbose && m.debug && (m.performance ? f.performance.log(arguments) : (f.verbose = Function.prototype.bind.call(console.info, console, m.name + ":"), f.verbose.apply(console, arguments)));
        }, error: function error() {
          m.silent || (f.error = Function.prototype.bind.call(console.error, console, m.name + ":"), f.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;m.performance && (n = (t = new Date().getTime()) - (s || t), s = t, l.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: T, "Execution Time": n })), clearTimeout(f.performance.timer), f.performance.timer = setTimeout(f.performance.display, 500);
          }, display: function display() {
            var t = m.name + ":",
                n = 0;s = !1, clearTimeout(f.performance.timer), e.each(l, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", r && (t += " '" + r + "'"), a.length > 1 && (t += " (" + a.length + ")"), (console.group !== i || console.table !== i) && l.length > 0 && (console.groupCollapsed(t), console.table ? console.table(l) : e.each(l, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), l = [];
          } }, invoke: function invoke(t, n, a) {
          var r,
              s,
              l,
              c = A;return n = n || d, a = T || a, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i ? (s = c[o], !1) : (f.error(v.method, t), !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(a, n) : s !== i && (l = s), e.isArray(o) ? o.push(l) : o !== i ? o = [o, l] : l !== i && (o = l), s;
        } }, u ? (A === i && f.initialize(), f.invoke(c)) : (A !== i && A.invoke("destroy"), f.initialize());
    }), o !== i ? o : this;
  }, e.fn.embed.settings = { name: "Embed", namespace: "embed", silent: !1, debug: !1, verbose: !1, performance: !0, icon: !1, source: !1, url: !1, id: !1, autoplay: "auto", color: "#444444", hd: !0, brandedUI: !1, parameters: !1, onDisplay: function onDisplay() {}, onPlaceholderDisplay: function onPlaceholderDisplay() {}, onReset: function onReset() {}, onCreate: function onCreate(e) {}, onEmbed: function onEmbed(e) {
      return e;
    }, metadata: { id: "id", icon: "icon", placeholder: "placeholder", source: "source", url: "url" }, error: { noURL: "No URL specified", method: "The method you called is not defined" }, className: { active: "active", embed: "embed" }, selector: { embed: ".embed", placeholder: ".placeholder", icon: ".icon" }, sources: { youtube: { name: "youtube", type: "video", icon: "video play", domain: "youtube.com", url: "//www.youtube.com/embed/{id}", parameters: function parameters(e) {
          return { autohide: !e.brandedUI, autoplay: e.autoplay, color: e.color || i, hq: e.hd, jsapi: e.api, modestbranding: !e.brandedUI };
        } }, vimeo: { name: "vimeo", type: "video", icon: "video play", domain: "vimeo.com", url: "//player.vimeo.com/video/{id}", parameters: function parameters(e) {
          return { api: e.api, autoplay: e.autoplay, byline: e.brandedUI, color: e.color || i, portrait: e.brandedUI, title: e.brandedUI };
        } } }, templates: { iframe: function iframe(e, t) {
        var n = e;return t && (n += "?" + t), '<iframe src="' + n + '" width="100%" height="100%" frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
      }, placeholder: function placeholder(e, t) {
        var n = "";return t && (n += '<i class="' + t + ' icon"></i>'), e && (n += '<img class="placeholder" src="' + e + '">'), n;
      } }, api: !1, onPause: function onPause() {}, onPlay: function onPlay() {}, onStop: function onStop() {} };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.modal = function (o) {
    var a,
        r = e(this),
        s = e(t),
        l = e(n),
        c = e("body"),
        u = r.selector || "",
        d = new Date().getTime(),
        f = [],
        m = arguments[0],
        g = "string" == typeof m,
        p = [].slice.call(arguments, 1),
        h = t.requestAnimationFrame || t.mozRequestAnimationFrame || t.webkitRequestAnimationFrame || t.msRequestAnimationFrame || function (e) {
      setTimeout(e, 0);
    };return r.each(function () {
      var r,
          v,
          b,
          y,
          x,
          C,
          w,
          S,
          k,
          T = e.isPlainObject(o) ? e.extend(!0, {}, e.fn.modal.settings, o) : e.extend({}, e.fn.modal.settings),
          A = T.selector,
          R = T.className,
          P = T.namespace,
          E = T.error,
          F = "." + P,
          O = "module-" + P,
          D = e(this),
          q = e(T.context),
          j = D.find(A.close),
          z = this,
          I = D.data(O),
          M = !1;k = { initialize: function initialize() {
          k.verbose("Initializing dimmer", q), k.create.id(), k.create.dimmer(), k.refreshModals(), k.bind.events(), T.observeChanges && k.observeChanges(), k.instantiate();
        }, instantiate: function instantiate() {
          k.verbose("Storing instance of modal"), I = k, D.data(O, I);
        }, create: { dimmer: function dimmer() {
            var t = { debug: T.debug, variation: !T.centered && "top aligned", dimmerName: "modals" },
                n = e.extend(!0, t, T.dimmerSettings);e.fn.dimmer !== i ? (k.debug("Creating dimmer"), y = q.dimmer(n), T.detachable ? (k.verbose("Modal is detachable, moving content into dimmer"), y.dimmer("add content", D)) : k.set.undetached(), x = y.dimmer("get dimmer")) : k.error(E.dimmer);
          }, id: function id() {
            w = (Math.random().toString(16) + "000000000").substr(2, 8), C = "." + w, k.verbose("Creating unique id for element", w);
          } }, destroy: function destroy() {
          k.verbose("Destroying previous modal"), D.removeData(O).off(F), s.off(C), x.off(C), j.off(F), q.dimmer("destroy");
        }, observeChanges: function observeChanges() {
          "MutationObserver" in t && ((S = new MutationObserver(function (e) {
            k.debug("DOM tree modified, refreshing"), k.refresh();
          })).observe(z, { childList: !0, subtree: !0 }), k.debug("Setting up mutation observer", S));
        }, refresh: function refresh() {
          k.remove.scrolling(), k.cacheSizes(), k.set.screenHeight(), k.set.type();
        }, refreshModals: function refreshModals() {
          v = D.siblings(A.modal), r = v.add(D);
        }, attachEvents: function attachEvents(t, n) {
          var i = e(t);n = e.isFunction(k[n]) ? k[n] : k.toggle, i.length > 0 ? (k.debug("Attaching modal events to element", t, n), i.off(F).on("click" + F, n)) : k.error(E.notFound, t);
        }, bind: { events: function events() {
            k.verbose("Attaching events"), D.on("click" + F, A.close, k.event.close).on("click" + F, A.approve, k.event.approve).on("click" + F, A.deny, k.event.deny), s.on("resize" + C, k.event.resize);
          } }, get: { id: function id() {
            return (Math.random().toString(16) + "000000000").substr(2, 8);
          } }, event: { approve: function approve() {
            M || !1 === T.onApprove.call(z, e(this)) ? k.verbose("Approve callback returned false cancelling hide") : (M = !0, k.hide(function () {
              M = !1;
            }));
          }, deny: function deny() {
            M || !1 === T.onDeny.call(z, e(this)) ? k.verbose("Deny callback returned false cancelling hide") : (M = !0, k.hide(function () {
              M = !1;
            }));
          }, close: function close() {
            k.hide();
          }, click: function click(t) {
            if (T.closable) {
              var i = e(t.target).closest(A.modal).length > 0,
                  o = e.contains(n.documentElement, t.target);!i && o && k.is.active() && (k.debug("Dimmer clicked, hiding all modals"), k.remove.clickaway(), T.allowMultiple ? k.hide() : k.hideAll());
            } else k.verbose("Dimmer clicked but closable setting is disabled");
          }, debounce: function debounce(e, t) {
            clearTimeout(k.timer), k.timer = setTimeout(e, t);
          }, keyboard: function keyboard(e) {
            27 == e.which && (T.closable ? (k.debug("Escape key pressed hiding modal"), k.hide()) : k.debug("Escape key pressed, but closable is set to false"), e.preventDefault());
          }, resize: function resize() {
            y.dimmer("is active") && (k.is.animating() || k.is.active()) && h(k.refresh);
          } }, toggle: function toggle() {
          k.is.active() || k.is.animating() ? k.hide() : k.show();
        }, show: function show(t) {
          t = e.isFunction(t) ? t : function () {}, k.refreshModals(), k.set.dimmerSettings(), k.showModal(t);
        }, hide: function hide(t) {
          t = e.isFunction(t) ? t : function () {}, k.refreshModals(), k.hideModal(t);
        }, showModal: function showModal(t) {
          t = e.isFunction(t) ? t : function () {}, k.is.animating() || !k.is.active() ? (k.showDimmer(), k.cacheSizes(), k.set.screenHeight(), k.set.type(), k.set.clickaway(), !T.allowMultiple && k.others.active() ? k.hideOthers(k.showModal) : (T.allowMultiple && T.detachable && D.detach().appendTo(x), T.onShow.call(z), T.transition && e.fn.transition !== i && D.transition("is supported") ? (k.debug("Showing modal with css animations"), D.transition({ debug: T.debug, animation: T.transition + " in", queue: T.queue, duration: T.duration, useFailSafe: !0, onComplete: function onComplete() {
              T.onVisible.apply(z), T.keyboardShortcuts && k.add.keyboardShortcuts(), k.save.focus(), k.set.active(), T.autofocus && k.set.autofocus(), t();
            } })) : k.error(E.noTransition))) : k.debug("Modal is already visible");
        }, hideModal: function hideModal(t, n) {
          t = e.isFunction(t) ? t : function () {}, k.debug("Hiding modal"), !1 !== T.onHide.call(z, e(this)) ? (k.is.animating() || k.is.active()) && (T.transition && e.fn.transition !== i && D.transition("is supported") ? (k.remove.active(), D.transition({ debug: T.debug, animation: T.transition + " out", queue: T.queue, duration: T.duration, useFailSafe: !0, onStart: function onStart() {
              k.others.active() || n || k.hideDimmer(), T.keyboardShortcuts && k.remove.keyboardShortcuts();
            }, onComplete: function onComplete() {
              T.onHidden.call(z), k.restore.focus(), t();
            } })) : k.error(E.noTransition)) : k.verbose("Hide callback returned false cancelling hide");
        }, showDimmer: function showDimmer() {
          y.dimmer("is animating") || !y.dimmer("is active") ? (k.debug("Showing dimmer"), y.dimmer("show")) : k.debug("Dimmer already visible");
        }, hideDimmer: function hideDimmer() {
          y.dimmer("is animating") || y.dimmer("is active") ? y.dimmer("hide", function () {
            k.remove.clickaway(), k.remove.screenHeight();
          }) : k.debug("Dimmer is not visible cannot hide");
        }, hideAll: function hideAll(t) {
          var n = r.filter("." + R.active + ", ." + R.animating);t = e.isFunction(t) ? t : function () {}, n.length > 0 && (k.debug("Hiding all visible modals"), k.hideDimmer(), n.modal("hide modal", t));
        }, hideOthers: function hideOthers(t) {
          var n = v.filter("." + R.active + ", ." + R.animating);t = e.isFunction(t) ? t : function () {}, n.length > 0 && (k.debug("Hiding other modals", v), n.modal("hide modal", t, !0));
        }, others: { active: function active() {
            return v.filter("." + R.active).length > 0;
          }, animating: function animating() {
            return v.filter("." + R.animating).length > 0;
          } }, add: { keyboardShortcuts: function keyboardShortcuts() {
            k.verbose("Adding keyboard shortcuts"), l.on("keyup" + F, k.event.keyboard);
          } }, save: { focus: function focus() {
            e(n.activeElement).closest(D).length > 0 || (b = e(n.activeElement).blur());
          } }, restore: { focus: function focus() {
            b && b.length > 0 && b.focus();
          } }, remove: { active: function active() {
            D.removeClass(R.active);
          }, clickaway: function clickaway() {
            x.off("click" + C);
          }, bodyStyle: function bodyStyle() {
            "" === c.attr("style") && (k.verbose("Removing style attribute"), c.removeAttr("style"));
          }, screenHeight: function screenHeight() {
            k.debug("Removing page height"), c.css("height", "");
          }, keyboardShortcuts: function keyboardShortcuts() {
            k.verbose("Removing keyboard shortcuts"), l.off("keyup" + F);
          }, scrolling: function scrolling() {
            y.removeClass(R.scrolling), D.removeClass(R.scrolling);
          } }, cacheSizes: function cacheSizes() {
          D.addClass(R.loading);var o = D.prop("scrollHeight"),
              a = D.outerHeight();k.cache !== i && 0 === a || (k.cache = { pageHeight: e(n).outerHeight(), height: a + T.offset, scrollHeight: o + T.offset, contextHeight: "body" == T.context ? e(t).height() : y.height() }, k.cache.topOffset = -k.cache.height / 2), D.removeClass(R.loading), k.debug("Caching modal and container sizes", k.cache);
        }, can: { fit: function fit() {
            var e = k.cache.contextHeight,
                t = k.cache.contextHeight / 2,
                n = k.cache.topOffset,
                i = k.cache.scrollHeight,
                o = k.cache.height,
                a = T.padding;return i > o ? t + n + i + a < e : o + 2 * a < e;
          } }, is: { active: function active() {
            return D.hasClass(R.active);
          }, animating: function animating() {
            return D.transition("is supported") ? D.transition("is animating") : D.is(":visible");
          }, scrolling: function scrolling() {
            return y.hasClass(R.scrolling);
          }, modernBrowser: function modernBrowser() {
            return !(t.ActiveXObject || "ActiveXObject" in t);
          } }, set: { autofocus: function autofocus() {
            var e = D.find("[tabindex], :input").filter(":visible"),
                t = e.filter("[autofocus]"),
                n = t.length > 0 ? t.first() : e.first();n.length > 0 && n.focus();
          }, clickaway: function clickaway() {
            x.on("click" + C, k.event.click);
          }, dimmerSettings: function dimmerSettings() {
            if (e.fn.dimmer !== i) {
              var t = { debug: T.debug, dimmerName: "modals", closable: "auto", variation: !T.centered && "top aligned", duration: { show: T.duration, hide: T.duration } },
                  n = e.extend(!0, t, T.dimmerSettings);T.inverted ? (n.variation = n.variation !== i ? n.variation + " inverted" : "inverted", x.addClass(R.inverted)) : x.removeClass(R.inverted), T.blurring ? y.addClass(R.blurring) : y.removeClass(R.blurring), q.dimmer("setting", n);
            } else k.error(E.dimmer);
          }, screenHeight: function screenHeight() {
            k.can.fit() ? c.css("height", "") : (k.debug("Modal is taller than page content, resizing page height"), c.css("height", k.cache.height + 2 * T.padding));
          }, active: function active() {
            D.addClass(R.active);
          }, scrolling: function scrolling() {
            y.addClass(R.scrolling), D.addClass(R.scrolling);
          }, type: function type() {
            k.can.fit() ? (k.verbose("Modal fits on screen"), k.others.active() || k.others.animating() || k.remove.scrolling()) : (k.verbose("Modal cannot fit on screen setting to scrolling"), k.set.scrolling());
          }, undetached: function undetached() {
            y.addClass(R.undetached);
          } }, setting: function setting(t, n) {
          if (k.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, T, t);else {
            if (n === i) return T[t];e.isPlainObject(T[t]) ? e.extend(!0, T[t], n) : T[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, k, t);else {
            if (n === i) return k[t];k[t] = n;
          }
        }, debug: function debug() {
          !T.silent && T.debug && (T.performance ? k.performance.log(arguments) : (k.debug = Function.prototype.bind.call(console.info, console, T.name + ":"), k.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !T.silent && T.verbose && T.debug && (T.performance ? k.performance.log(arguments) : (k.verbose = Function.prototype.bind.call(console.info, console, T.name + ":"), k.verbose.apply(console, arguments)));
        }, error: function error() {
          T.silent || (k.error = Function.prototype.bind.call(console.error, console, T.name + ":"), k.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;T.performance && (n = (t = new Date().getTime()) - (d || t), d = t, f.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: z, "Execution Time": n })), clearTimeout(k.performance.timer), k.performance.timer = setTimeout(k.performance.display, 500);
          }, display: function display() {
            var t = T.name + ":",
                n = 0;d = !1, clearTimeout(k.performance.timer), e.each(f, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", u && (t += " '" + u + "'"), (console.group !== i || console.table !== i) && f.length > 0 && (console.groupCollapsed(t), console.table ? console.table(f) : e.each(f, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), f = [];
          } }, invoke: function invoke(t, n, o) {
          var r,
              s,
              l,
              c = I;return n = n || p, o = z || o, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i && (s = c[o], !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(o, n) : s !== i && (l = s), e.isArray(a) ? a.push(l) : a !== i ? a = [a, l] : l !== i && (a = l), s;
        } }, g ? (I === i && k.initialize(), k.invoke(m)) : (I !== i && I.invoke("destroy"), k.initialize());
    }), a !== i ? a : this;
  }, e.fn.modal.settings = { name: "Modal", namespace: "modal", silent: !1, debug: !1, verbose: !1, performance: !0, observeChanges: !1, allowMultiple: !1, detachable: !0, closable: !0, autofocus: !0, inverted: !1, blurring: !1, centered: !0, dimmerSettings: { closable: !1, useCSS: !0 }, keyboardShortcuts: !0, context: "body", queue: !1, duration: 500, offset: 0, transition: "scale", padding: 50, onShow: function onShow() {}, onVisible: function onVisible() {}, onHide: function onHide() {
      return !0;
    }, onHidden: function onHidden() {}, onApprove: function onApprove() {
      return !0;
    }, onDeny: function onDeny() {
      return !0;
    }, selector: { close: "> .close", approve: ".actions .positive, .actions .approve, .actions .ok", deny: ".actions .negative, .actions .deny, .actions .cancel", modal: ".ui.modal" }, error: { dimmer: "UI Dimmer, a required component is not included in this page", method: "The method you called is not defined.", notFound: "The element you specified could not be found" }, className: { active: "active", animating: "animating", blurring: "blurring", inverted: "inverted", loading: "loading", scrolling: "scrolling", undetached: "undetached" } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.nag = function (n) {
    var o,
        a = e(this),
        r = a.selector || "",
        s = new Date().getTime(),
        l = [],
        c = arguments[0],
        u = "string" == typeof c,
        d = [].slice.call(arguments, 1);return a.each(function () {
      var a,
          f = e.isPlainObject(n) ? e.extend(!0, {}, e.fn.nag.settings, n) : e.extend({}, e.fn.nag.settings),
          m = (f.className, f.selector),
          g = f.error,
          p = f.namespace,
          h = "." + p,
          v = p + "-module",
          b = e(this),
          y = (b.find(m.close), f.context ? e(f.context) : e("body")),
          x = this,
          C = b.data(v);t.requestAnimationFrame || t.mozRequestAnimationFrame || t.webkitRequestAnimationFrame || t.msRequestAnimationFrame;a = { initialize: function initialize() {
          a.verbose("Initializing element"), b.on("click" + h, m.close, a.dismiss).data(v, a), f.detachable && b.parent()[0] !== y[0] && b.detach().prependTo(y), f.displayTime > 0 && setTimeout(a.hide, f.displayTime), a.show();
        }, destroy: function destroy() {
          a.verbose("Destroying instance"), b.removeData(v).off(h);
        }, show: function show() {
          a.should.show() && !b.is(":visible") && (a.debug("Showing nag", f.animation.show), "fade" == f.animation.show ? b.fadeIn(f.duration, f.easing) : b.slideDown(f.duration, f.easing));
        }, hide: function hide() {
          a.debug("Showing nag", f.animation.hide), "fade" == f.animation.show ? b.fadeIn(f.duration, f.easing) : b.slideUp(f.duration, f.easing);
        }, onHide: function onHide() {
          a.debug("Removing nag", f.animation.hide), b.remove(), f.onHide && f.onHide();
        }, dismiss: function dismiss(e) {
          f.storageMethod && a.storage.set(f.key, f.value), a.hide(), e.stopImmediatePropagation(), e.preventDefault();
        }, should: { show: function show() {
            return f.persist ? (a.debug("Persistent nag is set, can show nag"), !0) : a.storage.get(f.key) != f.value.toString() ? (a.debug("Stored value is not set, can show nag", a.storage.get(f.key)), !0) : (a.debug("Stored value is set, cannot show nag", a.storage.get(f.key)), !1);
          } }, get: { storageOptions: function storageOptions() {
            var e = {};return f.expires && (e.expires = f.expires), f.domain && (e.domain = f.domain), f.path && (e.path = f.path), e;
          } }, clear: function clear() {
          a.storage.remove(f.key);
        }, storage: { set: function set(n, o) {
            var r = a.get.storageOptions();if ("localstorage" == f.storageMethod && t.localStorage !== i) t.localStorage.setItem(n, o), a.debug("Value stored using local storage", n, o);else if ("sessionstorage" == f.storageMethod && t.sessionStorage !== i) t.sessionStorage.setItem(n, o), a.debug("Value stored using session storage", n, o);else {
              if (e.cookie === i) return void a.error(g.noCookieStorage);e.cookie(n, o, r), a.debug("Value stored using cookie", n, o, r);
            }
          }, get: function get(n, o) {
            var r;return "localstorage" == f.storageMethod && t.localStorage !== i ? r = t.localStorage.getItem(n) : "sessionstorage" == f.storageMethod && t.sessionStorage !== i ? r = t.sessionStorage.getItem(n) : e.cookie !== i ? r = e.cookie(n) : a.error(g.noCookieStorage), "undefined" != r && "null" != r && r !== i && null !== r || (r = i), r;
          }, remove: function remove(n) {
            var o = a.get.storageOptions();"localstorage" == f.storageMethod && t.localStorage !== i ? t.localStorage.removeItem(n) : "sessionstorage" == f.storageMethod && t.sessionStorage !== i ? t.sessionStorage.removeItem(n) : e.cookie !== i ? e.removeCookie(n, o) : a.error(g.noStorage);
          } }, setting: function setting(t, n) {
          if (a.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, f, t);else {
            if (n === i) return f[t];e.isPlainObject(f[t]) ? e.extend(!0, f[t], n) : f[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, a, t);else {
            if (n === i) return a[t];a[t] = n;
          }
        }, debug: function debug() {
          !f.silent && f.debug && (f.performance ? a.performance.log(arguments) : (a.debug = Function.prototype.bind.call(console.info, console, f.name + ":"), a.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !f.silent && f.verbose && f.debug && (f.performance ? a.performance.log(arguments) : (a.verbose = Function.prototype.bind.call(console.info, console, f.name + ":"), a.verbose.apply(console, arguments)));
        }, error: function error() {
          f.silent || (a.error = Function.prototype.bind.call(console.error, console, f.name + ":"), a.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;f.performance && (n = (t = new Date().getTime()) - (s || t), s = t, l.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: x, "Execution Time": n })), clearTimeout(a.performance.timer), a.performance.timer = setTimeout(a.performance.display, 500);
          }, display: function display() {
            var t = f.name + ":",
                n = 0;s = !1, clearTimeout(a.performance.timer), e.each(l, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", r && (t += " '" + r + "'"), (console.group !== i || console.table !== i) && l.length > 0 && (console.groupCollapsed(t), console.table ? console.table(l) : e.each(l, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), l = [];
          } }, invoke: function invoke(t, n, r) {
          var s,
              l,
              c,
              u = C;return n = n || d, r = x || r, "string" == typeof t && u !== i && (t = t.split(/[\. ]/), s = t.length - 1, e.each(t, function (n, o) {
            var r = n != s ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(u[r]) && n != s) u = u[r];else {
              if (u[r] !== i) return l = u[r], !1;if (!e.isPlainObject(u[o]) || n == s) return u[o] !== i ? (l = u[o], !1) : (a.error(g.method, t), !1);u = u[o];
            }
          })), e.isFunction(l) ? c = l.apply(r, n) : l !== i && (c = l), e.isArray(o) ? o.push(c) : o !== i ? o = [o, c] : c !== i && (o = c), l;
        } }, u ? (C === i && a.initialize(), a.invoke(c)) : (C !== i && C.invoke("destroy"), a.initialize());
    }), o !== i ? o : this;
  }, e.fn.nag.settings = { name: "Nag", silent: !1, debug: !1, verbose: !1, performance: !0, namespace: "Nag", persist: !1, displayTime: 0, animation: { show: "slide", hide: "slide" }, context: !1, detachable: !1, expires: 30, domain: !1, path: "/", storageMethod: "cookie", key: "nag", value: "dismiss", error: { noCookieStorage: "$.cookie is not included. A storage solution is required.", noStorage: "Neither $.cookie or store is defined. A storage solution is required for storing state", method: "The method you called is not defined." }, className: { bottom: "bottom", fixed: "fixed" }, selector: { close: ".close.icon" }, speed: 500, easing: "easeOutQuad", onHide: function onHide() {} }, e.extend(e.easing, { easeOutQuad: function easeOutQuad(e, t, n, i, o) {
      return -i * (t /= o) * (t - 2) + n;
    } });
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.popup = function (o) {
    var a,
        r = e(this),
        s = e(n),
        l = e(t),
        c = e("body"),
        u = r.selector || "",
        d = new Date().getTime(),
        f = [],
        m = arguments[0],
        g = "string" == typeof m,
        p = [].slice.call(arguments, 1);return r.each(function () {
      var r,
          h,
          v,
          b,
          y,
          x,
          C = e.isPlainObject(o) ? e.extend(!0, {}, e.fn.popup.settings, o) : e.extend({}, e.fn.popup.settings),
          w = C.selector,
          S = C.className,
          k = C.error,
          T = C.metadata,
          A = C.namespace,
          R = "." + C.namespace,
          P = "module-" + A,
          E = e(this),
          F = e(C.context),
          O = e(C.scrollContext),
          D = e(C.boundary),
          q = C.target ? e(C.target) : E,
          j = 0,
          z = !1,
          I = !1,
          M = this,
          L = E.data(P);x = { initialize: function initialize() {
          x.debug("Initializing", E), x.createID(), x.bind.events(), !x.exists() && C.preserve && x.create(), C.observeChanges && x.observeChanges(), x.instantiate();
        }, instantiate: function instantiate() {
          x.verbose("Storing instance", x), L = x, E.data(P, L);
        }, observeChanges: function observeChanges() {
          "MutationObserver" in t && ((v = new MutationObserver(x.event.documentChanged)).observe(n, { childList: !0, subtree: !0 }), x.debug("Setting up mutation observer", v));
        }, refresh: function refresh() {
          C.popup ? r = e(C.popup).eq(0) : C.inline && (r = q.nextAll(w.popup).eq(0), C.popup = r), C.popup ? (r.addClass(S.loading), h = x.get.offsetParent(), r.removeClass(S.loading), C.movePopup && x.has.popup() && x.get.offsetParent(r)[0] !== h[0] && (x.debug("Moving popup to the same offset parent as target"), r.detach().appendTo(h))) : h = C.inline ? x.get.offsetParent(q) : x.has.popup() ? x.get.offsetParent(r) : c, h.is("html") && h[0] !== c[0] && (x.debug("Setting page as offset parent"), h = c), x.get.variation() && x.set.variation();
        }, reposition: function reposition() {
          x.refresh(), x.set.position();
        }, destroy: function destroy() {
          x.debug("Destroying previous module"), v && v.disconnect(), r && !C.preserve && x.removePopup(), clearTimeout(x.hideTimer), clearTimeout(x.showTimer), x.unbind.close(), x.unbind.events(), E.removeData(P);
        }, event: { start: function start(t) {
            var n = e.isPlainObject(C.delay) ? C.delay.show : C.delay;clearTimeout(x.hideTimer), I || (x.showTimer = setTimeout(x.show, n));
          }, end: function end() {
            var t = e.isPlainObject(C.delay) ? C.delay.hide : C.delay;clearTimeout(x.showTimer), x.hideTimer = setTimeout(x.hide, t);
          }, touchstart: function touchstart(e) {
            I = !0, x.show();
          }, resize: function resize() {
            x.is.visible() && x.set.position();
          }, documentChanged: function documentChanged(t) {
            [].forEach.call(t, function (t) {
              t.removedNodes && [].forEach.call(t.removedNodes, function (t) {
                (t == M || e(t).find(M).length > 0) && (x.debug("Element removed from DOM, tearing down events"), x.destroy());
              });
            });
          }, hideGracefully: function hideGracefully(t) {
            var i = e(t.target),
                o = e.contains(n.documentElement, t.target),
                a = i.closest(w.popup).length > 0;t && !a && o ? (x.debug("Click occurred outside popup hiding popup"), x.hide()) : x.debug("Click was inside popup, keeping popup open");
          } }, create: function create() {
          var t = x.get.html(),
              n = x.get.title(),
              i = x.get.content();t || i || n ? (x.debug("Creating pop-up html"), t || (t = C.templates.popup({ title: n, content: i })), r = e("<div/>").addClass(S.popup).data(T.activator, E).html(t), C.inline ? (x.verbose("Inserting popup element inline", r), r.insertAfter(E)) : (x.verbose("Appending popup element to body", r), r.appendTo(F)), x.refresh(), x.set.variation(), C.hoverable && x.bind.popup(), C.onCreate.call(r, M)) : 0 !== q.next(w.popup).length ? (x.verbose("Pre-existing popup found"), C.inline = !0, C.popup = q.next(w.popup).data(T.activator, E), x.refresh(), C.hoverable && x.bind.popup()) : C.popup ? (e(C.popup).data(T.activator, E), x.verbose("Used popup specified in settings"), x.refresh(), C.hoverable && x.bind.popup()) : x.debug("No content specified skipping display", M);
        }, createID: function createID() {
          y = (Math.random().toString(16) + "000000000").substr(2, 8), b = "." + y, x.verbose("Creating unique id for element", y);
        }, toggle: function toggle() {
          x.debug("Toggling pop-up"), x.is.hidden() ? (x.debug("Popup is hidden, showing pop-up"), x.unbind.close(), x.show()) : (x.debug("Popup is visible, hiding pop-up"), x.hide());
        }, show: function show(e) {
          if (e = e || function () {}, x.debug("Showing pop-up", C.transition), x.is.hidden() && (!x.is.active() || !x.is.dropdown())) {
            if (x.exists() || x.create(), !1 === C.onShow.call(r, M)) return void x.debug("onShow callback returned false, cancelling popup animation");C.preserve || C.popup || x.refresh(), r && x.set.position() && (x.save.conditions(), C.exclusive && x.hideAll(), x.animate.show(e));
          }
        }, hide: function hide(e) {
          if (e = e || function () {}, x.is.visible() || x.is.animating()) {
            if (!1 === C.onHide.call(r, M)) return void x.debug("onHide callback returned false, cancelling popup animation");x.remove.visible(), x.unbind.close(), x.restore.conditions(), x.animate.hide(e);
          }
        }, hideAll: function hideAll() {
          e(w.popup).filter("." + S.popupVisible).each(function () {
            e(this).data(T.activator).popup("hide");
          });
        }, exists: function exists() {
          return !!r && (C.inline || C.popup ? x.has.popup() : r.closest(F).length >= 1);
        }, removePopup: function removePopup() {
          x.has.popup() && !C.popup && (x.debug("Removing popup", r), r.remove(), r = i, C.onRemove.call(r, M));
        }, save: { conditions: function conditions() {
            x.cache = { title: E.attr("title") }, x.cache.title && E.removeAttr("title"), x.verbose("Saving original attributes", x.cache.title);
          } }, restore: { conditions: function conditions() {
            return x.cache && x.cache.title && (E.attr("title", x.cache.title), x.verbose("Restoring original attributes", x.cache.title)), !0;
          } }, supports: { svg: function svg() {
            return "undefined" == typeof SVGGraphicsElement;
          } }, animate: { show: function show(t) {
            t = e.isFunction(t) ? t : function () {}, C.transition && e.fn.transition !== i && E.transition("is supported") ? (x.set.visible(), r.transition({ animation: C.transition + " in", queue: !1, debug: C.debug, verbose: C.verbose, duration: C.duration, onComplete: function onComplete() {
                x.bind.close(), t.call(r, M), C.onVisible.call(r, M);
              } })) : x.error(k.noTransition);
          }, hide: function hide(t) {
            t = e.isFunction(t) ? t : function () {}, x.debug("Hiding pop-up"), !1 !== C.onHide.call(r, M) ? C.transition && e.fn.transition !== i && E.transition("is supported") ? r.transition({ animation: C.transition + " out", queue: !1, duration: C.duration, debug: C.debug, verbose: C.verbose, onComplete: function onComplete() {
                x.reset(), t.call(r, M), C.onHidden.call(r, M);
              } }) : x.error(k.noTransition) : x.debug("onHide callback returned false, cancelling popup animation");
          } }, change: { content: function content(e) {
            r.html(e);
          } }, get: { html: function html() {
            return E.removeData(T.html), E.data(T.html) || C.html;
          }, title: function title() {
            return E.removeData(T.title), E.data(T.title) || C.title;
          }, content: function content() {
            return E.removeData(T.content), E.data(T.content) || C.content || E.attr("title");
          }, variation: function variation() {
            return E.removeData(T.variation), E.data(T.variation) || C.variation;
          }, popup: function popup() {
            return r;
          }, popupOffset: function popupOffset() {
            return r.offset();
          }, calculations: function calculations() {
            var e,
                n = x.get.offsetParent(r),
                i = q[0],
                o = D[0] == t,
                a = C.inline || C.popup && C.movePopup ? q.position() : q.offset(),
                s = o ? { top: 0, left: 0 } : D.offset(),
                c = {},
                u = o ? { top: l.scrollTop(), left: l.scrollLeft() } : { top: 0, left: 0 };if (c = { target: { element: q[0], width: q.outerWidth(), height: q.outerHeight(), top: a.top, left: a.left, margin: {} }, popup: { width: r.outerWidth(), height: r.outerHeight() }, parent: { width: h.outerWidth(), height: h.outerHeight() }, screen: { top: s.top, left: s.left, scroll: { top: u.top, left: u.left }, width: D.width(), height: D.height() } }, n.get(0) !== h.get(0)) {
              var d = n.offset();c.target.top -= d.top, c.target.left -= d.left, c.parent.width = n.outerWidth(), c.parent.height = n.outerHeight();
            }return C.setFluidWidth && x.is.fluid() && (c.container = { width: r.parent().outerWidth() }, c.popup.width = c.container.width), c.target.margin.top = C.inline ? parseInt(t.getComputedStyle(i).getPropertyValue("margin-top"), 10) : 0, c.target.margin.left = C.inline ? x.is.rtl() ? parseInt(t.getComputedStyle(i).getPropertyValue("margin-right"), 10) : parseInt(t.getComputedStyle(i).getPropertyValue("margin-left"), 10) : 0, e = c.screen, c.boundary = { top: e.top + e.scroll.top, bottom: e.top + e.scroll.top + e.height, left: e.left + e.scroll.left, right: e.left + e.scroll.left + e.width }, c;
          }, id: function id() {
            return y;
          }, startEvent: function startEvent() {
            return "hover" == C.on ? "mouseenter" : "focus" == C.on && "focus";
          }, scrollEvent: function scrollEvent() {
            return "scroll";
          }, endEvent: function endEvent() {
            return "hover" == C.on ? "mouseleave" : "focus" == C.on && "blur";
          }, distanceFromBoundary: function distanceFromBoundary(e, t) {
            var n,
                i,
                o = {};return n = (t = t || x.get.calculations()).popup, i = t.boundary, e && (o = { top: e.top - i.top, left: e.left - i.left, right: i.right - (e.left + n.width), bottom: i.bottom - (e.top + n.height) }, x.verbose("Distance from boundaries determined", e, o)), o;
          }, offsetParent: function offsetParent(t) {
            var n = (t !== i ? t[0] : q[0]).parentNode,
                o = e(n);if (n) for (var a = "none" === o.css("transform"), r = "static" === o.css("position"), s = o.is("body"); n && !s && r && a;) {
              n = n.parentNode, a = "none" === (o = e(n)).css("transform"), r = "static" === o.css("position"), s = o.is("body");
            }return o && o.length > 0 ? o : e();
          }, positions: function positions() {
            return { "top left": !1, "top center": !1, "top right": !1, "bottom left": !1, "bottom center": !1, "bottom right": !1, "left center": !1, "right center": !1 };
          }, nextPosition: function nextPosition(e) {
            var t = e.split(" "),
                n = t[0],
                i = t[1],
                o = "top" == n || "bottom" == n,
                a = !1,
                r = !1,
                s = !1;return z || (x.verbose("All available positions available"), z = x.get.positions()), x.debug("Recording last position tried", e), z[e] = !0, "opposite" === C.prefer && (s = (s = [{ top: "bottom", bottom: "top", left: "right", right: "left" }[n], i]).join(" "), a = !0 === z[s], x.debug("Trying opposite strategy", s)), "adjacent" === C.prefer && o && (s = (s = [n, { left: "center", center: "right", right: "left" }[i]]).join(" "), r = !0 === z[s], x.debug("Trying adjacent strategy", s)), (r || a) && (x.debug("Using backup position", s), s = { "top left": "top center", "top center": "top right", "top right": "right center", "right center": "bottom right", "bottom right": "bottom center", "bottom center": "bottom left", "bottom left": "left center", "left center": "top left" }[e]), s;
          } }, set: { position: function position(e, t) {
            if (0 !== q.length && 0 !== r.length) {
              var n, o, a, s, l, c, u, d;if (t = t || x.get.calculations(), e = e || E.data(T.position) || C.position, n = E.data(T.offset) || C.offset, o = C.distanceAway, a = t.target, s = t.popup, l = t.parent, x.should.centerArrow(t) && (x.verbose("Adjusting offset to center arrow on small target element"), "top left" != e && "bottom left" != e || (n += a.width / 2, n -= C.arrowPixelsFromEdge), "top right" != e && "bottom right" != e || (n -= a.width / 2, n += C.arrowPixelsFromEdge)), 0 === a.width && 0 === a.height && !x.is.svg(a.element)) return x.debug("Popup target is hidden, no action taken"), !1;switch (C.inline && (x.debug("Adding margin to calculation", a.margin), "left center" == e || "right center" == e ? (n += a.margin.top, o += -a.margin.left) : "top left" == e || "top center" == e || "top right" == e ? (n += a.margin.left, o -= a.margin.top) : (n += a.margin.left, o += a.margin.top)), x.debug("Determining popup position from calculations", e, t), x.is.rtl() && (e = e.replace(/left|right/g, function (e) {
                return "left" == e ? "right" : "left";
              }), x.debug("RTL: Popup position updated", e)), j == C.maxSearchDepth && "string" == typeof C.lastResort && (e = C.lastResort), e) {case "top left":
                  c = { top: "auto", bottom: l.height - a.top + o, left: a.left + n, right: "auto" };break;case "top center":
                  c = { bottom: l.height - a.top + o, left: a.left + a.width / 2 - s.width / 2 + n, top: "auto", right: "auto" };break;case "top right":
                  c = { bottom: l.height - a.top + o, right: l.width - a.left - a.width - n, top: "auto", left: "auto" };break;case "left center":
                  c = { top: a.top + a.height / 2 - s.height / 2 + n, right: l.width - a.left + o, left: "auto", bottom: "auto" };break;case "right center":
                  c = { top: a.top + a.height / 2 - s.height / 2 + n, left: a.left + a.width + o, bottom: "auto", right: "auto" };break;case "bottom left":
                  c = { top: a.top + a.height + o, left: a.left + n, bottom: "auto", right: "auto" };break;case "bottom center":
                  c = { top: a.top + a.height + o, left: a.left + a.width / 2 - s.width / 2 + n, bottom: "auto", right: "auto" };break;case "bottom right":
                  c = { top: a.top + a.height + o, right: l.width - a.left - a.width - n, left: "auto", bottom: "auto" };}if (c === i && x.error(k.invalidPosition, e), x.debug("Calculated popup positioning values", c), r.css(c).removeClass(S.position).addClass(e).addClass(S.loading), u = x.get.popupOffset(), d = x.get.distanceFromBoundary(u, t), x.is.offstage(d, e)) {
                if (x.debug("Position is outside viewport", e), j < C.maxSearchDepth) return j++, e = x.get.nextPosition(e), x.debug("Trying new position", e), !!r && x.set.position(e, t);if (!C.lastResort) return x.debug("Popup could not find a position to display", r), x.error(k.cannotPlace, M), x.remove.attempts(), x.remove.loading(), x.reset(), C.onUnplaceable.call(r, M), !1;x.debug("No position found, showing with last position");
              }return x.debug("Position is on stage", e), x.remove.attempts(), x.remove.loading(), C.setFluidWidth && x.is.fluid() && x.set.fluidWidth(t), !0;
            }x.error(k.notFound);
          }, fluidWidth: function fluidWidth(e) {
            e = e || x.get.calculations(), x.debug("Automatically setting element width to parent width", e.parent.width), r.css("width", e.container.width);
          }, variation: function variation(e) {
            (e = e || x.get.variation()) && x.has.popup() && (x.verbose("Adding variation to popup", e), r.addClass(e));
          }, visible: function visible() {
            E.addClass(S.visible);
          } }, remove: { loading: function loading() {
            r.removeClass(S.loading);
          }, variation: function variation(e) {
            (e = e || x.get.variation()) && (x.verbose("Removing variation", e), r.removeClass(e));
          }, visible: function visible() {
            E.removeClass(S.visible);
          }, attempts: function attempts() {
            x.verbose("Resetting all searched positions"), j = 0, z = !1;
          } }, bind: { events: function events() {
            x.debug("Binding popup events to module"), "click" == C.on && E.on("click" + R, x.toggle), "hover" == C.on && E.on("touchstart" + R, x.event.touchstart), x.get.startEvent() && E.on(x.get.startEvent() + R, x.event.start).on(x.get.endEvent() + R, x.event.end), C.target && x.debug("Target set to element", q), l.on("resize" + b, x.event.resize);
          }, popup: function popup() {
            x.verbose("Allowing hover events on popup to prevent closing"), r && x.has.popup() && r.on("mouseenter" + R, x.event.start).on("mouseleave" + R, x.event.end);
          }, close: function close() {
            (!0 === C.hideOnScroll || "auto" == C.hideOnScroll && "click" != C.on) && x.bind.closeOnScroll(), "hover" == C.on && I && x.bind.touchClose(), "click" == C.on && C.closable && x.bind.clickaway();
          }, closeOnScroll: function closeOnScroll() {
            x.verbose("Binding scroll close event to document"), O.one(x.get.scrollEvent() + b, x.event.hideGracefully);
          }, touchClose: function touchClose() {
            x.verbose("Binding popup touchclose event to document"), s.on("touchstart" + b, function (e) {
              x.verbose("Touched away from popup"), x.event.hideGracefully.call(M, e);
            });
          }, clickaway: function clickaway() {
            x.verbose("Binding popup close event to document"), s.on("click" + b, function (e) {
              x.verbose("Clicked away from popup"), x.event.hideGracefully.call(M, e);
            });
          } }, unbind: { events: function events() {
            l.off(b), E.off(R);
          }, close: function close() {
            s.off(b), O.off(b);
          } }, has: { popup: function popup() {
            return r && r.length > 0;
          } }, should: { centerArrow: function centerArrow(e) {
            return !x.is.basic() && e.target.width <= 2 * C.arrowPixelsFromEdge;
          } }, is: { offstage: function offstage(t, n) {
            var i = [];return e.each(t, function (e, t) {
              t < -C.jitter && (x.debug("Position exceeds allowable distance from edge", e, t, n), i.push(e));
            }), i.length > 0;
          }, svg: function svg(e) {
            return x.supports.svg() && e instanceof SVGGraphicsElement;
          }, basic: function basic() {
            return E.hasClass(S.basic);
          }, active: function active() {
            return E.hasClass(S.active);
          }, animating: function animating() {
            return r !== i && r.hasClass(S.animating);
          }, fluid: function fluid() {
            return r !== i && r.hasClass(S.fluid);
          }, visible: function visible() {
            return r !== i && r.hasClass(S.popupVisible);
          }, dropdown: function dropdown() {
            return E.hasClass(S.dropdown);
          }, hidden: function hidden() {
            return !x.is.visible();
          }, rtl: function rtl() {
            return "rtl" == E.css("direction");
          } }, reset: function reset() {
          x.remove.visible(), C.preserve ? e.fn.transition !== i && r.transition("remove transition") : x.removePopup();
        }, setting: function setting(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, C, t);else {
            if (n === i) return C[t];C[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, x, t);else {
            if (n === i) return x[t];x[t] = n;
          }
        }, debug: function debug() {
          !C.silent && C.debug && (C.performance ? x.performance.log(arguments) : (x.debug = Function.prototype.bind.call(console.info, console, C.name + ":"), x.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !C.silent && C.verbose && C.debug && (C.performance ? x.performance.log(arguments) : (x.verbose = Function.prototype.bind.call(console.info, console, C.name + ":"), x.verbose.apply(console, arguments)));
        }, error: function error() {
          C.silent || (x.error = Function.prototype.bind.call(console.error, console, C.name + ":"), x.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;C.performance && (n = (t = new Date().getTime()) - (d || t), d = t, f.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: M, "Execution Time": n })), clearTimeout(x.performance.timer), x.performance.timer = setTimeout(x.performance.display, 500);
          }, display: function display() {
            var t = C.name + ":",
                n = 0;d = !1, clearTimeout(x.performance.timer), e.each(f, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", u && (t += " '" + u + "'"), (console.group !== i || console.table !== i) && f.length > 0 && (console.groupCollapsed(t), console.table ? console.table(f) : e.each(f, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), f = [];
          } }, invoke: function invoke(t, n, o) {
          var r,
              s,
              l,
              c = L;return n = n || p, o = M || o, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i && (s = c[o], !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(o, n) : s !== i && (l = s), e.isArray(a) ? a.push(l) : a !== i ? a = [a, l] : l !== i && (a = l), s;
        } }, g ? (L === i && x.initialize(), x.invoke(m)) : (L !== i && L.invoke("destroy"), x.initialize());
    }), a !== i ? a : this;
  }, e.fn.popup.settings = { name: "Popup", silent: !1, debug: !1, verbose: !1, performance: !0, namespace: "popup", observeChanges: !0, onCreate: function onCreate() {}, onRemove: function onRemove() {}, onShow: function onShow() {}, onVisible: function onVisible() {}, onHide: function onHide() {}, onUnplaceable: function onUnplaceable() {}, onHidden: function onHidden() {}, on: "hover", boundary: t, addTouchEvents: !0, position: "top left", variation: "", movePopup: !0, target: !1, popup: !1, inline: !1, preserve: !1, hoverable: !1, content: !1, html: !1, title: !1, closable: !0, hideOnScroll: "auto", exclusive: !1, context: "body", scrollContext: t, prefer: "opposite", lastResort: !1, arrowPixelsFromEdge: 20, delay: { show: 50, hide: 70 }, setFluidWidth: !0, duration: 200, transition: "scale", distanceAway: 0, jitter: 2, offset: 0, maxSearchDepth: 15, error: { invalidPosition: "The position you specified is not a valid position", cannotPlace: "Popup does not fit within the boundaries of the viewport", method: "The method you called is not defined.", noTransition: "This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>", notFound: "The target or popup you specified does not exist on the page" }, metadata: { activator: "activator", content: "content", html: "html", offset: "offset", position: "position", title: "title", variation: "variation" }, className: { active: "active", basic: "basic", animating: "animating", dropdown: "dropdown", fluid: "fluid", loading: "loading", popup: "ui popup", position: "top left center bottom right", visible: "visible", popupVisible: "visible" }, selector: { popup: ".ui.popup" }, templates: { escape: function escape(e) {
        var t = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" };return (/[&<>"'`]/.test(e) ? e.replace(/[&<>"'`]/g, function (e) {
            return t[e];
          }) : e
        );
      }, popup: function popup(t) {
        var n = "",
            o = e.fn.popup.settings.templates.escape;return (typeof t === "undefined" ? "undefined" : _typeof(t)) !== i && (_typeof(t.title) !== i && t.title && (t.title = o(t.title), n += '<div class="header">' + t.title + "</div>"), _typeof(t.content) !== i && t.content && (t.content = o(t.content), n += '<div class="content">' + t.content + "</div>")), n;
      } } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  void 0 !== (t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")()) && t.Math == Math || ("undefined" != typeof self && self.Math == Math ? self : Function("return this")());e.fn.progress = function (t) {
    var o,
        a = e(this),
        r = a.selector || "",
        s = new Date().getTime(),
        l = [],
        c = arguments[0],
        u = "string" == typeof c,
        d = [].slice.call(arguments, 1);return a.each(function () {
      var a,
          f = e.isPlainObject(t) ? e.extend(!0, {}, e.fn.progress.settings, t) : e.extend({}, e.fn.progress.settings),
          m = f.className,
          g = f.metadata,
          p = f.namespace,
          h = f.selector,
          v = f.error,
          b = "." + p,
          y = "module-" + p,
          x = e(this),
          C = e(this).find(h.bar),
          w = e(this).find(h.progress),
          S = e(this).find(h.label),
          k = this,
          T = x.data(y),
          A = !1;a = { initialize: function initialize() {
          a.debug("Initializing progress bar", f), a.set.duration(), a.set.transitionEvent(), a.read.metadata(), a.read.settings(), a.instantiate();
        }, instantiate: function instantiate() {
          a.verbose("Storing instance of progress", a), T = a, x.data(y, a);
        }, destroy: function destroy() {
          a.verbose("Destroying previous progress for", x), clearInterval(T.interval), a.remove.state(), x.removeData(y), T = i;
        }, reset: function reset() {
          a.remove.nextValue(), a.update.progress(0);
        }, complete: function complete() {
          (a.percent === i || a.percent < 100) && (a.remove.progressPoll(), a.set.percent(100));
        }, read: { metadata: function metadata() {
            var e = { percent: x.data(g.percent), total: x.data(g.total), value: x.data(g.value) };e.percent && (a.debug("Current percent value set from metadata", e.percent), a.set.percent(e.percent)), e.total && (a.debug("Total value set from metadata", e.total), a.set.total(e.total)), e.value && (a.debug("Current value set from metadata", e.value), a.set.value(e.value), a.set.progress(e.value));
          }, settings: function settings() {
            !1 !== f.total && (a.debug("Current total set in settings", f.total), a.set.total(f.total)), !1 !== f.value && (a.debug("Current value set in settings", f.value), a.set.value(f.value), a.set.progress(a.value)), !1 !== f.percent && (a.debug("Current percent set in settings", f.percent), a.set.percent(f.percent));
          } }, bind: { transitionEnd: function transitionEnd(e) {
            var t = a.get.transitionEnd();C.one(t + b, function (t) {
              clearTimeout(a.failSafeTimer), e.call(this, t);
            }), a.failSafeTimer = setTimeout(function () {
              C.triggerHandler(t);
            }, f.duration + f.failSafeDelay), a.verbose("Adding fail safe timer", a.timer);
          } }, increment: function increment(e) {
          var t, n;a.has.total() ? n = (t = a.get.value()) + (e = e || 1) : (n = (t = a.get.percent()) + (e = e || a.get.randomValue()), 100, a.debug("Incrementing percentage by", t, n)), n = a.get.normalizedValue(n), a.set.progress(n);
        }, decrement: function decrement(e) {
          var t, n;a.get.total() ? (n = (t = a.get.value()) - (e = e || 1), a.debug("Decrementing value by", e, t)) : (n = (t = a.get.percent()) - (e = e || a.get.randomValue()), a.debug("Decrementing percentage by", e, t)), n = a.get.normalizedValue(n), a.set.progress(n);
        }, has: { progressPoll: function progressPoll() {
            return a.progressPoll;
          }, total: function total() {
            return !1 !== a.get.total();
          } }, get: { text: function text(e) {
            var t = a.value || 0,
                n = a.total || 0,
                i = A ? a.get.displayPercent() : a.percent || 0,
                o = a.total > 0 ? n - t : 100 - i;return e = (e = e || "").replace("{value}", t).replace("{total}", n).replace("{left}", o).replace("{percent}", i), a.verbose("Adding variables to progress bar text", e), e;
          }, normalizedValue: function normalizedValue(e) {
            if (e < 0) return a.debug("Value cannot decrement below 0"), 0;if (a.has.total()) {
              if (e > a.total) return a.debug("Value cannot increment above total", a.total), a.total;
            } else if (e > 100) return a.debug("Value cannot increment above 100 percent"), 100;return e;
          }, updateInterval: function updateInterval() {
            return "auto" == f.updateInterval ? f.duration : f.updateInterval;
          }, randomValue: function randomValue() {
            return a.debug("Generating random increment percentage"), Math.floor(Math.random() * f.random.max + f.random.min);
          }, numericValue: function numericValue(e) {
            return "string" == typeof e ? "" !== e.replace(/[^\d.]/g, "") && +e.replace(/[^\d.]/g, "") : e;
          }, transitionEnd: function transitionEnd() {
            var e,
                t = n.createElement("element"),
                o = { transition: "transitionend", OTransition: "oTransitionEnd", MozTransition: "transitionend", WebkitTransition: "webkitTransitionEnd" };for (e in o) {
              if (t.style[e] !== i) return o[e];
            }
          }, displayPercent: function displayPercent() {
            var e = C.width(),
                t = x.width(),
                n = e > parseInt(C.css("min-width"), 10) ? e / t * 100 : a.percent;return f.precision > 0 ? Math.round(n * (10 * f.precision)) / (10 * f.precision) : Math.round(n);
          }, percent: function percent() {
            return a.percent || 0;
          }, value: function value() {
            return a.nextValue || a.value || 0;
          }, total: function total() {
            return a.total || !1;
          } }, create: { progressPoll: function progressPoll() {
            a.progressPoll = setTimeout(function () {
              a.update.toNextValue(), a.remove.progressPoll();
            }, a.get.updateInterval());
          } }, is: { complete: function complete() {
            return a.is.success() || a.is.warning() || a.is.error();
          }, success: function success() {
            return x.hasClass(m.success);
          }, warning: function warning() {
            return x.hasClass(m.warning);
          }, error: function error() {
            return x.hasClass(m.error);
          }, active: function active() {
            return x.hasClass(m.active);
          }, visible: function visible() {
            return x.is(":visible");
          } }, remove: { progressPoll: function progressPoll() {
            a.verbose("Removing progress poll timer"), a.progressPoll && (clearTimeout(a.progressPoll), delete a.progressPoll);
          }, nextValue: function nextValue() {
            a.verbose("Removing progress value stored for next update"), delete a.nextValue;
          }, state: function state() {
            a.verbose("Removing stored state"), delete a.total, delete a.percent, delete a.value;
          }, active: function active() {
            a.verbose("Removing active state"), x.removeClass(m.active);
          }, success: function success() {
            a.verbose("Removing success state"), x.removeClass(m.success);
          }, warning: function warning() {
            a.verbose("Removing warning state"), x.removeClass(m.warning);
          }, error: function error() {
            a.verbose("Removing error state"), x.removeClass(m.error);
          } }, set: { barWidth: function barWidth(e) {
            e > 100 ? a.error(v.tooHigh, e) : e < 0 ? a.error(v.tooLow, e) : (C.css("width", e + "%"), x.attr("data-percent", parseInt(e, 10)));
          }, duration: function duration(e) {
            e = "number" == typeof (e = e || f.duration) ? e + "ms" : e, a.verbose("Setting progress bar transition duration", e), C.css({ "transition-duration": e });
          }, percent: function percent(e) {
            e = "string" == typeof e ? +e.replace("%", "") : e, e = f.precision > 0 ? Math.round(e * (10 * f.precision)) / (10 * f.precision) : Math.round(e), a.percent = e, a.has.total() || (a.value = f.precision > 0 ? Math.round(e / 100 * a.total * (10 * f.precision)) / (10 * f.precision) : Math.round(e / 100 * a.total * 10) / 10, f.limitValues && (a.value = a.value > 100 ? 100 : a.value < 0 ? 0 : a.value)), a.set.barWidth(e), a.set.labelInterval(), a.set.labels(), f.onChange.call(k, e, a.value, a.total);
          }, labelInterval: function labelInterval() {
            clearInterval(a.interval), a.bind.transitionEnd(function () {
              a.verbose("Bar finished animating, removing continuous label updates"), clearInterval(a.interval), A = !1, a.set.labels();
            }), A = !0, a.interval = setInterval(function () {
              e.contains(n.documentElement, k) || (clearInterval(a.interval), A = !1), a.set.labels();
            }, f.framerate);
          }, labels: function labels() {
            a.verbose("Setting both bar progress and outer label text"), a.set.barLabel(), a.set.state();
          }, label: function label(e) {
            (e = e || "") && (e = a.get.text(e), a.verbose("Setting label to text", e), S.text(e));
          }, state: function state(e) {
            100 === (e = e !== i ? e : a.percent) ? f.autoSuccess && !(a.is.warning() || a.is.error() || a.is.success()) ? (a.set.success(), a.debug("Automatically triggering success at 100%")) : (a.verbose("Reached 100% removing active state"), a.remove.active(), a.remove.progressPoll()) : e > 0 ? (a.verbose("Adjusting active progress bar label", e), a.set.active()) : (a.remove.active(), a.set.label(f.text.active));
          }, barLabel: function barLabel(e) {
            e !== i ? w.text(a.get.text(e)) : "ratio" == f.label && a.total ? (a.verbose("Adding ratio to bar label"), w.text(a.get.text(f.text.ratio))) : "percent" == f.label && (a.verbose("Adding percentage to bar label"), w.text(a.get.text(f.text.percent)));
          }, active: function active(e) {
            e = e || f.text.active, a.debug("Setting active state"), f.showActivity && !a.is.active() && x.addClass(m.active), a.remove.warning(), a.remove.error(), a.remove.success(), (e = f.onLabelUpdate("active", e, a.value, a.total)) && a.set.label(e), a.bind.transitionEnd(function () {
              f.onActive.call(k, a.value, a.total);
            });
          }, success: function success(e) {
            e = e || f.text.success || f.text.active, a.debug("Setting success state"), x.addClass(m.success), a.remove.active(), a.remove.warning(), a.remove.error(), a.complete(), f.text.success ? (e = f.onLabelUpdate("success", e, a.value, a.total), a.set.label(e)) : (e = f.onLabelUpdate("active", e, a.value, a.total), a.set.label(e)), a.bind.transitionEnd(function () {
              f.onSuccess.call(k, a.total);
            });
          }, warning: function warning(e) {
            e = e || f.text.warning, a.debug("Setting warning state"), x.addClass(m.warning), a.remove.active(), a.remove.success(), a.remove.error(), a.complete(), (e = f.onLabelUpdate("warning", e, a.value, a.total)) && a.set.label(e), a.bind.transitionEnd(function () {
              f.onWarning.call(k, a.value, a.total);
            });
          }, error: function error(e) {
            e = e || f.text.error, a.debug("Setting error state"), x.addClass(m.error), a.remove.active(), a.remove.success(), a.remove.warning(), a.complete(), (e = f.onLabelUpdate("error", e, a.value, a.total)) && a.set.label(e), a.bind.transitionEnd(function () {
              f.onError.call(k, a.value, a.total);
            });
          }, transitionEvent: function transitionEvent() {
            a.get.transitionEnd();
          }, total: function total(e) {
            a.total = e;
          }, value: function value(e) {
            a.value = e;
          }, progress: function progress(e) {
            a.has.progressPoll() ? (a.debug("Updated within interval, setting next update to use new value", e), a.set.nextValue(e)) : (a.debug("First update in progress update interval, immediately updating", e), a.update.progress(e), a.create.progressPoll());
          }, nextValue: function nextValue(e) {
            a.nextValue = e;
          } }, update: { toNextValue: function toNextValue() {
            var e = a.nextValue;e && (a.debug("Update interval complete using last updated value", e), a.update.progress(e), a.remove.nextValue());
          }, progress: function progress(e) {
            var t;!1 === (e = a.get.numericValue(e)) && a.error(v.nonNumeric, e), e = a.get.normalizedValue(e), a.has.total() ? (a.set.value(e), t = e / a.total * 100, a.debug("Calculating percent complete from total", t), a.set.percent(t)) : (t = e, a.debug("Setting value to exact percentage value", t), a.set.percent(t));
          } }, setting: function setting(t, n) {
          if (a.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, f, t);else {
            if (n === i) return f[t];e.isPlainObject(f[t]) ? e.extend(!0, f[t], n) : f[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, a, t);else {
            if (n === i) return a[t];a[t] = n;
          }
        }, debug: function debug() {
          !f.silent && f.debug && (f.performance ? a.performance.log(arguments) : (a.debug = Function.prototype.bind.call(console.info, console, f.name + ":"), a.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !f.silent && f.verbose && f.debug && (f.performance ? a.performance.log(arguments) : (a.verbose = Function.prototype.bind.call(console.info, console, f.name + ":"), a.verbose.apply(console, arguments)));
        }, error: function error() {
          f.silent || (a.error = Function.prototype.bind.call(console.error, console, f.name + ":"), a.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;f.performance && (n = (t = new Date().getTime()) - (s || t), s = t, l.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: k, "Execution Time": n })), clearTimeout(a.performance.timer), a.performance.timer = setTimeout(a.performance.display, 500);
          }, display: function display() {
            var t = f.name + ":",
                n = 0;s = !1, clearTimeout(a.performance.timer), e.each(l, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", r && (t += " '" + r + "'"), (console.group !== i || console.table !== i) && l.length > 0 && (console.groupCollapsed(t), console.table ? console.table(l) : e.each(l, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), l = [];
          } }, invoke: function invoke(t, n, r) {
          var s,
              l,
              c,
              u = T;return n = n || d, r = k || r, "string" == typeof t && u !== i && (t = t.split(/[\. ]/), s = t.length - 1, e.each(t, function (n, o) {
            var r = n != s ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(u[r]) && n != s) u = u[r];else {
              if (u[r] !== i) return l = u[r], !1;if (!e.isPlainObject(u[o]) || n == s) return u[o] !== i ? (l = u[o], !1) : (a.error(v.method, t), !1);u = u[o];
            }
          })), e.isFunction(l) ? c = l.apply(r, n) : l !== i && (c = l), e.isArray(o) ? o.push(c) : o !== i ? o = [o, c] : c !== i && (o = c), l;
        } }, u ? (T === i && a.initialize(), a.invoke(c)) : (T !== i && T.invoke("destroy"), a.initialize());
    }), o !== i ? o : this;
  }, e.fn.progress.settings = { name: "Progress", namespace: "progress", silent: !1, debug: !1, verbose: !1, performance: !0, random: { min: 2, max: 5 }, duration: 300, updateInterval: "auto", autoSuccess: !0, showActivity: !0, limitValues: !0, label: "percent", precision: 0, framerate: 1e3 / 30, percent: !1, total: !1, value: !1, failSafeDelay: 100, onLabelUpdate: function onLabelUpdate(e, t, n, i) {
      return t;
    }, onChange: function onChange(e, t, n) {}, onSuccess: function onSuccess(e) {}, onActive: function onActive(e, t) {}, onError: function onError(e, t) {}, onWarning: function onWarning(e, t) {}, error: { method: "The method you called is not defined.", nonNumeric: "Progress value is non numeric", tooHigh: "Value specified is above 100%", tooLow: "Value specified is below 0%" }, regExp: { variable: /\{\$*[A-z0-9]+\}/g }, metadata: { percent: "percent", total: "total", value: "value" }, selector: { bar: "> .bar", label: "> .label", progress: ".bar > .progress" }, text: { active: !1, error: !1, success: !1, warning: !1, percent: "{percent}%", ratio: "{value} of {total}" }, className: { active: "active", error: "error", success: "success", warning: "warning" } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.rating = function (t) {
    var n,
        o = e(this),
        a = o.selector || "",
        r = new Date().getTime(),
        s = [],
        l = arguments[0],
        c = "string" == typeof l,
        u = [].slice.call(arguments, 1);return o.each(function () {
      var d,
          f,
          m = e.isPlainObject(t) ? e.extend(!0, {}, e.fn.rating.settings, t) : e.extend({}, e.fn.rating.settings),
          g = m.namespace,
          p = m.className,
          h = m.metadata,
          v = m.selector,
          b = (m.error, "." + g),
          y = "module-" + g,
          x = this,
          C = e(this).data(y),
          w = e(this),
          S = w.find(v.icon);f = { initialize: function initialize() {
          f.verbose("Initializing rating module", m), 0 === S.length && f.setup.layout(), m.interactive ? f.enable() : f.disable(), f.set.initialLoad(), f.set.rating(f.get.initialRating()), f.remove.initialLoad(), f.instantiate();
        }, instantiate: function instantiate() {
          f.verbose("Instantiating module", m), C = f, w.data(y, f);
        }, destroy: function destroy() {
          f.verbose("Destroying previous instance", C), f.remove.events(), w.removeData(y);
        }, refresh: function refresh() {
          S = w.find(v.icon);
        }, setup: { layout: function layout() {
            var t = f.get.maxRating(),
                n = e.fn.rating.settings.templates.icon(t);f.debug("Generating icon html dynamically"), w.html(n), f.refresh();
          } }, event: { mouseenter: function mouseenter() {
            var t = e(this);t.nextAll().removeClass(p.selected), w.addClass(p.selected), t.addClass(p.selected).prevAll().addClass(p.selected);
          }, mouseleave: function mouseleave() {
            w.removeClass(p.selected), S.removeClass(p.selected);
          }, click: function click() {
            var t = e(this),
                n = f.get.rating(),
                i = S.index(t) + 1;("auto" == m.clearable ? 1 === S.length : m.clearable) && n == i ? f.clearRating() : f.set.rating(i);
          } }, clearRating: function clearRating() {
          f.debug("Clearing current rating"), f.set.rating(0);
        }, bind: { events: function events() {
            f.verbose("Binding events"), w.on("mouseenter" + b, v.icon, f.event.mouseenter).on("mouseleave" + b, v.icon, f.event.mouseleave).on("click" + b, v.icon, f.event.click);
          } }, remove: { events: function events() {
            f.verbose("Removing events"), w.off(b);
          }, initialLoad: function initialLoad() {
            d = !1;
          } }, enable: function enable() {
          f.debug("Setting rating to interactive mode"), f.bind.events(), w.removeClass(p.disabled);
        }, disable: function disable() {
          f.debug("Setting rating to read-only mode"), f.remove.events(), w.addClass(p.disabled);
        }, is: { initialLoad: function initialLoad() {
            return d;
          } }, get: { initialRating: function initialRating() {
            return w.data(h.rating) !== i ? (w.removeData(h.rating), w.data(h.rating)) : m.initialRating;
          }, maxRating: function maxRating() {
            return w.data(h.maxRating) !== i ? (w.removeData(h.maxRating), w.data(h.maxRating)) : m.maxRating;
          }, rating: function rating() {
            var e = S.filter("." + p.active).length;return f.verbose("Current rating retrieved", e), e;
          } }, set: { rating: function rating(e) {
            var t = e - 1 >= 0 ? e - 1 : 0,
                n = S.eq(t);w.removeClass(p.selected), S.removeClass(p.selected).removeClass(p.active), e > 0 && (f.verbose("Setting current rating to", e), n.prevAll().addBack().addClass(p.active)), f.is.initialLoad() || m.onRate.call(x, e);
          }, initialLoad: function initialLoad() {
            d = !0;
          } }, setting: function setting(t, n) {
          if (f.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, m, t);else {
            if (n === i) return m[t];e.isPlainObject(m[t]) ? e.extend(!0, m[t], n) : m[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, f, t);else {
            if (n === i) return f[t];f[t] = n;
          }
        }, debug: function debug() {
          !m.silent && m.debug && (m.performance ? f.performance.log(arguments) : (f.debug = Function.prototype.bind.call(console.info, console, m.name + ":"), f.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !m.silent && m.verbose && m.debug && (m.performance ? f.performance.log(arguments) : (f.verbose = Function.prototype.bind.call(console.info, console, m.name + ":"), f.verbose.apply(console, arguments)));
        }, error: function error() {
          m.silent || (f.error = Function.prototype.bind.call(console.error, console, m.name + ":"), f.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;m.performance && (n = (t = new Date().getTime()) - (r || t), r = t, s.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: x, "Execution Time": n })), clearTimeout(f.performance.timer), f.performance.timer = setTimeout(f.performance.display, 500);
          }, display: function display() {
            var t = m.name + ":",
                n = 0;r = !1, clearTimeout(f.performance.timer), e.each(s, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", a && (t += " '" + a + "'"), o.length > 1 && (t += " (" + o.length + ")"), (console.group !== i || console.table !== i) && s.length > 0 && (console.groupCollapsed(t), console.table ? console.table(s) : e.each(s, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), s = [];
          } }, invoke: function invoke(t, o, a) {
          var r,
              s,
              l,
              c = C;return o = o || u, a = x || a, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i && (s = c[o], !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(a, o) : s !== i && (l = s), e.isArray(n) ? n.push(l) : n !== i ? n = [n, l] : l !== i && (n = l), s;
        } }, c ? (C === i && f.initialize(), f.invoke(l)) : (C !== i && C.invoke("destroy"), f.initialize());
    }), n !== i ? n : this;
  }, e.fn.rating.settings = { name: "Rating", namespace: "rating", slent: !1, debug: !1, verbose: !1, performance: !0, initialRating: 0, interactive: !0, maxRating: 4, clearable: "auto", fireOnInit: !1, onRate: function onRate(e) {}, error: { method: "The method you called is not defined", noMaximum: "No maximum rating specified. Cannot generate HTML automatically" }, metadata: { rating: "rating", maxRating: "maxRating" }, className: { active: "active", disabled: "disabled", selected: "selected", loading: "loading" }, selector: { icon: ".icon" }, templates: { icon: function icon(e) {
        for (var t = 1, n = ""; t <= e;) {
          n += '<i class="icon"></i>', t++;
        }return n;
      } } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.search = function (o) {
    var a,
        r = e(this),
        s = r.selector || "",
        l = new Date().getTime(),
        c = [],
        u = arguments[0],
        d = "string" == typeof u,
        f = [].slice.call(arguments, 1);return e(this).each(function () {
      var m,
          g = e.isPlainObject(o) ? e.extend(!0, {}, e.fn.search.settings, o) : e.extend({}, e.fn.search.settings),
          p = g.className,
          h = g.metadata,
          v = g.regExp,
          b = g.fields,
          y = g.selector,
          x = g.error,
          C = g.namespace,
          w = "." + C,
          S = C + "-module",
          k = e(this),
          T = k.find(y.prompt),
          A = k.find(y.searchButton),
          R = k.find(y.results),
          P = k.find(y.result),
          E = (k.find(y.category), this),
          F = k.data(S),
          O = !1,
          D = !1;m = { initialize: function initialize() {
          m.verbose("Initializing module"), m.get.settings(), m.determine.searchFields(), m.bind.events(), m.set.type(), m.create.results(), m.instantiate();
        }, instantiate: function instantiate() {
          m.verbose("Storing instance of module", m), F = m, k.data(S, m);
        }, destroy: function destroy() {
          m.verbose("Destroying instance"), k.off(w).removeData(S);
        }, refresh: function refresh() {
          m.debug("Refreshing selector cache"), T = k.find(y.prompt), A = k.find(y.searchButton), k.find(y.category), R = k.find(y.results), P = k.find(y.result);
        }, refreshResults: function refreshResults() {
          R = k.find(y.results), P = k.find(y.result);
        }, bind: { events: function events() {
            m.verbose("Binding events to search"), g.automatic && (k.on(m.get.inputEvent() + w, y.prompt, m.event.input), T.attr("autocomplete", "off")), k.on("focus" + w, y.prompt, m.event.focus).on("blur" + w, y.prompt, m.event.blur).on("keydown" + w, y.prompt, m.handleKeyboard).on("click" + w, y.searchButton, m.query).on("mousedown" + w, y.results, m.event.result.mousedown).on("mouseup" + w, y.results, m.event.result.mouseup).on("click" + w, y.result, m.event.result.click);
          } }, determine: { searchFields: function searchFields() {
            o && o.searchFields !== i && (g.searchFields = o.searchFields);
          } }, event: { input: function input() {
            g.searchDelay ? (clearTimeout(m.timer), m.timer = setTimeout(function () {
              m.is.focused() && m.query();
            }, g.searchDelay)) : m.query();
          }, focus: function focus() {
            m.set.focus(), g.searchOnFocus && m.has.minimumCharacters() && m.query(function () {
              m.can.show() && m.showResults();
            });
          }, blur: function blur(e) {
            var t = function t() {
              m.cancel.query(), m.remove.focus(), m.timer = setTimeout(m.hideResults, g.hideDelay);
            };n.activeElement === this || (D = !1, m.resultsClicked ? (m.debug("Determining if user action caused search to close"), k.one("click.close" + w, y.results, function (e) {
              m.is.inMessage(e) || O ? T.focus() : (O = !1, m.is.animating() || m.is.hidden() || t());
            })) : (m.debug("Input blurred without user action, closing results"), t()));
          }, result: { mousedown: function mousedown() {
              m.resultsClicked = !0;
            }, mouseup: function mouseup() {
              m.resultsClicked = !1;
            }, click: function click(n) {
              m.debug("Search result selected");var i = e(this),
                  o = i.find(y.title).eq(0),
                  a = i.is("a[href]") ? i : i.find("a[href]").eq(0),
                  r = a.attr("href") || !1,
                  s = a.attr("target") || !1,
                  l = (o.html(), o.length > 0 && o.text()),
                  c = m.get.results(),
                  u = i.data(h.result) || m.get.result(l, c);if (e.isFunction(g.onSelect) && !1 === g.onSelect.call(E, u, c)) return m.debug("Custom onSelect callback cancelled default select action"), void (O = !0);m.hideResults(), l && m.set.value(l), r && (m.verbose("Opening search link found in result", a), "_blank" == s || n.ctrlKey ? t.open(r) : t.location.href = r);
            } } }, handleKeyboard: function handleKeyboard(e) {
          var t,
              n = k.find(y.result),
              i = k.find(y.category),
              o = n.filter("." + p.active),
              a = n.index(o),
              r = n.length,
              s = o.length > 0,
              l = e.which,
              c = 13,
              u = 38,
              d = 40;if (l == 27 && (m.verbose("Escape key pressed, blurring search field"), m.hideResults(), D = !0), m.is.visible()) {
            if (l == c) {
              if (m.verbose("Enter key pressed, selecting active result"), n.filter("." + p.active).length > 0) return m.event.result.click.call(n.filter("." + p.active), e), e.preventDefault(), !1;
            } else l == u && s ? (m.verbose("Up key pressed, changing active result"), t = a - 1 < 0 ? a : a - 1, i.removeClass(p.active), n.removeClass(p.active).eq(t).addClass(p.active).closest(i).addClass(p.active), e.preventDefault()) : l == d && (m.verbose("Down key pressed, changing active result"), t = a + 1 >= r ? a : a + 1, i.removeClass(p.active), n.removeClass(p.active).eq(t).addClass(p.active).closest(i).addClass(p.active), e.preventDefault());
          } else l == c && (m.verbose("Enter key pressed, executing query"), m.query(), m.set.buttonPressed(), T.one("keyup", m.remove.buttonFocus));
        }, setup: { api: function api(t, n) {
            var i = { debug: g.debug, on: !1, cache: g.cache, action: "search", urlData: { query: t }, onSuccess: function onSuccess(e) {
                m.parse.response.call(E, e, t), n();
              }, onFailure: function onFailure() {
                m.displayMessage(x.serverError), n();
              }, onAbort: function onAbort(e) {}, onError: m.error };e.extend(!0, i, g.apiSettings), m.verbose("Setting up API request", i), k.api(i);
          } }, can: { useAPI: function useAPI() {
            return e.fn.api !== i;
          }, show: function show() {
            return m.is.focused() && !m.is.visible() && !m.is.empty();
          }, transition: function transition() {
            return g.transition && e.fn.transition !== i && k.transition("is supported");
          } }, is: { animating: function animating() {
            return R.hasClass(p.animating);
          }, hidden: function hidden() {
            return R.hasClass(p.hidden);
          }, inMessage: function inMessage(t) {
            if (t.target) {
              var i = e(t.target);return e.contains(n.documentElement, t.target) && i.closest(y.message).length > 0;
            }
          }, empty: function empty() {
            return "" === R.html();
          }, visible: function visible() {
            return R.filter(":visible").length > 0;
          }, focused: function focused() {
            return T.filter(":focus").length > 0;
          } }, get: { settings: function settings() {
            e.isPlainObject(o) && o.searchFullText && (g.fullTextSearch = o.searchFullText, m.error(g.error.oldSearchSyntax, E));
          }, inputEvent: function inputEvent() {
            var e = T[0];return e !== i && e.oninput !== i ? "input" : e !== i && e.onpropertychange !== i ? "propertychange" : "keyup";
          }, value: function value() {
            return T.val();
          }, results: function results() {
            return k.data(h.results);
          }, result: function result(t, n) {
            var o = ["title", "id"],
                a = !1;return t = t !== i ? t : m.get.value(), n = n !== i ? n : m.get.results(), "category" === g.type ? (m.debug("Finding result that matches", t), e.each(n, function (n, i) {
              if (e.isArray(i.results) && (a = m.search.object(t, i.results, o)[0])) return !1;
            })) : (m.debug("Finding result in results object", t), a = m.search.object(t, n, o)[0]), a || !1;
          } }, select: { firstResult: function firstResult() {
            m.verbose("Selecting first result"), P.first().addClass(p.active);
          } }, set: { focus: function focus() {
            k.addClass(p.focus);
          }, loading: function loading() {
            k.addClass(p.loading);
          }, value: function value(e) {
            m.verbose("Setting search input value", e), T.val(e);
          }, type: function type(e) {
            e = e || g.type, "category" == g.type && k.addClass(g.type);
          }, buttonPressed: function buttonPressed() {
            A.addClass(p.pressed);
          } }, remove: { loading: function loading() {
            k.removeClass(p.loading);
          }, focus: function focus() {
            k.removeClass(p.focus);
          }, buttonPressed: function buttonPressed() {
            A.removeClass(p.pressed);
          } }, query: function query(t) {
          t = e.isFunction(t) ? t : function () {};var n = m.get.value(),
              i = m.read.cache(n);t = t || function () {}, m.has.minimumCharacters() ? (i ? (m.debug("Reading result from cache", n), m.save.results(i.results), m.addResults(i.html), m.inject.id(i.results), t()) : (m.debug("Querying for", n), e.isPlainObject(g.source) || e.isArray(g.source) ? (m.search.local(n), t()) : m.can.useAPI() ? m.search.remote(n, t) : (m.error(x.source), t())), g.onSearchQuery.call(E, n)) : m.hideResults();
        }, search: { local: function local(e) {
            var t,
                n = m.search.object(e, g.content);m.set.loading(), m.save.results(n), m.debug("Returned full local search results", n), g.maxResults > 0 && (m.debug("Using specified max results", n), n = n.slice(0, g.maxResults)), "category" == g.type && (n = m.create.categoryResults(n)), t = m.generateResults({ results: n }), m.remove.loading(), m.addResults(t), m.inject.id(n), m.write.cache(e, { html: t, results: n });
          }, remote: function remote(t, n) {
            n = e.isFunction(n) ? n : function () {}, k.api("is loading") && k.api("abort"), m.setup.api(t, n), k.api("query");
          }, object: function object(t, n, o) {
            var a = [],
                r = [],
                s = [],
                l = t.toString().replace(v.escape, "\\$&"),
                c = new RegExp(v.beginsWith + l, "i"),
                u = function u(t, n) {
              var i = -1 == e.inArray(n, a),
                  o = -1 == e.inArray(n, s),
                  l = -1 == e.inArray(n, r);i && o && l && t.push(n);
            };return n = n || g.source, o = o !== i ? o : g.searchFields, e.isArray(o) || (o = [o]), n === i || !1 === n ? (m.error(x.source), []) : (e.each(o, function (i, o) {
              e.each(n, function (e, n) {
                "string" == typeof n[o] && (-1 !== n[o].search(c) ? u(a, n) : "exact" === g.fullTextSearch && m.exactSearch(t, n[o]) ? u(r, n) : 1 == g.fullTextSearch && m.fuzzySearch(t, n[o]) && u(s, n));
              });
            }), e.merge(r, s), e.merge(a, r), a);
          } }, exactSearch: function exactSearch(e, t) {
          return e = e.toLowerCase(), (t = t.toLowerCase()).indexOf(e) > -1;
        }, fuzzySearch: function fuzzySearch(e, t) {
          var n = t.length,
              i = e.length;if ("string" != typeof e) return !1;if (e = e.toLowerCase(), t = t.toLowerCase(), i > n) return !1;if (i === n) return e === t;e: for (var o = 0, a = 0; o < i; o++) {
            for (var r = e.charCodeAt(o); a < n;) {
              if (t.charCodeAt(a++) === r) continue e;
            }return !1;
          }return !0;
        }, parse: { response: function response(e, t) {
            var n = m.generateResults(e);m.verbose("Parsing server response", e), e !== i && t !== i && e[b.results] !== i && (m.addResults(n), m.inject.id(e[b.results]), m.write.cache(t, { html: n, results: e[b.results] }), m.save.results(e[b.results]));
          } }, cancel: { query: function query() {
            m.can.useAPI() && k.api("abort");
          } }, has: { minimumCharacters: function minimumCharacters() {
            return m.get.value().length >= g.minCharacters;
          }, results: function results() {
            return 0 !== R.length && "" != R.html();
          } }, clear: { cache: function cache(e) {
            var t = k.data(h.cache);e ? e && t && t[e] && (m.debug("Removing value from cache", e), delete t[e], k.data(h.cache, t)) : (m.debug("Clearing cache", e), k.removeData(h.cache));
          } }, read: { cache: function cache(e) {
            var t = k.data(h.cache);return !!g.cache && (m.verbose("Checking cache for generated html for query", e), "object" == (typeof t === "undefined" ? "undefined" : _typeof(t)) && t[e] !== i && t[e]);
          } }, create: { categoryResults: function categoryResults(t) {
            var n = {};return e.each(t, function (e, t) {
              t.category && (n[t.category] === i ? (m.verbose("Creating new category of results", t.category), n[t.category] = { name: t.category, results: [t] }) : n[t.category].results.push(t));
            }), n;
          }, id: function id(e, t) {
            var n,
                o = e + 1;return t !== i ? (n = String.fromCharCode(97 + t) + o, m.verbose("Creating category result id", n)) : (n = o, m.verbose("Creating result id", n)), n;
          }, results: function results() {
            0 === R.length && (R = e("<div />").addClass(p.results).appendTo(k));
          } }, inject: { result: function result(e, t, n) {
            m.verbose("Injecting result into results");var o = n !== i ? R.children().eq(n).children(y.results).first().children(y.result).eq(t) : R.children(y.result).eq(t);m.verbose("Injecting results metadata", o), o.data(h.result, e);
          }, id: function id(t) {
            m.debug("Injecting unique ids into results");var n = 0,
                o = 0;return "category" === g.type ? e.each(t, function (t, a) {
              o = 0, e.each(a.results, function (e, t) {
                var r = a.results[e];r.id === i && (r.id = m.create.id(o, n)), m.inject.result(r, o, n), o++;
              }), n++;
            }) : e.each(t, function (e, n) {
              var a = t[e];a.id === i && (a.id = m.create.id(o)), m.inject.result(a, o), o++;
            }), t;
          } }, save: { results: function results(e) {
            m.verbose("Saving current search results to metadata", e), k.data(h.results, e);
          } }, write: { cache: function cache(e, t) {
            var n = k.data(h.cache) !== i ? k.data(h.cache) : {};g.cache && (m.verbose("Writing generated html to cache", e, t), n[e] = t, k.data(h.cache, n));
          } }, addResults: function addResults(t) {
          if (e.isFunction(g.onResultsAdd) && !1 === g.onResultsAdd.call(R, t)) return m.debug("onResultsAdd callback cancelled default action"), !1;t ? (R.html(t), m.refreshResults(), g.selectFirstResult && m.select.firstResult(), m.showResults()) : m.hideResults(function () {
            R.empty();
          });
        }, showResults: function showResults(t) {
          t = e.isFunction(t) ? t : function () {}, D || !m.is.visible() && m.has.results() && (m.can.transition() ? (m.debug("Showing results with css animations"), R.transition({ animation: g.transition + " in", debug: g.debug, verbose: g.verbose, duration: g.duration, onComplete: function onComplete() {
              t();
            }, queue: !0 })) : (m.debug("Showing results with javascript"), R.stop().fadeIn(g.duration, g.easing)), g.onResultsOpen.call(R));
        }, hideResults: function hideResults(t) {
          t = e.isFunction(t) ? t : function () {}, m.is.visible() && (m.can.transition() ? (m.debug("Hiding results with css animations"), R.transition({ animation: g.transition + " out", debug: g.debug, verbose: g.verbose, duration: g.duration, onComplete: function onComplete() {
              t();
            }, queue: !0 })) : (m.debug("Hiding results with javascript"), R.stop().fadeOut(g.duration, g.easing)), g.onResultsClose.call(R));
        }, generateResults: function generateResults(t) {
          m.debug("Generating html from response", t);var n = g.templates[g.type],
              i = e.isPlainObject(t[b.results]) && !e.isEmptyObject(t[b.results]),
              o = e.isArray(t[b.results]) && t[b.results].length > 0,
              a = "";return i || o ? (g.maxResults > 0 && (i ? "standard" == g.type && m.error(x.maxResults) : t[b.results] = t[b.results].slice(0, g.maxResults)), e.isFunction(n) ? a = n(t, b) : m.error(x.noTemplate, !1)) : g.showNoResults && (a = m.displayMessage(x.noResults, "empty")), g.onResults.call(E, t), a;
        }, displayMessage: function displayMessage(e, t) {
          return t = t || "standard", m.debug("Displaying message", e, t), m.addResults(g.templates.message(e, t)), g.templates.message(e, t);
        }, setting: function setting(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, g, t);else {
            if (n === i) return g[t];g[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, m, t);else {
            if (n === i) return m[t];m[t] = n;
          }
        }, debug: function debug() {
          !g.silent && g.debug && (g.performance ? m.performance.log(arguments) : (m.debug = Function.prototype.bind.call(console.info, console, g.name + ":"), m.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !g.silent && g.verbose && g.debug && (g.performance ? m.performance.log(arguments) : (m.verbose = Function.prototype.bind.call(console.info, console, g.name + ":"), m.verbose.apply(console, arguments)));
        }, error: function error() {
          g.silent || (m.error = Function.prototype.bind.call(console.error, console, g.name + ":"), m.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;g.performance && (n = (t = new Date().getTime()) - (l || t), l = t, c.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: E, "Execution Time": n })), clearTimeout(m.performance.timer), m.performance.timer = setTimeout(m.performance.display, 500);
          }, display: function display() {
            var t = g.name + ":",
                n = 0;l = !1, clearTimeout(m.performance.timer), e.each(c, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", s && (t += " '" + s + "'"), r.length > 1 && (t += " (" + r.length + ")"), (console.group !== i || console.table !== i) && c.length > 0 && (console.groupCollapsed(t), console.table ? console.table(c) : e.each(c, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), c = [];
          } }, invoke: function invoke(t, n, o) {
          var r,
              s,
              l,
              c = F;return n = n || f, o = E || o, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i && (s = c[o], !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(o, n) : s !== i && (l = s), e.isArray(a) ? a.push(l) : a !== i ? a = [a, l] : l !== i && (a = l), s;
        } }, d ? (F === i && m.initialize(), m.invoke(u)) : (F !== i && F.invoke("destroy"), m.initialize());
    }), a !== i ? a : this;
  }, e.fn.search.settings = { name: "Search", namespace: "search", silent: !1, debug: !1, verbose: !1, performance: !0, type: "standard", minCharacters: 1, selectFirstResult: !1, apiSettings: !1, source: !1, searchOnFocus: !0, searchFields: ["title", "description"], displayField: "", fullTextSearch: "exact", automatic: !0, hideDelay: 0, searchDelay: 200, maxResults: 7, cache: !0, showNoResults: !0, transition: "scale", duration: 200, easing: "easeOutExpo", onSelect: !1, onResultsAdd: !1, onSearchQuery: function onSearchQuery(e) {}, onResults: function onResults(e) {}, onResultsOpen: function onResultsOpen() {}, onResultsClose: function onResultsClose() {}, className: { animating: "animating", active: "active", empty: "empty", focus: "focus", hidden: "hidden", loading: "loading", results: "results", pressed: "down" }, error: { source: "Cannot search. No source used, and Semantic API module was not included", noResults: "Your search returned no results", logging: "Error in debug logging, exiting.", noEndpoint: "No search endpoint was specified", noTemplate: "A valid template name was not specified.", oldSearchSyntax: "searchFullText setting has been renamed fullTextSearch for consistency, please adjust your settings.", serverError: "There was an issue querying the server.", maxResults: "Results must be an array to use maxResults setting", method: "The method you called is not defined." }, metadata: { cache: "cache", results: "results", result: "result" }, regExp: { escape: /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, beginsWith: "(?:s|^)" }, fields: { categories: "results", categoryName: "name", categoryResults: "results", description: "description", image: "image", price: "price", results: "results", title: "title", url: "url", action: "action", actionText: "text", actionURL: "url" }, selector: { prompt: ".prompt", searchButton: ".search.button", results: ".results", message: ".results > .message", category: ".category", result: ".result", title: ".title, .name" }, templates: { escape: function escape(e) {
        var t = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" };return (/[&<>"'`]/.test(e) ? e.replace(/[&<>"'`]/g, function (e) {
            return t[e];
          }) : e
        );
      }, message: function message(e, t) {
        var n = "";return e !== i && t !== i && (n += '<div class="message ' + t + '">', n += "empty" == t ? '<div class="header">No Results</div class="header"><div class="description">' + e + '</div class="description">' : ' <div class="description">' + e + "</div>", n += "</div>"), n;
      }, category: function category(t, n) {
        var o = "";e.fn.search.settings.templates.escape;return t[n.categoryResults] !== i && (e.each(t[n.categoryResults], function (t, a) {
          a[n.results] !== i && a.results.length > 0 && (o += '<div class="category">', a[n.categoryName] !== i && (o += '<div class="name">' + a[n.categoryName] + "</div>"), o += '<div class="results">', e.each(a.results, function (e, t) {
            t[n.url] ? o += '<a class="result" href="' + t[n.url] + '">' : o += '<a class="result">', t[n.image] !== i && (o += '<div class="image"> <img src="' + t[n.image] + '"></div>'), o += '<div class="content">', t[n.price] !== i && (o += '<div class="price">' + t[n.price] + "</div>"), t[n.title] !== i && (o += '<div class="title">' + t[n.title] + "</div>"), t[n.description] !== i && (o += '<div class="description">' + t[n.description] + "</div>"), o += "</div>", o += "</a>";
          }), o += "</div>", o += "</div>");
        }), t[n.action] && (o += '<a href="' + t[n.action][n.actionURL] + '" class="action">' + t[n.action][n.actionText] + "</a>"), o);
      }, standard: function standard(t, n) {
        var o = "";return t[n.results] !== i && (e.each(t[n.results], function (e, t) {
          t[n.url] ? o += '<a class="result" href="' + t[n.url] + '">' : o += '<a class="result">', t[n.image] !== i && (o += '<div class="image"> <img src="' + t[n.image] + '"></div>'), o += '<div class="content">', t[n.price] !== i && (o += '<div class="price">' + t[n.price] + "</div>"), t[n.title] !== i && (o += '<div class="title">' + t[n.title] + "</div>"), t[n.description] !== i && (o += '<div class="description">' + t[n.description] + "</div>"), o += "</div>", o += "</a>";
        }), t[n.action] && (o += '<a href="' + t[n.action][n.actionURL] + '" class="action">' + t[n.action][n.actionText] + "</a>"), o);
      } } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.shape = function (o) {
    var a,
        r = e(this),
        s = (e("body"), new Date().getTime()),
        l = [],
        c = arguments[0],
        u = "string" == typeof c,
        d = [].slice.call(arguments, 1),
        f = t.requestAnimationFrame || t.mozRequestAnimationFrame || t.webkitRequestAnimationFrame || t.msRequestAnimationFrame || function (e) {
      setTimeout(e, 0);
    };return r.each(function () {
      var t,
          m,
          g,
          p = r.selector || "",
          h = e.isPlainObject(o) ? e.extend(!0, {}, e.fn.shape.settings, o) : e.extend({}, e.fn.shape.settings),
          v = h.namespace,
          b = h.selector,
          y = h.error,
          x = h.className,
          C = "." + v,
          w = "module-" + v,
          S = e(this),
          k = S.find(b.sides),
          T = S.find(b.side),
          A = !1,
          R = this,
          P = S.data(w);g = { initialize: function initialize() {
          g.verbose("Initializing module for", R), g.set.defaultSide(), g.instantiate();
        }, instantiate: function instantiate() {
          g.verbose("Storing instance of module", g), P = g, S.data(w, P);
        }, destroy: function destroy() {
          g.verbose("Destroying previous module for", R), S.removeData(w).off(C);
        }, refresh: function refresh() {
          g.verbose("Refreshing selector cache for", R), S = e(R), k = e(this).find(b.shape), T = e(this).find(b.side);
        }, repaint: function repaint() {
          g.verbose("Forcing repaint event");(k[0] || n.createElement("div")).offsetWidth;
        }, animate: function animate(e, n) {
          g.verbose("Animating box with properties", e), n = n || function (e) {
            g.verbose("Executing animation callback"), e !== i && e.stopPropagation(), g.reset(), g.set.active();
          }, h.beforeChange.call(m[0]), g.get.transitionEvent() ? (g.verbose("Starting CSS animation"), S.addClass(x.animating), k.css(e).one(g.get.transitionEvent(), n), g.set.duration(h.duration), f(function () {
            S.addClass(x.animating), t.addClass(x.hidden);
          })) : n();
        }, queue: function queue(e) {
          g.debug("Queueing animation of", e), k.one(g.get.transitionEvent(), function () {
            g.debug("Executing queued animation"), setTimeout(function () {
              S.shape(e);
            }, 0);
          });
        }, reset: function reset() {
          g.verbose("Animating states reset"), S.removeClass(x.animating).attr("style", "").removeAttr("style"), k.attr("style", "").removeAttr("style"), T.attr("style", "").removeAttr("style").removeClass(x.hidden), m.removeClass(x.animating).attr("style", "").removeAttr("style");
        }, is: { complete: function complete() {
            return T.filter("." + x.active)[0] == m[0];
          }, animating: function animating() {
            return S.hasClass(x.animating);
          } }, set: { defaultSide: function defaultSide() {
            t = S.find("." + h.className.active), m = t.next(b.side).length > 0 ? t.next(b.side) : S.find(b.side).first(), A = !1, g.verbose("Active side set to", t), g.verbose("Next side set to", m);
          }, duration: function duration(e) {
            e = "number" == typeof (e = e || h.duration) ? e + "ms" : e, g.verbose("Setting animation duration", e), (h.duration || 0 === h.duration) && k.add(T).css({ "-webkit-transition-duration": e, "-moz-transition-duration": e, "-ms-transition-duration": e, "-o-transition-duration": e, "transition-duration": e });
          }, currentStageSize: function currentStageSize() {
            var e = S.find("." + h.className.active),
                t = e.outerWidth(!0),
                n = e.outerHeight(!0);S.css({ width: t, height: n });
          }, stageSize: function stageSize() {
            var e = S.clone().addClass(x.loading),
                t = e.find("." + h.className.active),
                n = A ? e.find(b.side).eq(A) : t.next(b.side).length > 0 ? t.next(b.side) : e.find(b.side).first(),
                i = "next" == h.width ? n.outerWidth(!0) : "initial" == h.width ? S.width() : h.width,
                o = "next" == h.height ? n.outerHeight(!0) : "initial" == h.height ? S.height() : h.height;t.removeClass(x.active), n.addClass(x.active), e.insertAfter(S), e.remove(), "auto" != h.width && (S.css("width", i + h.jitter), g.verbose("Specifying width during animation", i)), "auto" != h.height && (S.css("height", o + h.jitter), g.verbose("Specifying height during animation", o));
          }, nextSide: function nextSide(e) {
            A = e, m = T.filter(e), A = T.index(m), 0 === m.length && (g.set.defaultSide(), g.error(y.side)), g.verbose("Next side manually set to", m);
          }, active: function active() {
            g.verbose("Setting new side to active", m), T.removeClass(x.active), m.addClass(x.active), h.onChange.call(m[0]), g.set.defaultSide();
          } }, flip: { up: function up() {
            if (!g.is.complete() || g.is.animating() || h.allowRepeats) {
              if (g.is.animating()) g.queue("flip up");else {
                g.debug("Flipping up", m);var e = g.get.transform.up();g.set.stageSize(), g.stage.above(), g.animate(e);
              }
            } else g.debug("Side already visible", m);
          }, down: function down() {
            if (!g.is.complete() || g.is.animating() || h.allowRepeats) {
              if (g.is.animating()) g.queue("flip down");else {
                g.debug("Flipping down", m);var e = g.get.transform.down();g.set.stageSize(), g.stage.below(), g.animate(e);
              }
            } else g.debug("Side already visible", m);
          }, left: function left() {
            if (!g.is.complete() || g.is.animating() || h.allowRepeats) {
              if (g.is.animating()) g.queue("flip left");else {
                g.debug("Flipping left", m);var e = g.get.transform.left();g.set.stageSize(), g.stage.left(), g.animate(e);
              }
            } else g.debug("Side already visible", m);
          }, right: function right() {
            if (!g.is.complete() || g.is.animating() || h.allowRepeats) {
              if (g.is.animating()) g.queue("flip right");else {
                g.debug("Flipping right", m);var e = g.get.transform.right();g.set.stageSize(), g.stage.right(), g.animate(e);
              }
            } else g.debug("Side already visible", m);
          }, over: function over() {
            !g.is.complete() || g.is.animating() || h.allowRepeats ? g.is.animating() ? g.queue("flip over") : (g.debug("Flipping over", m), g.set.stageSize(), g.stage.behind(), g.animate(g.get.transform.over())) : g.debug("Side already visible", m);
          }, back: function back() {
            !g.is.complete() || g.is.animating() || h.allowRepeats ? g.is.animating() ? g.queue("flip back") : (g.debug("Flipping back", m), g.set.stageSize(), g.stage.behind(), g.animate(g.get.transform.back())) : g.debug("Side already visible", m);
          } }, get: { transform: { up: function up() {
              return { transform: "translateY(" + -(t.outerHeight(!0) - m.outerHeight(!0)) / 2 + "px) translateZ(" + -t.outerHeight(!0) / 2 + "px) rotateX(-90deg)" };
            }, down: function down() {
              return { transform: "translateY(" + -(t.outerHeight(!0) - m.outerHeight(!0)) / 2 + "px) translateZ(" + -t.outerHeight(!0) / 2 + "px) rotateX(90deg)" };
            }, left: function left() {
              return { transform: "translateX(" + -(t.outerWidth(!0) - m.outerWidth(!0)) / 2 + "px) translateZ(" + -t.outerWidth(!0) / 2 + "px) rotateY(90deg)" };
            }, right: function right() {
              return { transform: "translateX(" + -(t.outerWidth(!0) - m.outerWidth(!0)) / 2 + "px) translateZ(" + -t.outerWidth(!0) / 2 + "px) rotateY(-90deg)" };
            }, over: function over() {
              return { transform: "translateX(" + -(t.outerWidth(!0) - m.outerWidth(!0)) / 2 + "px) rotateY(180deg)" };
            }, back: function back() {
              return { transform: "translateX(" + -(t.outerWidth(!0) - m.outerWidth(!0)) / 2 + "px) rotateY(-180deg)" };
            } }, transitionEvent: function transitionEvent() {
            var e,
                t = n.createElement("element"),
                o = { transition: "transitionend", OTransition: "oTransitionEnd", MozTransition: "transitionend", WebkitTransition: "webkitTransitionEnd" };for (e in o) {
              if (t.style[e] !== i) return o[e];
            }
          }, nextSide: function nextSide() {
            return t.next(b.side).length > 0 ? t.next(b.side) : S.find(b.side).first();
          } }, stage: { above: function above() {
            var e = { origin: (t.outerHeight(!0) - m.outerHeight(!0)) / 2, depth: { active: m.outerHeight(!0) / 2, next: t.outerHeight(!0) / 2 } };g.verbose("Setting the initial animation position as above", m, e), k.css({ transform: "translateZ(-" + e.depth.active + "px)" }), t.css({ transform: "rotateY(0deg) translateZ(" + e.depth.active + "px)" }), m.addClass(x.animating).css({ top: e.origin + "px", transform: "rotateX(90deg) translateZ(" + e.depth.next + "px)" });
          }, below: function below() {
            var e = { origin: (t.outerHeight(!0) - m.outerHeight(!0)) / 2, depth: { active: m.outerHeight(!0) / 2, next: t.outerHeight(!0) / 2 } };g.verbose("Setting the initial animation position as below", m, e), k.css({ transform: "translateZ(-" + e.depth.active + "px)" }), t.css({ transform: "rotateY(0deg) translateZ(" + e.depth.active + "px)" }), m.addClass(x.animating).css({ top: e.origin + "px", transform: "rotateX(-90deg) translateZ(" + e.depth.next + "px)" });
          }, left: function left() {
            var e = t.outerWidth(!0),
                n = m.outerWidth(!0),
                i = { origin: (e - n) / 2, depth: { active: n / 2, next: e / 2 } };g.verbose("Setting the initial animation position as left", m, i), k.css({ transform: "translateZ(-" + i.depth.active + "px)" }), t.css({ transform: "rotateY(0deg) translateZ(" + i.depth.active + "px)" }), m.addClass(x.animating).css({ left: i.origin + "px", transform: "rotateY(-90deg) translateZ(" + i.depth.next + "px)" });
          }, right: function right() {
            var e = t.outerWidth(!0),
                n = m.outerWidth(!0),
                i = { origin: (e - n) / 2, depth: { active: n / 2, next: e / 2 } };g.verbose("Setting the initial animation position as left", m, i), k.css({ transform: "translateZ(-" + i.depth.active + "px)" }), t.css({ transform: "rotateY(0deg) translateZ(" + i.depth.active + "px)" }), m.addClass(x.animating).css({ left: i.origin + "px", transform: "rotateY(90deg) translateZ(" + i.depth.next + "px)" });
          }, behind: function behind() {
            var e = t.outerWidth(!0),
                n = m.outerWidth(!0),
                i = { origin: (e - n) / 2, depth: { active: n / 2, next: e / 2 } };g.verbose("Setting the initial animation position as behind", m, i), t.css({ transform: "rotateY(0deg)" }), m.addClass(x.animating).css({ left: i.origin + "px", transform: "rotateY(-180deg)" });
          } }, setting: function setting(t, n) {
          if (g.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, h, t);else {
            if (n === i) return h[t];e.isPlainObject(h[t]) ? e.extend(!0, h[t], n) : h[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, g, t);else {
            if (n === i) return g[t];g[t] = n;
          }
        }, debug: function debug() {
          !h.silent && h.debug && (h.performance ? g.performance.log(arguments) : (g.debug = Function.prototype.bind.call(console.info, console, h.name + ":"), g.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !h.silent && h.verbose && h.debug && (h.performance ? g.performance.log(arguments) : (g.verbose = Function.prototype.bind.call(console.info, console, h.name + ":"), g.verbose.apply(console, arguments)));
        }, error: function error() {
          h.silent || (g.error = Function.prototype.bind.call(console.error, console, h.name + ":"), g.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;h.performance && (n = (t = new Date().getTime()) - (s || t), s = t, l.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: R, "Execution Time": n })), clearTimeout(g.performance.timer), g.performance.timer = setTimeout(g.performance.display, 500);
          }, display: function display() {
            var t = h.name + ":",
                n = 0;s = !1, clearTimeout(g.performance.timer), e.each(l, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", p && (t += " '" + p + "'"), r.length > 1 && (t += " (" + r.length + ")"), (console.group !== i || console.table !== i) && l.length > 0 && (console.groupCollapsed(t), console.table ? console.table(l) : e.each(l, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), l = [];
          } }, invoke: function invoke(t, n, o) {
          var r,
              s,
              l,
              c = P;return n = n || d, o = R || o, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i && (s = c[o], !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(o, n) : s !== i && (l = s), e.isArray(a) ? a.push(l) : a !== i ? a = [a, l] : l !== i && (a = l), s;
        } }, u ? (P === i && g.initialize(), g.invoke(c)) : (P !== i && P.invoke("destroy"), g.initialize());
    }), a !== i ? a : this;
  }, e.fn.shape.settings = { name: "Shape", silent: !1, debug: !1, verbose: !1, jitter: 0, performance: !0, namespace: "shape", width: "initial", height: "initial", beforeChange: function beforeChange() {}, onChange: function onChange() {}, allowRepeats: !1, duration: !1, error: { side: "You tried to switch to a side that does not exist.", method: "The method you called is not defined" }, className: { animating: "animating", hidden: "hidden", loading: "loading", active: "active" }, selector: { sides: ".sides", side: ".side" } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.sidebar = function (o) {
    var a,
        r = e(this),
        s = e(t),
        l = e(n),
        c = e("html"),
        u = e("head"),
        d = r.selector || "",
        f = new Date().getTime(),
        m = [],
        g = arguments[0],
        p = "string" == typeof g,
        h = [].slice.call(arguments, 1),
        v = t.requestAnimationFrame || t.mozRequestAnimationFrame || t.webkitRequestAnimationFrame || t.msRequestAnimationFrame || function (e) {
      setTimeout(e, 0);
    };return r.each(function () {
      var r,
          b,
          y,
          x,
          C,
          w,
          S = e.isPlainObject(o) ? e.extend(!0, {}, e.fn.sidebar.settings, o) : e.extend({}, e.fn.sidebar.settings),
          k = S.selector,
          T = S.className,
          A = S.namespace,
          R = S.regExp,
          P = S.error,
          E = "." + A,
          F = "module-" + A,
          O = e(this),
          D = e(S.context),
          q = O.children(k.sidebar),
          j = (D.children(k.fixed), D.children(k.pusher)),
          z = this,
          I = O.data(F);w = { initialize: function initialize() {
          w.debug("Initializing sidebar", o), w.create.id(), C = w.get.transitionEvent(), S.delaySetup ? v(w.setup.layout) : w.setup.layout(), v(function () {
            w.setup.cache();
          }), w.instantiate();
        }, instantiate: function instantiate() {
          w.verbose("Storing instance of module", w), I = w, O.data(F, w);
        }, create: { id: function id() {
            y = (Math.random().toString(16) + "000000000").substr(2, 8), b = "." + y, w.verbose("Creating unique id for element", y);
          } }, destroy: function destroy() {
          w.verbose("Destroying previous module for", O), O.off(E).removeData(F), w.is.ios() && w.remove.ios(), D.off(b), s.off(b), l.off(b);
        }, event: { clickaway: function clickaway(e) {
            var t = j.find(e.target).length > 0 || j.is(e.target),
                n = D.is(e.target);t && (w.verbose("User clicked on dimmed page"), w.hide()), n && (w.verbose("User clicked on dimmable context (scaled out page)"), w.hide());
          }, touch: function touch(e) {}, containScroll: function containScroll(e) {
            z.scrollTop <= 0 && (z.scrollTop = 1), z.scrollTop + z.offsetHeight >= z.scrollHeight && (z.scrollTop = z.scrollHeight - z.offsetHeight - 1);
          }, scroll: function scroll(t) {
            0 === e(t.target).closest(k.sidebar).length && t.preventDefault();
          } }, bind: { clickaway: function clickaway() {
            w.verbose("Adding clickaway events to context", D), S.closable && D.on("click" + b, w.event.clickaway).on("touchend" + b, w.event.clickaway);
          }, scrollLock: function scrollLock() {
            S.scrollLock && (w.debug("Disabling page scroll"), s.on("DOMMouseScroll" + b, w.event.scroll)), w.verbose("Adding events to contain sidebar scroll"), l.on("touchmove" + b, w.event.touch), O.on("scroll" + E, w.event.containScroll);
          } }, unbind: { clickaway: function clickaway() {
            w.verbose("Removing clickaway events from context", D), D.off(b);
          }, scrollLock: function scrollLock() {
            w.verbose("Removing scroll lock from page"), l.off(b), s.off(b), O.off("scroll" + E);
          } }, add: { inlineCSS: function inlineCSS() {
            var t,
                n = w.cache.width || O.outerWidth(),
                i = w.cache.height || O.outerHeight(),
                o = w.is.rtl(),
                a = w.get.direction(),
                s = { left: n, right: -n, top: i, bottom: -i };o && (w.verbose("RTL detected, flipping widths"), s.left = -n, s.right = n), t = "<style>", "left" === a || "right" === a ? (w.debug("Adding CSS rules for animation distance", n), t += " .ui.visible." + a + ".sidebar ~ .fixed, .ui.visible." + a + ".sidebar ~ .pusher {   -webkit-transform: translate3d(" + s[a] + "px, 0, 0);           transform: translate3d(" + s[a] + "px, 0, 0); }") : "top" !== a && "bottom" != a || (t += " .ui.visible." + a + ".sidebar ~ .fixed, .ui.visible." + a + ".sidebar ~ .pusher {   -webkit-transform: translate3d(0, " + s[a] + "px, 0);           transform: translate3d(0, " + s[a] + "px, 0); }"), w.is.ie() && ("left" === a || "right" === a ? (w.debug("Adding CSS rules for animation distance", n), t += " body.pushable > .ui.visible." + a + ".sidebar ~ .pusher:after {   -webkit-transform: translate3d(" + s[a] + "px, 0, 0);           transform: translate3d(" + s[a] + "px, 0, 0); }") : "top" !== a && "bottom" != a || (t += " body.pushable > .ui.visible." + a + ".sidebar ~ .pusher:after {   -webkit-transform: translate3d(0, " + s[a] + "px, 0);           transform: translate3d(0, " + s[a] + "px, 0); }"), t += " body.pushable > .ui.visible.left.sidebar ~ .ui.visible.right.sidebar ~ .pusher:after, body.pushable > .ui.visible.right.sidebar ~ .ui.visible.left.sidebar ~ .pusher:after {   -webkit-transform: translate3d(0px, 0, 0);           transform: translate3d(0px, 0, 0); }"), r = e(t += "</style>").appendTo(u), w.debug("Adding sizing css to head", r);
          } }, refresh: function refresh() {
          w.verbose("Refreshing selector cache"), D = e(S.context), q = D.children(k.sidebar), j = D.children(k.pusher), D.children(k.fixed), w.clear.cache();
        }, refreshSidebars: function refreshSidebars() {
          w.verbose("Refreshing other sidebars"), q = D.children(k.sidebar);
        }, repaint: function repaint() {
          w.verbose("Forcing repaint event"), z.style.display = "none";z.offsetHeight;z.scrollTop = z.scrollTop, z.style.display = "";
        }, setup: { cache: function cache() {
            w.cache = { width: O.outerWidth(), height: O.outerHeight(), rtl: "rtl" == O.css("direction") };
          }, layout: function layout() {
            0 === D.children(k.pusher).length && (w.debug("Adding wrapper element for sidebar"), w.error(P.pusher), j = e('<div class="pusher" />'), D.children().not(k.omitted).not(q).wrapAll(j), w.refresh()), 0 !== O.nextAll(k.pusher).length && O.nextAll(k.pusher)[0] === j[0] || (w.debug("Moved sidebar to correct parent element"), w.error(P.movedSidebar, z), O.detach().prependTo(D), w.refresh()), w.clear.cache(), w.set.pushable(), w.set.direction();
          } }, attachEvents: function attachEvents(t, n) {
          var i = e(t);n = e.isFunction(w[n]) ? w[n] : w.toggle, i.length > 0 ? (w.debug("Attaching sidebar events to element", t, n), i.on("click" + E, n)) : w.error(P.notFound, t);
        }, show: function show(t) {
          if (t = e.isFunction(t) ? t : function () {}, w.is.hidden()) {
            if (w.refreshSidebars(), S.overlay && (w.error(P.overlay), S.transition = "overlay"), w.refresh(), w.othersActive()) if (w.debug("Other sidebars currently visible"), S.exclusive) {
              if ("overlay" != S.transition) return void w.hideOthers(w.show);w.hideOthers();
            } else S.transition = "overlay";w.pushPage(function () {
              t.call(z), S.onShow.call(z);
            }), S.onChange.call(z), S.onVisible.call(z);
          } else w.debug("Sidebar is already visible");
        }, hide: function hide(t) {
          t = e.isFunction(t) ? t : function () {}, (w.is.visible() || w.is.animating()) && (w.debug("Hiding sidebar", t), w.refreshSidebars(), w.pullPage(function () {
            t.call(z), S.onHidden.call(z);
          }), S.onChange.call(z), S.onHide.call(z));
        }, othersAnimating: function othersAnimating() {
          return q.not(O).filter("." + T.animating).length > 0;
        }, othersVisible: function othersVisible() {
          return q.not(O).filter("." + T.visible).length > 0;
        }, othersActive: function othersActive() {
          return w.othersVisible() || w.othersAnimating();
        }, hideOthers: function hideOthers(e) {
          var t = q.not(O).filter("." + T.visible),
              n = t.length,
              i = 0;e = e || function () {}, t.sidebar("hide", function () {
            ++i == n && e();
          });
        }, toggle: function toggle() {
          w.verbose("Determining toggled direction"), w.is.hidden() ? w.show() : w.hide();
        }, pushPage: function pushPage(t) {
          var n,
              i,
              _o,
              a = w.get.transition(),
              r = "overlay" === a || w.othersActive() ? O : j;t = e.isFunction(t) ? t : function () {}, "scale down" == S.transition && w.scrollToTop(), w.set.transition(a), w.repaint(), n = function n() {
            w.bind.clickaway(), w.add.inlineCSS(), w.set.animating(), w.set.visible();
          }, i = function i() {
            w.set.dimmed();
          }, _o = function o(e) {
            e.target == r[0] && (r.off(C + b, _o), w.remove.animating(), w.bind.scrollLock(), t.call(z));
          }, r.off(C + b), r.on(C + b, _o), v(n), S.dimPage && !w.othersVisible() && v(i);
        }, pullPage: function pullPage(t) {
          var n,
              _i,
              o = w.get.transition(),
              a = "overlay" == o || w.othersActive() ? O : j;t = e.isFunction(t) ? t : function () {}, w.verbose("Removing context push state", w.get.direction()), w.unbind.clickaway(), w.unbind.scrollLock(), n = function n() {
            w.set.transition(o), w.set.animating(), w.remove.visible(), S.dimPage && !w.othersVisible() && j.removeClass(T.dimmed);
          }, _i = function i(e) {
            e.target == a[0] && (a.off(C + b, _i), w.remove.animating(), w.remove.transition(), w.remove.inlineCSS(), ("scale down" == o || S.returnScroll && w.is.mobile()) && w.scrollBack(), t.call(z));
          }, a.off(C + b), a.on(C + b, _i), v(n);
        }, scrollToTop: function scrollToTop() {
          w.verbose("Scrolling to top of page to avoid animation issues"), x = e(t).scrollTop(), O.scrollTop(0), t.scrollTo(0, 0);
        }, scrollBack: function scrollBack() {
          w.verbose("Scrolling back to original page position"), t.scrollTo(0, x);
        }, clear: { cache: function cache() {
            w.verbose("Clearing cached dimensions"), w.cache = {};
          } }, set: { ios: function ios() {
            c.addClass(T.ios);
          }, pushed: function pushed() {
            D.addClass(T.pushed);
          }, pushable: function pushable() {
            D.addClass(T.pushable);
          }, dimmed: function dimmed() {
            j.addClass(T.dimmed);
          }, active: function active() {
            O.addClass(T.active);
          }, animating: function animating() {
            O.addClass(T.animating);
          }, transition: function transition(e) {
            e = e || w.get.transition(), O.addClass(e);
          }, direction: function direction(e) {
            e = e || w.get.direction(), O.addClass(T[e]);
          }, visible: function visible() {
            O.addClass(T.visible);
          }, overlay: function overlay() {
            O.addClass(T.overlay);
          } }, remove: { inlineCSS: function inlineCSS() {
            w.debug("Removing inline css styles", r), r && r.length > 0 && r.remove();
          }, ios: function ios() {
            c.removeClass(T.ios);
          }, pushed: function pushed() {
            D.removeClass(T.pushed);
          }, pushable: function pushable() {
            D.removeClass(T.pushable);
          }, active: function active() {
            O.removeClass(T.active);
          }, animating: function animating() {
            O.removeClass(T.animating);
          }, transition: function transition(e) {
            e = e || w.get.transition(), O.removeClass(e);
          }, direction: function direction(e) {
            e = e || w.get.direction(), O.removeClass(T[e]);
          }, visible: function visible() {
            O.removeClass(T.visible);
          }, overlay: function overlay() {
            O.removeClass(T.overlay);
          } }, get: { direction: function direction() {
            return O.hasClass(T.top) ? T.top : O.hasClass(T.right) ? T.right : O.hasClass(T.bottom) ? T.bottom : T.left;
          }, transition: function transition() {
            var e,
                t = w.get.direction();return e = w.is.mobile() ? "auto" == S.mobileTransition ? S.defaultTransition.mobile[t] : S.mobileTransition : "auto" == S.transition ? S.defaultTransition.computer[t] : S.transition, w.verbose("Determined transition", e), e;
          }, transitionEvent: function transitionEvent() {
            var e,
                t = n.createElement("element"),
                o = { transition: "transitionend", OTransition: "oTransitionEnd", MozTransition: "transitionend", WebkitTransition: "webkitTransitionEnd" };for (e in o) {
              if (t.style[e] !== i) return o[e];
            }
          } }, is: { ie: function ie() {
            return !t.ActiveXObject && "ActiveXObject" in t || "ActiveXObject" in t;
          }, ios: function ios() {
            var e = navigator.userAgent,
                t = e.match(R.ios),
                n = e.match(R.mobileChrome);return !(!t || n) && (w.verbose("Browser was found to be iOS", e), !0);
          }, mobile: function mobile() {
            var e = navigator.userAgent;return e.match(R.mobile) ? (w.verbose("Browser was found to be mobile", e), !0) : (w.verbose("Browser is not mobile, using regular transition", e), !1);
          }, hidden: function hidden() {
            return !w.is.visible();
          }, visible: function visible() {
            return O.hasClass(T.visible);
          }, open: function open() {
            return w.is.visible();
          }, closed: function closed() {
            return w.is.hidden();
          }, vertical: function vertical() {
            return O.hasClass(T.top);
          }, animating: function animating() {
            return D.hasClass(T.animating);
          }, rtl: function rtl() {
            return w.cache.rtl === i && (w.cache.rtl = "rtl" == O.css("direction")), w.cache.rtl;
          } }, setting: function setting(t, n) {
          if (w.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, S, t);else {
            if (n === i) return S[t];e.isPlainObject(S[t]) ? e.extend(!0, S[t], n) : S[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, w, t);else {
            if (n === i) return w[t];w[t] = n;
          }
        }, debug: function debug() {
          !S.silent && S.debug && (S.performance ? w.performance.log(arguments) : (w.debug = Function.prototype.bind.call(console.info, console, S.name + ":"), w.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !S.silent && S.verbose && S.debug && (S.performance ? w.performance.log(arguments) : (w.verbose = Function.prototype.bind.call(console.info, console, S.name + ":"), w.verbose.apply(console, arguments)));
        }, error: function error() {
          S.silent || (w.error = Function.prototype.bind.call(console.error, console, S.name + ":"), w.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;S.performance && (n = (t = new Date().getTime()) - (f || t), f = t, m.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: z, "Execution Time": n })), clearTimeout(w.performance.timer), w.performance.timer = setTimeout(w.performance.display, 500);
          }, display: function display() {
            var t = S.name + ":",
                n = 0;f = !1, clearTimeout(w.performance.timer), e.each(m, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", d && (t += " '" + d + "'"), (console.group !== i || console.table !== i) && m.length > 0 && (console.groupCollapsed(t), console.table ? console.table(m) : e.each(m, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), m = [];
          } }, invoke: function invoke(t, n, o) {
          var r,
              s,
              l,
              c = I;return n = n || h, o = z || o, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i ? (s = c[o], !1) : (w.error(P.method, t), !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(o, n) : s !== i && (l = s), e.isArray(a) ? a.push(l) : a !== i ? a = [a, l] : l !== i && (a = l), s;
        } }, p ? (I === i && w.initialize(), w.invoke(g)) : (I !== i && w.invoke("destroy"), w.initialize());
    }), a !== i ? a : this;
  }, e.fn.sidebar.settings = { name: "Sidebar", namespace: "sidebar", silent: !1, debug: !1, verbose: !1, performance: !0, transition: "auto", mobileTransition: "auto", defaultTransition: { computer: { left: "uncover", right: "uncover", top: "overlay", bottom: "overlay" }, mobile: { left: "uncover", right: "uncover", top: "overlay", bottom: "overlay" } }, context: "body", exclusive: !1, closable: !0, dimPage: !0, scrollLock: !1, returnScroll: !1, delaySetup: !1, duration: 500, onChange: function onChange() {}, onShow: function onShow() {}, onHide: function onHide() {}, onHidden: function onHidden() {}, onVisible: function onVisible() {}, className: { active: "active", animating: "animating", dimmed: "dimmed", ios: "ios", pushable: "pushable", pushed: "pushed", right: "right", top: "top", left: "left", bottom: "bottom", visible: "visible" }, selector: { fixed: ".fixed", omitted: "script, link, style, .ui.modal, .ui.dimmer, .ui.nag, .ui.fixed", pusher: ".pusher", sidebar: ".ui.sidebar" }, regExp: { ios: /(iPad|iPhone|iPod)/g, mobileChrome: /(CriOS)/g, mobile: /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/g }, error: { method: "The method you called is not defined.", pusher: "Had to add pusher element. For optimal performance make sure body content is inside a pusher element", movedSidebar: "Had to move sidebar. For optimal performance make sure sidebar and pusher are direct children of your body tag", overlay: "The overlay setting is no longer supported, use animation: overlay", notFound: "There were no elements that matched the specified selector" } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.sticky = function (o) {
    var a,
        r = e(this),
        s = r.selector || "",
        l = new Date().getTime(),
        c = [],
        u = arguments[0],
        d = "string" == typeof u,
        f = [].slice.call(arguments, 1);return r.each(function () {
      var r,
          m,
          g,
          p,
          h,
          v = e.isPlainObject(o) ? e.extend(!0, {}, e.fn.sticky.settings, o) : e.extend({}, e.fn.sticky.settings),
          b = v.className,
          y = v.namespace,
          x = v.error,
          C = "." + y,
          w = "module-" + y,
          S = e(this),
          k = e(t),
          T = e(v.scrollContext),
          A = (S.selector, S.data(w)),
          R = t.requestAnimationFrame || t.mozRequestAnimationFrame || t.webkitRequestAnimationFrame || t.msRequestAnimationFrame || function (e) {
        setTimeout(e, 0);
      },
          P = this;h = { initialize: function initialize() {
          h.determineContainer(), h.determineContext(), h.verbose("Initializing sticky", v, r), h.save.positions(), h.checkErrors(), h.bind.events(), v.observeChanges && h.observeChanges(), h.instantiate();
        }, instantiate: function instantiate() {
          h.verbose("Storing instance of module", h), A = h, S.data(w, h);
        }, destroy: function destroy() {
          h.verbose("Destroying previous instance"), h.reset(), g && g.disconnect(), p && p.disconnect(), k.off("load" + C, h.event.load).off("resize" + C, h.event.resize), T.off("scrollchange" + C, h.event.scrollchange), S.removeData(w);
        }, observeChanges: function observeChanges() {
          "MutationObserver" in t && (g = new MutationObserver(h.event.documentChanged), p = new MutationObserver(h.event.changed), g.observe(n, { childList: !0, subtree: !0 }), p.observe(P, { childList: !0, subtree: !0 }), p.observe(m[0], { childList: !0, subtree: !0 }), h.debug("Setting up mutation observer", p));
        }, determineContainer: function determineContainer() {
          r = v.container ? e(v.container) : S.offsetParent();
        }, determineContext: function determineContext() {
          0 !== (m = v.context ? e(v.context) : r).length || h.error(x.invalidContext, v.context, S);
        }, checkErrors: function checkErrors() {
          if (h.is.hidden() && h.error(x.visible, S), h.cache.element.height > h.cache.context.height) return h.reset(), void h.error(x.elementSize, S);
        }, bind: { events: function events() {
            k.on("load" + C, h.event.load).on("resize" + C, h.event.resize), T.off("scroll" + C).on("scroll" + C, h.event.scroll).on("scrollchange" + C, h.event.scrollchange);
          } }, event: { changed: function changed(e) {
            clearTimeout(h.timer), h.timer = setTimeout(function () {
              h.verbose("DOM tree modified, updating sticky menu", e), h.refresh();
            }, 100);
          }, documentChanged: function documentChanged(t) {
            [].forEach.call(t, function (t) {
              t.removedNodes && [].forEach.call(t.removedNodes, function (t) {
                (t == P || e(t).find(P).length > 0) && (h.debug("Element removed from DOM, tearing down events"), h.destroy());
              });
            });
          }, load: function load() {
            h.verbose("Page contents finished loading"), R(h.refresh);
          }, resize: function resize() {
            h.verbose("Window resized"), R(h.refresh);
          }, scroll: function scroll() {
            R(function () {
              T.triggerHandler("scrollchange" + C, T.scrollTop());
            });
          }, scrollchange: function scrollchange(e, t) {
            h.stick(t), v.onScroll.call(P);
          } }, refresh: function refresh(e) {
          h.reset(), v.context || h.determineContext(), e && h.determineContainer(), h.save.positions(), h.stick(), v.onReposition.call(P);
        }, supports: { sticky: function sticky() {
            var t = e("<div/>");t[0];return t.addClass(b.supported), t.css("position").match("sticky");
          } }, save: { lastScroll: function lastScroll(e) {
            h.lastScroll = e;
          }, elementScroll: function elementScroll(e) {
            h.elementScroll = e;
          }, positions: function positions() {
            var e = { height: T.height() },
                t = { margin: { top: parseInt(S.css("margin-top"), 10), bottom: parseInt(S.css("margin-bottom"), 10) }, offset: S.offset(), width: S.outerWidth(), height: S.outerHeight() },
                n = { offset: m.offset(), height: m.outerHeight() };r.outerHeight();h.is.standardScroll() || (h.debug("Non-standard scroll. Removing scroll offset from element offset"), e.top = T.scrollTop(), e.left = T.scrollLeft(), t.offset.top += e.top, n.offset.top += e.top, t.offset.left += e.left, n.offset.left += e.left), h.cache = { fits: t.height + v.offset <= e.height, sameHeight: t.height == n.height, scrollContext: { height: e.height }, element: { margin: t.margin, top: t.offset.top - t.margin.top, left: t.offset.left, width: t.width, height: t.height, bottom: t.offset.top + t.height }, context: { top: n.offset.top, height: n.height, bottom: n.offset.top + n.height } }, h.set.containerSize(), h.stick(), h.debug("Caching element positions", h.cache);
          } }, get: { direction: function direction(e) {
            var t = "down";return e = e || T.scrollTop(), h.lastScroll !== i && (h.lastScroll < e ? t = "down" : h.lastScroll > e && (t = "up")), t;
          }, scrollChange: function scrollChange(e) {
            return e = e || T.scrollTop(), h.lastScroll ? e - h.lastScroll : 0;
          }, currentElementScroll: function currentElementScroll() {
            return h.elementScroll ? h.elementScroll : h.is.top() ? Math.abs(parseInt(S.css("top"), 10)) || 0 : Math.abs(parseInt(S.css("bottom"), 10)) || 0;
          }, elementScroll: function elementScroll(e) {
            e = e || T.scrollTop();var t = h.cache.element,
                n = h.cache.scrollContext,
                i = h.get.scrollChange(e),
                o = t.height - n.height + v.offset,
                a = h.get.currentElementScroll(),
                r = a + i;return a = h.cache.fits || r < 0 ? 0 : r > o ? o : r;
          } }, remove: { lastScroll: function lastScroll() {
            delete h.lastScroll;
          }, elementScroll: function elementScroll(e) {
            delete h.elementScroll;
          }, minimumSize: function minimumSize() {
            r.css("min-height", "");
          }, offset: function offset() {
            S.css("margin-top", "");
          } }, set: { offset: function offset() {
            h.verbose("Setting offset on element", v.offset), S.css("margin-top", v.offset);
          }, containerSize: function containerSize() {
            var e = r.get(0).tagName;"HTML" === e || "body" == e ? h.determineContainer() : Math.abs(r.outerHeight() - h.cache.context.height) > v.jitter && (h.debug("Context has padding, specifying exact height for container", h.cache.context.height), r.css({ height: h.cache.context.height }));
          }, minimumSize: function minimumSize() {
            var e = h.cache.element;r.css("min-height", e.height);
          }, scroll: function scroll(e) {
            h.debug("Setting scroll on element", e), h.elementScroll != e && (h.is.top() && S.css("bottom", "").css("top", -e), h.is.bottom() && S.css("top", "").css("bottom", e));
          }, size: function size() {
            0 !== h.cache.element.height && 0 !== h.cache.element.width && (P.style.setProperty("width", h.cache.element.width + "px", "important"), P.style.setProperty("height", h.cache.element.height + "px", "important"));
          } }, is: { standardScroll: function standardScroll() {
            return T[0] == t;
          }, top: function top() {
            return S.hasClass(b.top);
          }, bottom: function bottom() {
            return S.hasClass(b.bottom);
          }, initialPosition: function initialPosition() {
            return !h.is.fixed() && !h.is.bound();
          }, hidden: function hidden() {
            return !S.is(":visible");
          }, bound: function bound() {
            return S.hasClass(b.bound);
          }, fixed: function fixed() {
            return S.hasClass(b.fixed);
          } }, stick: function stick(e) {
          var t = e || T.scrollTop(),
              n = h.cache,
              i = n.fits,
              o = n.sameHeight,
              a = n.element,
              r = n.scrollContext,
              s = n.context,
              l = h.is.bottom() && v.pushing ? v.bottomOffset : v.offset,
              c = (e = { top: t + l, bottom: t + l + r.height }, h.get.direction(e.top), i ? 0 : h.get.elementScroll(e.top)),
              u = !i;0 !== a.height && !o && (h.is.initialPosition() ? e.top >= s.bottom ? (h.debug("Initial element position is bottom of container"), h.bindBottom()) : e.top > a.top && (a.height + e.top - c >= s.bottom ? (h.debug("Initial element position is bottom of container"), h.bindBottom()) : (h.debug("Initial element position is fixed"), h.fixTop())) : h.is.fixed() ? h.is.top() ? e.top <= a.top ? (h.debug("Fixed element reached top of container"), h.setInitialPosition()) : a.height + e.top - c >= s.bottom ? (h.debug("Fixed element reached bottom of container"), h.bindBottom()) : u && (h.set.scroll(c), h.save.lastScroll(e.top), h.save.elementScroll(c)) : h.is.bottom() && (e.bottom - a.height <= a.top ? (h.debug("Bottom fixed rail has reached top of container"), h.setInitialPosition()) : e.bottom >= s.bottom ? (h.debug("Bottom fixed rail has reached bottom of container"), h.bindBottom()) : u && (h.set.scroll(c), h.save.lastScroll(e.top), h.save.elementScroll(c))) : h.is.bottom() && (e.top <= a.top ? (h.debug("Jumped from bottom fixed to top fixed, most likely used home/end button"), h.setInitialPosition()) : v.pushing ? h.is.bound() && e.bottom <= s.bottom && (h.debug("Fixing bottom attached element to bottom of browser."), h.fixBottom()) : h.is.bound() && e.top <= s.bottom - a.height && (h.debug("Fixing bottom attached element to top of browser."), h.fixTop())));
        }, bindTop: function bindTop() {
          h.debug("Binding element to top of parent container"), h.remove.offset(), S.css({ left: "", top: "", marginBottom: "" }).removeClass(b.fixed).removeClass(b.bottom).addClass(b.bound).addClass(b.top), v.onTop.call(P), v.onUnstick.call(P);
        }, bindBottom: function bindBottom() {
          h.debug("Binding element to bottom of parent container"), h.remove.offset(), S.css({ left: "", top: "" }).removeClass(b.fixed).removeClass(b.top).addClass(b.bound).addClass(b.bottom), v.onBottom.call(P), v.onUnstick.call(P);
        }, setInitialPosition: function setInitialPosition() {
          h.debug("Returning to initial position"), h.unfix(), h.unbind();
        }, fixTop: function fixTop() {
          h.debug("Fixing element to top of page"), v.setSize && h.set.size(), h.set.minimumSize(), h.set.offset(), S.css({ left: h.cache.element.left, bottom: "", marginBottom: "" }).removeClass(b.bound).removeClass(b.bottom).addClass(b.fixed).addClass(b.top), v.onStick.call(P);
        }, fixBottom: function fixBottom() {
          h.debug("Sticking element to bottom of page"), v.setSize && h.set.size(), h.set.minimumSize(), h.set.offset(), S.css({ left: h.cache.element.left, bottom: "", marginBottom: "" }).removeClass(b.bound).removeClass(b.top).addClass(b.fixed).addClass(b.bottom), v.onStick.call(P);
        }, unbind: function unbind() {
          h.is.bound() && (h.debug("Removing container bound position on element"), h.remove.offset(), S.removeClass(b.bound).removeClass(b.top).removeClass(b.bottom));
        }, unfix: function unfix() {
          h.is.fixed() && (h.debug("Removing fixed position on element"), h.remove.minimumSize(), h.remove.offset(), S.removeClass(b.fixed).removeClass(b.top).removeClass(b.bottom), v.onUnstick.call(P));
        }, reset: function reset() {
          h.debug("Resetting elements position"), h.unbind(), h.unfix(), h.resetCSS(), h.remove.offset(), h.remove.lastScroll();
        }, resetCSS: function resetCSS() {
          S.css({ width: "", height: "" }), r.css({ height: "" });
        }, setting: function setting(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, v, t);else {
            if (n === i) return v[t];v[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, h, t);else {
            if (n === i) return h[t];h[t] = n;
          }
        }, debug: function debug() {
          !v.silent && v.debug && (v.performance ? h.performance.log(arguments) : (h.debug = Function.prototype.bind.call(console.info, console, v.name + ":"), h.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !v.silent && v.verbose && v.debug && (v.performance ? h.performance.log(arguments) : (h.verbose = Function.prototype.bind.call(console.info, console, v.name + ":"), h.verbose.apply(console, arguments)));
        }, error: function error() {
          v.silent || (h.error = Function.prototype.bind.call(console.error, console, v.name + ":"), h.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;v.performance && (n = (t = new Date().getTime()) - (l || t), l = t, c.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: P, "Execution Time": n })), clearTimeout(h.performance.timer), h.performance.timer = setTimeout(h.performance.display, 0);
          }, display: function display() {
            var t = v.name + ":",
                n = 0;l = !1, clearTimeout(h.performance.timer), e.each(c, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", s && (t += " '" + s + "'"), (console.group !== i || console.table !== i) && c.length > 0 && (console.groupCollapsed(t), console.table ? console.table(c) : e.each(c, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), c = [];
          } }, invoke: function invoke(t, n, o) {
          var r,
              s,
              l,
              c = A;return n = n || f, o = P || o, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i && (s = c[o], !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(o, n) : s !== i && (l = s), e.isArray(a) ? a.push(l) : a !== i ? a = [a, l] : l !== i && (a = l), s;
        } }, d ? (A === i && h.initialize(), h.invoke(u)) : (A !== i && A.invoke("destroy"), h.initialize());
    }), a !== i ? a : this;
  }, e.fn.sticky.settings = { name: "Sticky", namespace: "sticky", silent: !1, debug: !1, verbose: !0, performance: !0, pushing: !1, context: !1, container: !1, scrollContext: t, offset: 0, bottomOffset: 0, jitter: 5, setSize: !0, observeChanges: !1, onReposition: function onReposition() {}, onScroll: function onScroll() {}, onStick: function onStick() {}, onUnstick: function onUnstick() {}, onTop: function onTop() {}, onBottom: function onBottom() {}, error: { container: "Sticky element must be inside a relative container", visible: "Element is hidden, you must call refresh after element becomes visible. Use silent setting to surpress this warning in production.", method: "The method you called is not defined.", invalidContext: "Context specified does not exist", elementSize: "Sticky element is larger than its container, cannot create sticky." }, className: { bound: "bound", fixed: "fixed", supported: "native", top: "top", bottom: "bottom" } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.tab = function (o) {
    var a,
        r = e.isFunction(this) ? e(t) : e(this),
        s = r.selector || "",
        l = new Date().getTime(),
        c = [],
        u = arguments[0],
        d = "string" == typeof u,
        f = [].slice.call(arguments, 1),
        m = !1;return r.each(function () {
      var g,
          p,
          h,
          v,
          b,
          y,
          x = e.isPlainObject(o) ? e.extend(!0, {}, e.fn.tab.settings, o) : e.extend({}, e.fn.tab.settings),
          C = x.className,
          w = x.metadata,
          S = x.selector,
          k = x.error,
          T = "." + x.namespace,
          A = "module-" + x.namespace,
          R = e(this),
          P = {},
          E = !0,
          F = 0,
          O = this,
          D = R.data(A);b = { initialize: function initialize() {
          b.debug("Initializing tab menu item", R), b.fix.callbacks(), b.determineTabs(), b.debug("Determining tabs", x.context, p), x.auto && b.set.auto(), b.bind.events(), x.history && !m && (b.initializeHistory(), m = !0), b.instantiate();
        }, instantiate: function instantiate() {
          b.verbose("Storing instance of module", b), D = b, R.data(A, b);
        }, destroy: function destroy() {
          b.debug("Destroying tabs", R), R.removeData(A).off(T);
        }, bind: { events: function events() {
            e.isWindow(O) || (b.debug("Attaching tab activation events to element", R), R.on("click" + T, b.event.click));
          } }, determineTabs: function determineTabs() {
          var t;"parent" === x.context ? (R.closest(S.ui).length > 0 ? (t = R.closest(S.ui), b.verbose("Using closest UI element as parent", t)) : t = R, g = t.parent(), b.verbose("Determined parent element for creating context", g)) : x.context ? (g = e(x.context), b.verbose("Using selector for tab context", x.context, g)) : g = e("body"), x.childrenOnly ? (p = g.children(S.tabs), b.debug("Searching tab context children for tabs", g, p)) : (p = g.find(S.tabs), b.debug("Searching tab context for tabs", g, p));
        }, fix: { callbacks: function callbacks() {
            e.isPlainObject(o) && (o.onTabLoad || o.onTabInit) && (o.onTabLoad && (o.onLoad = o.onTabLoad, delete o.onTabLoad, b.error(k.legacyLoad, o.onLoad)), o.onTabInit && (o.onFirstLoad = o.onTabInit, delete o.onTabInit, b.error(k.legacyInit, o.onFirstLoad)), x = e.extend(!0, {}, e.fn.tab.settings, o));
          } }, initializeHistory: function initializeHistory() {
          if (b.debug("Initializing page state"), e.address === i) return b.error(k.state), !1;if ("state" == x.historyType) {
            if (b.debug("Using HTML5 to manage state"), !1 === x.path) return b.error(k.path), !1;e.address.history(!0).state(x.path);
          }e.address.bind("change", b.event.history.change);
        }, event: { click: function click(t) {
            var n = e(this).data(w.tab);n !== i ? (x.history ? (b.verbose("Updating page state", t), e.address.value(n)) : (b.verbose("Changing tab", t), b.changeTab(n)), t.preventDefault()) : b.debug("No tab specified");
          }, history: { change: function change(t) {
              var n = t.pathNames.join("/") || b.get.initialPath(),
                  o = x.templates.determineTitle(n) || !1;b.performance.display(), b.debug("History change event", n, t), y = t, n !== i && b.changeTab(n), o && e.address.title(o);
            } } }, refresh: function refresh() {
          h && (b.debug("Refreshing tab", h), b.changeTab(h));
        }, cache: { read: function read(e) {
            return e !== i && P[e];
          }, add: function add(e, t) {
            e = e || h, b.debug("Adding cached content for", e), P[e] = t;
          }, remove: function remove(e) {
            e = e || h, b.debug("Removing cached content for", e), delete P[e];
          } }, set: { auto: function auto() {
            var t = "string" == typeof x.path ? x.path.replace(/\/$/, "") + "/{$tab}" : "/{$tab}";b.verbose("Setting up automatic tab retrieval from server", t), e.isPlainObject(x.apiSettings) ? x.apiSettings.url = t : x.apiSettings = { url: t };
          }, loading: function loading(e) {
            var t = b.get.tabElement(e);t.hasClass(C.loading) || (b.verbose("Setting loading state for", t), t.addClass(C.loading).siblings(p).removeClass(C.active + " " + C.loading), t.length > 0 && x.onRequest.call(t[0], e));
          }, state: function state(t) {
            e.address.value(t);
          } }, changeTab: function changeTab(n) {
          var i = t.history && t.history.pushState && x.ignoreFirstLoad && E,
              o = x.auto || e.isPlainObject(x.apiSettings),
              a = o && !i ? b.utilities.pathToArray(n) : b.get.defaultPathArray(n);n = b.utilities.arrayToPath(a), e.each(a, function (t, r) {
            var s,
                l,
                c,
                u,
                d = a.slice(0, t + 1),
                f = b.utilities.arrayToPath(d),
                m = b.is.tab(f),
                p = t + 1 == a.length,
                S = b.get.tabElement(f);if (b.verbose("Looking for tab", r), m) {
              if (b.verbose("Tab was found", r), h = f, v = b.utilities.filterArray(a, d), p ? u = !0 : (l = a.slice(0, t + 2), c = b.utilities.arrayToPath(l), (u = !b.is.tab(c)) && b.verbose("Tab parameters found", l)), u && o) return i ? (b.debug("Ignoring remote content on first tab load", f), E = !1, b.cache.add(n, S.html()), b.activate.all(f), x.onFirstLoad.call(S[0], f, v, y), x.onLoad.call(S[0], f, v, y)) : (b.activate.navigation(f), b.fetch.content(f, n)), !1;b.debug("Opened local tab", f), b.activate.all(f), b.cache.read(f) || (b.cache.add(f, !0), b.debug("First time tab loaded calling tab init"), x.onFirstLoad.call(S[0], f, v, y)), x.onLoad.call(S[0], f, v, y);
            } else {
              if (-1 != n.search("/") || "" === n) return b.error(k.missingTab, R, g, f), !1;if (f = (s = e("#" + n + ', a[name="' + n + '"]')).closest("[data-tab]").data(w.tab), S = b.get.tabElement(f), s && s.length > 0 && f) return b.debug("Anchor link used, opening parent tab", S, s), S.hasClass(C.active) || setTimeout(function () {
                b.scrollTo(s);
              }, 0), b.activate.all(f), b.cache.read(f) || (b.cache.add(f, !0), b.debug("First time tab loaded calling tab init"), x.onFirstLoad.call(S[0], f, v, y)), x.onLoad.call(S[0], f, v, y), !1;
            }
          });
        }, scrollTo: function scrollTo(t) {
          var i = !!(t && t.length > 0) && t.offset().top;!1 !== i && (b.debug("Forcing scroll to an in-page link in a hidden tab", i, t), e(n).scrollTop(i));
        }, update: { content: function content(t, n, o) {
            var a = b.get.tabElement(t),
                r = a[0];o = o !== i ? o : x.evaluateScripts, "string" == typeof x.cacheType && "dom" == x.cacheType.toLowerCase() && "string" != typeof n ? a.empty().append(e(n).clone(!0)) : o ? (b.debug("Updating HTML and evaluating inline scripts", t, n), a.html(n)) : (b.debug("Updating HTML", t, n), r.innerHTML = n);
          } }, fetch: { content: function content(t, n) {
            var o,
                a,
                r = b.get.tabElement(t),
                s = { dataType: "html", encodeParameters: !1, on: "now", cache: x.alwaysRefresh, headers: { "X-Remote": !0 }, onSuccess: function onSuccess(e) {
                "response" == x.cacheType && b.cache.add(n, e), b.update.content(t, e), t == h ? (b.debug("Content loaded", t), b.activate.tab(t)) : b.debug("Content loaded in background", t), x.onFirstLoad.call(r[0], t, v, y), x.onLoad.call(r[0], t, v, y), x.loadOnce ? b.cache.add(n, !0) : "string" == typeof x.cacheType && "dom" == x.cacheType.toLowerCase() && r.children().length > 0 ? setTimeout(function () {
                  var e = r.children().clone(!0);e = e.not("script"), b.cache.add(n, e);
                }, 0) : b.cache.add(n, r.html());
              }, urlData: { tab: n } },
                l = r.api("get request") || !1,
                c = l && "pending" === l.state();n = n || t, a = b.cache.read(n), x.cache && a ? (b.activate.tab(t), b.debug("Adding cached content", n), x.loadOnce || ("once" == x.evaluateScripts ? b.update.content(t, a, !1) : b.update.content(t, a)), x.onLoad.call(r[0], t, v, y)) : c ? (b.set.loading(t), b.debug("Content is already loading", n)) : e.api !== i ? (o = e.extend(!0, {}, x.apiSettings, s), b.debug("Retrieving remote content", n, o), b.set.loading(t), r.api(o)) : b.error(k.api);
          } }, activate: { all: function all(e) {
            b.activate.tab(e), b.activate.navigation(e);
          }, tab: function tab(e) {
            var t = b.get.tabElement(e),
                n = "siblings" == x.deactivate ? t.siblings(p) : p.not(t),
                i = t.hasClass(C.active);b.verbose("Showing tab content for", t), i || (t.addClass(C.active), n.removeClass(C.active + " " + C.loading), t.length > 0 && x.onVisible.call(t[0], e));
          }, navigation: function navigation(e) {
            var t = b.get.navElement(e),
                n = "siblings" == x.deactivate ? t.siblings(r) : r.not(t),
                i = t.hasClass(C.active);b.verbose("Activating tab navigation for", t, e), i || (t.addClass(C.active), n.removeClass(C.active + " " + C.loading));
          } }, deactivate: { all: function all() {
            b.deactivate.navigation(), b.deactivate.tabs();
          }, navigation: function navigation() {
            r.removeClass(C.active);
          }, tabs: function tabs() {
            p.removeClass(C.active + " " + C.loading);
          } }, is: { tab: function tab(e) {
            return e !== i && b.get.tabElement(e).length > 0;
          } }, get: { initialPath: function initialPath() {
            return r.eq(0).data(w.tab) || p.eq(0).data(w.tab);
          }, path: function path() {
            return e.address.value();
          }, defaultPathArray: function defaultPathArray(e) {
            return b.utilities.pathToArray(b.get.defaultPath(e));
          }, defaultPath: function defaultPath(e) {
            var t = r.filter("[data-" + w.tab + '^="' + e + '/"]').eq(0).data(w.tab) || !1;if (t) {
              if (b.debug("Found default tab", t), F < x.maxDepth) return F++, b.get.defaultPath(t);b.error(k.recursion);
            } else b.debug("No default tabs found for", e, p);return F = 0, e;
          }, navElement: function navElement(e) {
            return e = e || h, r.filter("[data-" + w.tab + '="' + e + '"]');
          }, tabElement: function tabElement(e) {
            var t, n, i, o;return e = e || h, i = b.utilities.pathToArray(e), o = b.utilities.last(i), t = p.filter("[data-" + w.tab + '="' + e + '"]'), n = p.filter("[data-" + w.tab + '="' + o + '"]'), t.length > 0 ? t : n;
          }, tab: function tab() {
            return h;
          } }, utilities: { filterArray: function filterArray(t, n) {
            return e.grep(t, function (t) {
              return -1 == e.inArray(t, n);
            });
          }, last: function last(t) {
            return !!e.isArray(t) && t[t.length - 1];
          }, pathToArray: function pathToArray(e) {
            return e === i && (e = h), "string" == typeof e ? e.split("/") : [e];
          }, arrayToPath: function arrayToPath(t) {
            return !!e.isArray(t) && t.join("/");
          } }, setting: function setting(t, n) {
          if (b.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, x, t);else {
            if (n === i) return x[t];e.isPlainObject(x[t]) ? e.extend(!0, x[t], n) : x[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, b, t);else {
            if (n === i) return b[t];b[t] = n;
          }
        }, debug: function debug() {
          !x.silent && x.debug && (x.performance ? b.performance.log(arguments) : (b.debug = Function.prototype.bind.call(console.info, console, x.name + ":"), b.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !x.silent && x.verbose && x.debug && (x.performance ? b.performance.log(arguments) : (b.verbose = Function.prototype.bind.call(console.info, console, x.name + ":"), b.verbose.apply(console, arguments)));
        }, error: function error() {
          x.silent || (b.error = Function.prototype.bind.call(console.error, console, x.name + ":"), b.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;x.performance && (n = (t = new Date().getTime()) - (l || t), l = t, c.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: O, "Execution Time": n })), clearTimeout(b.performance.timer), b.performance.timer = setTimeout(b.performance.display, 500);
          }, display: function display() {
            var t = x.name + ":",
                n = 0;l = !1, clearTimeout(b.performance.timer), e.each(c, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", s && (t += " '" + s + "'"), (console.group !== i || console.table !== i) && c.length > 0 && (console.groupCollapsed(t), console.table ? console.table(c) : e.each(c, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), c = [];
          } }, invoke: function invoke(t, n, o) {
          var r,
              s,
              l,
              c = D;return n = n || f, o = O || o, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i ? (s = c[o], !1) : (b.error(k.method, t), !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(o, n) : s !== i && (l = s), e.isArray(a) ? a.push(l) : a !== i ? a = [a, l] : l !== i && (a = l), s;
        } }, d ? (D === i && b.initialize(), b.invoke(u)) : (D !== i && D.invoke("destroy"), b.initialize());
    }), a !== i ? a : this;
  }, e.tab = function () {
    e(t).tab.apply(this, arguments);
  }, e.fn.tab.settings = { name: "Tab", namespace: "tab", silent: !1, debug: !1, verbose: !1, performance: !0, auto: !1, history: !1, historyType: "hash", path: !1, context: !1, childrenOnly: !1, maxDepth: 25, deactivate: "siblings", alwaysRefresh: !1, cache: !0, loadOnce: !1, cacheType: "response", ignoreFirstLoad: !1, apiSettings: !1, evaluateScripts: "once", onFirstLoad: function onFirstLoad(e, t, n) {}, onLoad: function onLoad(e, t, n) {}, onVisible: function onVisible(e, t, n) {}, onRequest: function onRequest(e, t, n) {}, templates: { determineTitle: function determineTitle(e) {} }, error: { api: "You attempted to load content without API module", method: "The method you called is not defined", missingTab: "Activated tab cannot be found. Tabs are case-sensitive.", noContent: "The tab you specified is missing a content url.", path: "History enabled, but no path was specified", recursion: "Max recursive depth reached", legacyInit: "onTabInit has been renamed to onFirstLoad in 2.0, please adjust your code.", legacyLoad: "onTabLoad has been renamed to onLoad in 2.0. Please adjust your code", state: "History requires Asual's Address library <https://github.com/asual/jquery-address>" }, metadata: { tab: "tab", loaded: "loaded", promise: "promise" }, className: { loading: "loading", active: "active" }, selector: { tabs: ".ui.tab", ui: ".ui" } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.transition = function () {
    var o,
        a = e(this),
        r = a.selector || "",
        s = new Date().getTime(),
        l = [],
        c = arguments,
        u = c[0],
        d = [].slice.call(arguments, 1),
        f = "string" == typeof u;t.requestAnimationFrame || t.mozRequestAnimationFrame || t.webkitRequestAnimationFrame || t.msRequestAnimationFrame;return a.each(function (t) {
      var m,
          g,
          p,
          h,
          v,
          b,
          y,
          x,
          C,
          w = e(this),
          S = this;(C = { initialize: function initialize() {
          m = C.get.settings.apply(S, c), h = m.className, p = m.error, v = m.metadata, x = "." + m.namespace, y = "module-" + m.namespace, g = w.data(y) || C, b = C.get.animationEndEvent(), f && (f = C.invoke(u)), !1 === f && (C.verbose("Converted arguments into settings object", m), m.interval ? C.delay(m.animate) : C.animate(), C.instantiate());
        }, instantiate: function instantiate() {
          C.verbose("Storing instance of module", C), g = C, w.data(y, g);
        }, destroy: function destroy() {
          C.verbose("Destroying previous module for", S), w.removeData(y);
        }, refresh: function refresh() {
          C.verbose("Refreshing display type on next animation"), delete C.displayType;
        }, forceRepaint: function forceRepaint() {
          C.verbose("Forcing element repaint");var e = w.parent(),
              t = w.next();0 === t.length ? w.detach().appendTo(e) : w.detach().insertBefore(t);
        }, repaint: function repaint() {
          C.verbose("Repainting element");S.offsetWidth;
        }, delay: function delay(e) {
          var n,
              o = C.get.animationDirection();o || (o = C.can.transition() ? C.get.direction() : "static"), e = e !== i ? e : m.interval, n = "auto" == m.reverse && o == h.outward || 1 == m.reverse ? (a.length - t) * m.interval : t * m.interval, C.debug("Delaying animation by", n), setTimeout(C.animate, n);
        }, animate: function animate(e) {
          if (m = e || m, !C.is.supported()) return C.error(p.support), !1;if (C.debug("Preparing animation", m.animation), C.is.animating()) {
            if (m.queue) return !m.allowRepeats && C.has.direction() && C.is.occurring() && !0 !== C.queuing ? C.debug("Animation is currently occurring, preventing queueing same animation", m.animation) : C.queue(m.animation), !1;if (!m.allowRepeats && C.is.occurring()) return C.debug("Animation is already occurring, will not execute repeated animation", m.animation), !1;C.debug("New animation started, completing previous early", m.animation), g.complete();
          }C.can.animate() ? C.set.animating(m.animation) : C.error(p.noAnimation, m.animation, S);
        }, reset: function reset() {
          C.debug("Resetting animation to beginning conditions"), C.remove.animationCallbacks(), C.restore.conditions(), C.remove.animating();
        }, queue: function queue(e) {
          C.debug("Queueing animation of", e), C.queuing = !0, w.one(b + ".queue" + x, function () {
            C.queuing = !1, C.repaint(), C.animate.apply(this, m);
          });
        }, complete: function complete(e) {
          C.debug("Animation complete", m.animation), C.remove.completeCallback(), C.remove.failSafe(), C.is.looping() || (C.is.outward() ? (C.verbose("Animation is outward, hiding element"), C.restore.conditions(), C.hide()) : C.is.inward() ? (C.verbose("Animation is outward, showing element"), C.restore.conditions(), C.show()) : (C.verbose("Static animation completed"), C.restore.conditions(), m.onComplete.call(S)));
        }, force: { visible: function visible() {
            var e = w.attr("style"),
                t = C.get.userStyle(),
                n = C.get.displayType(),
                o = t + "display: " + n + " !important;",
                a = w.css("display"),
                r = e === i || "" === e;a !== n ? (C.verbose("Overriding default display to show element", n), w.attr("style", o)) : r && w.removeAttr("style");
          }, hidden: function hidden() {
            var e = w.attr("style"),
                t = w.css("display"),
                n = e === i || "" === e;"none" === t || C.is.hidden() ? n && w.removeAttr("style") : (C.verbose("Overriding default display to hide element"), w.css("display", "none"));
          } }, has: { direction: function direction(t) {
            var n = !1;return "string" == typeof (t = t || m.animation) && (t = t.split(" "), e.each(t, function (e, t) {
              t !== h.inward && t !== h.outward || (n = !0);
            })), n;
          }, inlineDisplay: function inlineDisplay() {
            var t = w.attr("style") || "";return e.isArray(t.match(/display.*?;/, ""));
          } }, set: { animating: function animating(e) {
            var t;C.remove.completeCallback(), e = e || m.animation, t = C.get.animationClass(e), C.save.animation(t), C.force.visible(), C.remove.hidden(), C.remove.direction(), C.start.animation(t);
          }, duration: function duration(e, t) {
            ((t = "number" == typeof (t = t || m.duration) ? t + "ms" : t) || 0 === t) && (C.verbose("Setting animation duration", t), w.css({ "animation-duration": t }));
          }, direction: function direction(e) {
            (e = e || C.get.direction()) == h.inward ? C.set.inward() : C.set.outward();
          }, looping: function looping() {
            C.debug("Transition set to loop"), w.addClass(h.looping);
          }, hidden: function hidden() {
            w.addClass(h.transition).addClass(h.hidden);
          }, inward: function inward() {
            C.debug("Setting direction to inward"), w.removeClass(h.outward).addClass(h.inward);
          }, outward: function outward() {
            C.debug("Setting direction to outward"), w.removeClass(h.inward).addClass(h.outward);
          }, visible: function visible() {
            w.addClass(h.transition).addClass(h.visible);
          } }, start: { animation: function animation(e) {
            e = e || C.get.animationClass(), C.debug("Starting tween", e), w.addClass(e).one(b + ".complete" + x, C.complete), m.useFailSafe && C.add.failSafe(), C.set.duration(m.duration), m.onStart.call(S);
          } }, save: { animation: function animation(e) {
            C.cache || (C.cache = {}), C.cache.animation = e;
          }, displayType: function displayType(e) {
            "none" !== e && w.data(v.displayType, e);
          }, transitionExists: function transitionExists(t, n) {
            e.fn.transition.exists[t] = n, C.verbose("Saving existence of transition", t, n);
          } }, restore: { conditions: function conditions() {
            var e = C.get.currentAnimation();e && (w.removeClass(e), C.verbose("Removing animation class", C.cache)), C.remove.duration();
          } }, add: { failSafe: function failSafe() {
            var e = C.get.duration();C.timer = setTimeout(function () {
              w.triggerHandler(b);
            }, e + m.failSafeDelay), C.verbose("Adding fail safe timer", C.timer);
          } }, remove: { animating: function animating() {
            w.removeClass(h.animating);
          }, animationCallbacks: function animationCallbacks() {
            C.remove.queueCallback(), C.remove.completeCallback();
          }, queueCallback: function queueCallback() {
            w.off(".queue" + x);
          }, completeCallback: function completeCallback() {
            w.off(".complete" + x);
          }, display: function display() {
            w.css("display", "");
          }, direction: function direction() {
            w.removeClass(h.inward).removeClass(h.outward);
          }, duration: function duration() {
            w.css("animation-duration", "");
          }, failSafe: function failSafe() {
            C.verbose("Removing fail safe timer", C.timer), C.timer && clearTimeout(C.timer);
          }, hidden: function hidden() {
            w.removeClass(h.hidden);
          }, visible: function visible() {
            w.removeClass(h.visible);
          }, looping: function looping() {
            C.debug("Transitions are no longer looping"), C.is.looping() && (C.reset(), w.removeClass(h.looping));
          }, transition: function transition() {
            w.removeClass(h.visible).removeClass(h.hidden);
          } }, get: { settings: function settings(t, n, i) {
            return "object" == (typeof t === "undefined" ? "undefined" : _typeof(t)) ? e.extend(!0, {}, e.fn.transition.settings, t) : "function" == typeof i ? e.extend({}, e.fn.transition.settings, { animation: t, onComplete: i, duration: n }) : "string" == typeof n || "number" == typeof n ? e.extend({}, e.fn.transition.settings, { animation: t, duration: n }) : "object" == (typeof n === "undefined" ? "undefined" : _typeof(n)) ? e.extend({}, e.fn.transition.settings, n, { animation: t }) : "function" == typeof n ? e.extend({}, e.fn.transition.settings, { animation: t, onComplete: n }) : e.extend({}, e.fn.transition.settings, { animation: t });
          }, animationClass: function animationClass(e) {
            var t = e || m.animation,
                n = C.can.transition() && !C.has.direction() ? C.get.direction() + " " : "";return h.animating + " " + h.transition + " " + n + t;
          }, currentAnimation: function currentAnimation() {
            return !(!C.cache || C.cache.animation === i) && C.cache.animation;
          }, currentDirection: function currentDirection() {
            return C.is.inward() ? h.inward : h.outward;
          }, direction: function direction() {
            return C.is.hidden() || !C.is.visible() ? h.inward : h.outward;
          }, animationDirection: function animationDirection(t) {
            var n;return "string" == typeof (t = t || m.animation) && (t = t.split(" "), e.each(t, function (e, t) {
              t === h.inward ? n = h.inward : t === h.outward && (n = h.outward);
            })), n || !1;
          }, duration: function duration(e) {
            return !1 === (e = e || m.duration) && (e = w.css("animation-duration") || 0), "string" == typeof e ? e.indexOf("ms") > -1 ? parseFloat(e) : 1e3 * parseFloat(e) : e;
          }, displayType: function displayType(e) {
            return e = e === i || e, m.displayType ? m.displayType : (e && w.data(v.displayType) === i && C.can.transition(!0), w.data(v.displayType));
          }, userStyle: function userStyle(e) {
            return (e = e || w.attr("style") || "").replace(/display.*?;/, "");
          }, transitionExists: function transitionExists(t) {
            return e.fn.transition.exists[t];
          }, animationStartEvent: function animationStartEvent() {
            var e,
                t = n.createElement("div"),
                o = { animation: "animationstart", OAnimation: "oAnimationStart", MozAnimation: "mozAnimationStart", WebkitAnimation: "webkitAnimationStart" };for (e in o) {
              if (t.style[e] !== i) return o[e];
            }return !1;
          }, animationEndEvent: function animationEndEvent() {
            var e,
                t = n.createElement("div"),
                o = { animation: "animationend", OAnimation: "oAnimationEnd", MozAnimation: "mozAnimationEnd", WebkitAnimation: "webkitAnimationEnd" };for (e in o) {
              if (t.style[e] !== i) return o[e];
            }return !1;
          } }, can: { transition: function transition(t) {
            var n,
                o,
                a,
                r,
                s,
                l,
                c = m.animation,
                u = C.get.transitionExists(c),
                d = C.get.displayType(!1);if (u === i || t) {
              if (C.verbose("Determining whether animation exists"), n = w.attr("class"), o = w.prop("tagName"), r = (a = e("<" + o + " />").addClass(n).insertAfter(w)).addClass(c).removeClass(h.inward).removeClass(h.outward).addClass(h.animating).addClass(h.transition).css("animationName"), s = a.addClass(h.inward).css("animationName"), d || (d = a.attr("class", n).removeAttr("style").removeClass(h.hidden).removeClass(h.visible).show().css("display"), C.verbose("Determining final display state", d), C.save.displayType(d)), a.remove(), r != s) C.debug("Direction exists for animation", c), l = !0;else {
                if ("none" == r || !r) return void C.debug("No animation defined in css", c);C.debug("Static animation found", c, d), l = !1;
              }C.save.transitionExists(c, l);
            }return u !== i ? u : l;
          }, animate: function animate() {
            return C.can.transition() !== i;
          } }, is: { animating: function animating() {
            return w.hasClass(h.animating);
          }, inward: function inward() {
            return w.hasClass(h.inward);
          }, outward: function outward() {
            return w.hasClass(h.outward);
          }, looping: function looping() {
            return w.hasClass(h.looping);
          }, occurring: function occurring(e) {
            return e = "." + (e = e || m.animation).replace(" ", "."), w.filter(e).length > 0;
          }, visible: function visible() {
            return w.is(":visible");
          }, hidden: function hidden() {
            return "hidden" === w.css("visibility");
          }, supported: function supported() {
            return !1 !== b;
          } }, hide: function hide() {
          C.verbose("Hiding element"), C.is.animating() && C.reset(), S.blur(), C.remove.display(), C.remove.visible(), C.set.hidden(), C.force.hidden(), m.onHide.call(S), m.onComplete.call(S);
        }, show: function show(e) {
          C.verbose("Showing element", e), C.remove.hidden(), C.set.visible(), C.force.visible(), m.onShow.call(S), m.onComplete.call(S);
        }, toggle: function toggle() {
          C.is.visible() ? C.hide() : C.show();
        }, stop: function stop() {
          C.debug("Stopping current animation"), w.triggerHandler(b);
        }, stopAll: function stopAll() {
          C.debug("Stopping all animation"), C.remove.queueCallback(), w.triggerHandler(b);
        }, clear: { queue: function queue() {
            C.debug("Clearing animation queue"), C.remove.queueCallback();
          } }, enable: function enable() {
          C.verbose("Starting animation"), w.removeClass(h.disabled);
        }, disable: function disable() {
          C.debug("Stopping animation"), w.addClass(h.disabled);
        }, setting: function setting(t, n) {
          if (C.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, m, t);else {
            if (n === i) return m[t];e.isPlainObject(m[t]) ? e.extend(!0, m[t], n) : m[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, C, t);else {
            if (n === i) return C[t];C[t] = n;
          }
        }, debug: function debug() {
          !m.silent && m.debug && (m.performance ? C.performance.log(arguments) : (C.debug = Function.prototype.bind.call(console.info, console, m.name + ":"), C.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !m.silent && m.verbose && m.debug && (m.performance ? C.performance.log(arguments) : (C.verbose = Function.prototype.bind.call(console.info, console, m.name + ":"), C.verbose.apply(console, arguments)));
        }, error: function error() {
          m.silent || (C.error = Function.prototype.bind.call(console.error, console, m.name + ":"), C.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;m.performance && (n = (t = new Date().getTime()) - (s || t), s = t, l.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: S, "Execution Time": n })), clearTimeout(C.performance.timer), C.performance.timer = setTimeout(C.performance.display, 500);
          }, display: function display() {
            var t = m.name + ":",
                n = 0;s = !1, clearTimeout(C.performance.timer), e.each(l, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", r && (t += " '" + r + "'"), a.length > 1 && (t += " (" + a.length + ")"), (console.group !== i || console.table !== i) && l.length > 0 && (console.groupCollapsed(t), console.table ? console.table(l) : e.each(l, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), l = [];
          } }, invoke: function invoke(t, n, a) {
          var r,
              s,
              l,
              c = g;return n = n || d, a = S || a, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i && (s = c[o], !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(a, n) : s !== i && (l = s), e.isArray(o) ? o.push(l) : o !== i ? o = [o, l] : l !== i && (o = l), s !== i && s;
        } }).initialize();
    }), o !== i ? o : this;
  }, e.fn.transition.exists = {}, e.fn.transition.settings = { name: "Transition", silent: !1, debug: !1, verbose: !1, performance: !0, namespace: "transition", interval: 0, reverse: "auto", onStart: function onStart() {}, onComplete: function onComplete() {}, onShow: function onShow() {}, onHide: function onHide() {}, useFailSafe: !0, failSafeDelay: 100, allowRepeats: !1, displayType: !1, animation: "fade", duration: !1, queue: !0, metadata: { displayType: "display" }, className: { animating: "animating", disabled: "disabled", hidden: "hidden", inward: "in", loading: "loading", looping: "looping", outward: "out", transition: "transition", visible: "visible" }, error: { noAnimation: "Element is no longer attached to DOM. Unable to animate.  Use silent setting to surpress this warning in production.", repeated: "That animation is already occurring, cancelling repeated animation", method: "The method you called is not defined", support: "This browser does not support CSS animations" } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")();e.api = e.fn.api = function (n) {
    var o,
        a = e.isFunction(this) ? e(t) : e(this),
        r = a.selector || "",
        s = new Date().getTime(),
        l = [],
        c = arguments[0],
        u = "string" == typeof c,
        d = [].slice.call(arguments, 1);return a.each(function () {
      var a,
          f,
          m,
          g,
          p,
          h,
          v = e.isPlainObject(n) ? e.extend(!0, {}, e.fn.api.settings, n) : e.extend({}, e.fn.api.settings),
          b = v.namespace,
          y = v.metadata,
          x = v.selector,
          C = v.error,
          w = v.className,
          S = "." + b,
          k = "module-" + b,
          T = e(this),
          A = T.closest(x.form),
          R = v.stateContext ? e(v.stateContext) : T,
          P = this,
          E = R[0],
          F = T.data(k);h = { initialize: function initialize() {
          u || h.bind.events(), h.instantiate();
        }, instantiate: function instantiate() {
          h.verbose("Storing instance of module", h), F = h, T.data(k, F);
        }, destroy: function destroy() {
          h.verbose("Destroying previous module for", P), T.removeData(k).off(S);
        }, bind: { events: function events() {
            var e = h.get.event();e ? (h.verbose("Attaching API events to element", e), T.on(e + S, h.event.trigger)) : "now" == v.on && (h.debug("Querying API endpoint immediately"), h.query());
          } }, decode: { json: function json(e) {
            if (e !== i && "string" == typeof e) try {
              e = JSON.parse(e);
            } catch (e) {}return e;
          } }, read: { cachedResponse: function cachedResponse(e) {
            var n;if (t.Storage !== i) return n = sessionStorage.getItem(e), h.debug("Using cached response", e, n), n = h.decode.json(n);h.error(C.noStorage);
          } }, write: { cachedResponse: function cachedResponse(n, o) {
            o && "" === o ? h.debug("Response empty, not caching", o) : t.Storage !== i ? (e.isPlainObject(o) && (o = JSON.stringify(o)), sessionStorage.setItem(n, o), h.verbose("Storing cached response for url", n, o)) : h.error(C.noStorage);
          } }, query: function query() {
          if (h.is.disabled()) h.debug("Element is disabled API request aborted");else {
            if (h.is.loading()) {
              if (!v.interruptRequests) return void h.debug("Cancelling request, previous request is still pending");h.debug("Interrupting previous request"), h.abort();
            }if (v.defaultData && e.extend(!0, v.urlData, h.get.defaultData()), v.serializeForm && (v.data = h.add.formData(v.data)), !1 === (f = h.get.settings())) return h.cancelled = !0, void h.error(C.beforeSend);if (h.cancelled = !1, (m = h.get.templatedURL()) || h.is.mocked()) {
              if ((m = h.add.urlData(m)) || h.is.mocked()) {
                if (f.url = v.base + m, a = e.extend(!0, {}, v, { type: v.method || v.type, data: g, url: v.base + m, beforeSend: v.beforeXHR, success: function success() {}, failure: function failure() {}, complete: function complete() {} }), h.debug("Querying URL", a.url), h.verbose("Using AJAX settings", a), "local" === v.cache && h.read.cachedResponse(m)) return h.debug("Response returned from local cache"), h.request = h.create.request(), void h.request.resolveWith(E, [h.read.cachedResponse(m)]);v.throttle ? v.throttleFirstRequest || h.timer ? (h.debug("Throttling request", v.throttle), clearTimeout(h.timer), h.timer = setTimeout(function () {
                  h.timer && delete h.timer, h.debug("Sending throttled request", g, a.method), h.send.request();
                }, v.throttle)) : (h.debug("Sending request", g, a.method), h.send.request(), h.timer = setTimeout(function () {}, v.throttle)) : (h.debug("Sending request", g, a.method), h.send.request());
              }
            } else h.error(C.missingURL);
          }
        }, should: { removeError: function removeError() {
            return !0 === v.hideError || "auto" === v.hideError && !h.is.form();
          } }, is: { disabled: function disabled() {
            return T.filter(x.disabled).length > 0;
          }, expectingJSON: function expectingJSON() {
            return "json" === v.dataType || "jsonp" === v.dataType;
          }, form: function form() {
            return T.is("form") || R.is("form");
          }, mocked: function mocked() {
            return v.mockResponse || v.mockResponseAsync || v.response || v.responseAsync;
          }, input: function input() {
            return T.is("input");
          }, loading: function loading() {
            return !!h.request && "pending" == h.request.state();
          }, abortedRequest: function abortedRequest(e) {
            return e && e.readyState !== i && 0 === e.readyState ? (h.verbose("XHR request determined to be aborted"), !0) : (h.verbose("XHR request was not aborted"), !1);
          }, validResponse: function validResponse(t) {
            return h.is.expectingJSON() && e.isFunction(v.successTest) ? (h.debug("Checking JSON returned success", v.successTest, t), v.successTest(t) ? (h.debug("Response passed success test", t), !0) : (h.debug("Response failed success test", t), !1)) : (h.verbose("Response is not JSON, skipping validation", v.successTest, t), !0);
          } }, was: { cancelled: function cancelled() {
            return h.cancelled || !1;
          }, succesful: function succesful() {
            return h.request && "resolved" == h.request.state();
          }, failure: function failure() {
            return h.request && "rejected" == h.request.state();
          }, complete: function complete() {
            return h.request && ("resolved" == h.request.state() || "rejected" == h.request.state());
          } }, add: { urlData: function urlData(t, n) {
            var o, a;return t && (o = t.match(v.regExp.required), a = t.match(v.regExp.optional), n = n || v.urlData, o && (h.debug("Looking for required URL variables", o), e.each(o, function (o, a) {
              var r = -1 !== a.indexOf("$") ? a.substr(2, a.length - 3) : a.substr(1, a.length - 2),
                  s = e.isPlainObject(n) && n[r] !== i ? n[r] : T.data(r) !== i ? T.data(r) : R.data(r) !== i ? R.data(r) : n[r];if (s === i) return h.error(C.requiredParameter, r, t), t = !1, !1;h.verbose("Found required variable", r, s), s = v.encodeParameters ? h.get.urlEncodedValue(s) : s, t = t.replace(a, s);
            })), a && (h.debug("Looking for optional URL variables", o), e.each(a, function (o, a) {
              var r = -1 !== a.indexOf("$") ? a.substr(3, a.length - 4) : a.substr(2, a.length - 3),
                  s = e.isPlainObject(n) && n[r] !== i ? n[r] : T.data(r) !== i ? T.data(r) : R.data(r) !== i ? R.data(r) : n[r];s !== i ? (h.verbose("Optional variable Found", r, s), t = t.replace(a, s)) : (h.verbose("Optional variable not found", r), t = -1 !== t.indexOf("/" + a) ? t.replace("/" + a, "") : t.replace(a, ""));
            }))), t;
          }, formData: function formData(t) {
            var n = e.fn.serializeObject !== i,
                o = n ? A.serializeObject() : A.serialize();return t = t || v.data, e.isPlainObject(t) ? n ? (h.debug("Extending existing data with form data", t, o), t = e.extend(!0, {}, t, o)) : (h.error(C.missingSerialize), h.debug("Cant extend data. Replacing data with form data", t, o), t = o) : (h.debug("Adding form data", o), t = o), t;
          } }, send: { request: function request() {
            h.set.loading(), h.request = h.create.request(), h.is.mocked() ? h.mockedXHR = h.create.mockedXHR() : h.xhr = h.create.xhr(), v.onRequest.call(E, h.request, h.xhr);
          } }, event: { trigger: function trigger(e) {
            h.query(), "submit" != e.type && "click" != e.type || e.preventDefault();
          }, xhr: { always: function always() {}, done: function done(t, n, i) {
              var o = this,
                  a = new Date().getTime() - p,
                  r = v.loadingDuration - a,
                  s = !!e.isFunction(v.onResponse) && (h.is.expectingJSON() ? v.onResponse.call(o, e.extend(!0, {}, t)) : v.onResponse.call(o, t));r = r > 0 ? r : 0, s && (h.debug("Modified API response in onResponse callback", v.onResponse, s, t), t = s), r > 0 && h.debug("Response completed early delaying state change by", r), setTimeout(function () {
                h.is.validResponse(t) ? h.request.resolveWith(o, [t, i]) : h.request.rejectWith(o, [i, "invalid"]);
              }, r);
            }, fail: function fail(e, t, n) {
              var i = this,
                  o = new Date().getTime() - p,
                  a = v.loadingDuration - o;(a = a > 0 ? a : 0) > 0 && h.debug("Response completed early delaying state change by", a), setTimeout(function () {
                h.is.abortedRequest(e) ? h.request.rejectWith(i, [e, "aborted", n]) : h.request.rejectWith(i, [e, "error", t, n]);
              }, a);
            } }, request: { done: function done(e, t) {
              h.debug("Successful API Response", e), "local" === v.cache && m && (h.write.cachedResponse(m, e), h.debug("Saving server response locally", h.cache)), v.onSuccess.call(E, e, T, t);
            }, complete: function complete(e, t) {
              var n, i;h.was.succesful() ? (i = e, n = t) : (n = e, i = h.get.responseFromXHR(n)), h.remove.loading(), v.onComplete.call(E, i, T, n);
            }, fail: function fail(e, t, n) {
              var o = h.get.responseFromXHR(e),
                  r = h.get.errorFromRequest(o, t, n);if ("aborted" == t) return h.debug("XHR Aborted (Most likely caused by page navigation or CORS Policy)", t, n), v.onAbort.call(E, t, T, e), !0;"invalid" == t ? h.debug("JSON did not pass success test. A server-side error has most likely occurred", o) : "error" == t && e !== i && (h.debug("XHR produced a server error", t, n), 200 != e.status && n !== i && "" !== n && h.error(C.statusMessage + n, a.url), v.onError.call(E, r, T, e)), v.errorDuration && "aborted" !== t && (h.debug("Adding error state"), h.set.error(), h.should.removeError() && setTimeout(h.remove.error, v.errorDuration)), h.debug("API Request failed", r, e), v.onFailure.call(E, o, T, e);
            } } }, create: { request: function request() {
            return e.Deferred().always(h.event.request.complete).done(h.event.request.done).fail(h.event.request.fail);
          }, mockedXHR: function mockedXHR() {
            var t,
                n,
                i,
                o = v.mockResponse || v.response,
                a = v.mockResponseAsync || v.responseAsync;return i = e.Deferred().always(h.event.xhr.complete).done(h.event.xhr.done).fail(h.event.xhr.fail), o ? (e.isFunction(o) ? (h.debug("Using specified synchronous callback", o), n = o.call(E, f)) : (h.debug("Using settings specified response", o), n = o), i.resolveWith(E, [n, !1, { responseText: n }])) : e.isFunction(a) && (t = function t(e) {
              h.debug("Async callback returned response", e), e ? i.resolveWith(E, [e, !1, { responseText: e }]) : i.rejectWith(E, [{ responseText: e }, !1, !1]);
            }, h.debug("Using specified async response callback", a), a.call(E, f, t)), i;
          }, xhr: function xhr() {
            var t;return t = e.ajax(a).always(h.event.xhr.always).done(h.event.xhr.done).fail(h.event.xhr.fail), h.verbose("Created server request", t, a), t;
          } }, set: { error: function error() {
            h.verbose("Adding error state to element", R), R.addClass(w.error);
          }, loading: function loading() {
            h.verbose("Adding loading state to element", R), R.addClass(w.loading), p = new Date().getTime();
          } }, remove: { error: function error() {
            h.verbose("Removing error state from element", R), R.removeClass(w.error);
          }, loading: function loading() {
            h.verbose("Removing loading state from element", R), R.removeClass(w.loading);
          } }, get: { responseFromXHR: function responseFromXHR(t) {
            return !!e.isPlainObject(t) && (h.is.expectingJSON() ? h.decode.json(t.responseText) : t.responseText);
          }, errorFromRequest: function errorFromRequest(t, n, o) {
            return e.isPlainObject(t) && t.error !== i ? t.error : v.error[n] !== i ? v.error[n] : o;
          }, request: function request() {
            return h.request || !1;
          }, xhr: function xhr() {
            return h.xhr || !1;
          }, settings: function settings() {
            var t;return (t = v.beforeSend.call(E, v)) && (t.success !== i && (h.debug("Legacy success callback detected", t), h.error(C.legacyParameters, t.success), t.onSuccess = t.success), t.failure !== i && (h.debug("Legacy failure callback detected", t), h.error(C.legacyParameters, t.failure), t.onFailure = t.failure), t.complete !== i && (h.debug("Legacy complete callback detected", t), h.error(C.legacyParameters, t.complete), t.onComplete = t.complete)), t === i && h.error(C.noReturnedValue), !1 === t ? t : t !== i ? e.extend(!0, {}, t) : e.extend(!0, {}, v);
          }, urlEncodedValue: function urlEncodedValue(e) {
            var n = t.decodeURIComponent(e),
                i = t.encodeURIComponent(e);return n !== e ? (h.debug("URL value is already encoded, avoiding double encoding", e), e) : (h.verbose("Encoding value using encodeURIComponent", e, i), i);
          }, defaultData: function defaultData() {
            var t = {};return e.isWindow(P) || (h.is.input() ? t.value = T.val() : h.is.form() || (t.text = T.text())), t;
          }, event: function event() {
            return e.isWindow(P) || "now" == v.on ? (h.debug("API called without element, no events attached"), !1) : "auto" == v.on ? T.is("input") ? P.oninput !== i ? "input" : P.onpropertychange !== i ? "propertychange" : "keyup" : T.is("form") ? "submit" : "click" : v.on;
          }, templatedURL: function templatedURL(e) {
            if (e = e || T.data(y.action) || v.action || !1, m = T.data(y.url) || v.url || !1) return h.debug("Using specified url", m), m;if (e) {
              if (h.debug("Looking up url for action", e, v.api), v.api[e] === i && !h.is.mocked()) return void h.error(C.missingAction, v.action, v.api);m = v.api[e];
            } else h.is.form() && (m = T.attr("action") || R.attr("action") || !1, h.debug("No url or action specified, defaulting to form action", m));return m;
          } }, abort: function abort() {
          var e = h.get.xhr();e && "resolved" !== e.state() && (h.debug("Cancelling API request"), e.abort());
        }, reset: function reset() {
          h.remove.error(), h.remove.loading();
        }, setting: function setting(t, n) {
          if (h.debug("Changing setting", t, n), e.isPlainObject(t)) e.extend(!0, v, t);else {
            if (n === i) return v[t];e.isPlainObject(v[t]) ? e.extend(!0, v[t], n) : v[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, h, t);else {
            if (n === i) return h[t];h[t] = n;
          }
        }, debug: function debug() {
          !v.silent && v.debug && (v.performance ? h.performance.log(arguments) : (h.debug = Function.prototype.bind.call(console.info, console, v.name + ":"), h.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !v.silent && v.verbose && v.debug && (v.performance ? h.performance.log(arguments) : (h.verbose = Function.prototype.bind.call(console.info, console, v.name + ":"), h.verbose.apply(console, arguments)));
        }, error: function error() {
          v.silent || (h.error = Function.prototype.bind.call(console.error, console, v.name + ":"), h.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;v.performance && (n = (t = new Date().getTime()) - (s || t), s = t, l.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", "Execution Time": n })), clearTimeout(h.performance.timer), h.performance.timer = setTimeout(h.performance.display, 500);
          }, display: function display() {
            var t = v.name + ":",
                n = 0;s = !1, clearTimeout(h.performance.timer), e.each(l, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", r && (t += " '" + r + "'"), (console.group !== i || console.table !== i) && l.length > 0 && (console.groupCollapsed(t), console.table ? console.table(l) : e.each(l, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), l = [];
          } }, invoke: function invoke(t, n, a) {
          var r,
              s,
              l,
              c = F;return n = n || d, a = P || a, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i ? (s = c[o], !1) : (h.error(C.method, t), !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(a, n) : s !== i && (l = s), e.isArray(o) ? o.push(l) : o !== i ? o = [o, l] : l !== i && (o = l), s;
        } }, u ? (F === i && h.initialize(), h.invoke(c)) : (F !== i && F.invoke("destroy"), h.initialize());
    }), o !== i ? o : this;
  }, e.api.settings = { name: "API", namespace: "api", debug: !1, verbose: !1, performance: !0, api: {}, cache: !0, interruptRequests: !0, on: "auto", stateContext: !1, loadingDuration: 0, hideError: "auto", errorDuration: 2e3, encodeParameters: !0, action: !1, url: !1, base: "", urlData: {}, defaultData: !0, serializeForm: !1, throttle: 0, throttleFirstRequest: !0, method: "get", data: {}, dataType: "json", mockResponse: !1, mockResponseAsync: !1, response: !1, responseAsync: !1, beforeSend: function beforeSend(e) {
      return e;
    }, beforeXHR: function beforeXHR(e) {}, onRequest: function onRequest(e, t) {}, onResponse: !1, onSuccess: function onSuccess(e, t) {}, onComplete: function onComplete(e, t) {}, onFailure: function onFailure(e, t) {}, onError: function onError(e, t) {}, onAbort: function onAbort(e, t) {}, successTest: !1, error: { beforeSend: "The before send function has aborted the request", error: "There was an error with your request", exitConditions: "API Request Aborted. Exit conditions met", JSONParse: "JSON could not be parsed during error handling", legacyParameters: "You are using legacy API success callback names", method: "The method you called is not defined", missingAction: "API action used but no url was defined", missingSerialize: "jquery-serialize-object is required to add form data to an existing data object", missingURL: "No URL specified for api event", noReturnedValue: "The beforeSend callback must return a settings object, beforeSend ignored.", noStorage: "Caching responses locally requires session storage", parseError: "There was an error parsing your request", requiredParameter: "Missing a required URL parameter: ", statusMessage: "Server gave an error: ", timeout: "Your request timed out" }, regExp: { required: /\{\$*[A-z0-9]+\}/g, optional: /\{\/\$*[A-z0-9]+\}/g }, className: { loading: "loading", error: "error" }, selector: { disabled: ".disabled", form: "form" }, metadata: { action: "action", url: "url" } };
}(jQuery, window, document), function (e, t, n, i) {
  "use strict";
  t = void 0 !== t && t.Math == Math ? t : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(), e.fn.visibility = function (o) {
    var a,
        r = e(this),
        s = r.selector || "",
        l = new Date().getTime(),
        c = [],
        u = arguments[0],
        d = "string" == typeof u,
        f = [].slice.call(arguments, 1),
        m = r.length,
        g = 0;return r.each(function () {
      var r,
          p,
          h,
          v,
          b = e.isPlainObject(o) ? e.extend(!0, {}, e.fn.visibility.settings, o) : e.extend({}, e.fn.visibility.settings),
          y = b.className,
          x = b.namespace,
          C = b.error,
          w = b.metadata,
          S = "." + x,
          k = "module-" + x,
          T = e(t),
          A = e(this),
          R = e(b.context),
          P = (A.selector, A.data(k)),
          E = t.requestAnimationFrame || t.mozRequestAnimationFrame || t.webkitRequestAnimationFrame || t.msRequestAnimationFrame || function (e) {
        setTimeout(e, 0);
      },
          F = this,
          O = !1;v = { initialize: function initialize() {
          v.debug("Initializing", b), v.setup.cache(), v.should.trackChanges() && ("image" == b.type && v.setup.image(), "fixed" == b.type && v.setup.fixed(), b.observeChanges && v.observeChanges(), v.bind.events()), v.save.position(), v.is.visible() || v.error(C.visible, A), b.initialCheck && v.checkVisibility(), v.instantiate();
        }, instantiate: function instantiate() {
          v.debug("Storing instance", v), A.data(k, v), P = v;
        }, destroy: function destroy() {
          v.verbose("Destroying previous module"), h && h.disconnect(), p && p.disconnect(), T.off("load" + S, v.event.load).off("resize" + S, v.event.resize), R.off("scroll" + S, v.event.scroll).off("scrollchange" + S, v.event.scrollchange), "fixed" == b.type && (v.resetFixed(), v.remove.placeholder()), A.off(S).removeData(k);
        }, observeChanges: function observeChanges() {
          "MutationObserver" in t && (p = new MutationObserver(v.event.contextChanged), h = new MutationObserver(v.event.changed), p.observe(n, { childList: !0, subtree: !0 }), h.observe(F, { childList: !0, subtree: !0 }), v.debug("Setting up mutation observer", h));
        }, bind: { events: function events() {
            v.verbose("Binding visibility events to scroll and resize"), b.refreshOnLoad && T.on("load" + S, v.event.load), T.on("resize" + S, v.event.resize), R.off("scroll" + S).on("scroll" + S, v.event.scroll).on("scrollchange" + S, v.event.scrollchange);
          } }, event: { changed: function changed(e) {
            v.verbose("DOM tree modified, updating visibility calculations"), v.timer = setTimeout(function () {
              v.verbose("DOM tree modified, updating sticky menu"), v.refresh();
            }, 100);
          }, contextChanged: function contextChanged(t) {
            [].forEach.call(t, function (t) {
              t.removedNodes && [].forEach.call(t.removedNodes, function (t) {
                (t == F || e(t).find(F).length > 0) && (v.debug("Element removed from DOM, tearing down events"), v.destroy());
              });
            });
          }, resize: function resize() {
            v.debug("Window resized"), b.refreshOnResize && E(v.refresh);
          }, load: function load() {
            v.debug("Page finished loading"), E(v.refresh);
          }, scroll: function scroll() {
            b.throttle ? (clearTimeout(v.timer), v.timer = setTimeout(function () {
              R.triggerHandler("scrollchange" + S, [R.scrollTop()]);
            }, b.throttle)) : E(function () {
              R.triggerHandler("scrollchange" + S, [R.scrollTop()]);
            });
          }, scrollchange: function scrollchange(e, t) {
            v.checkVisibility(t);
          } }, precache: function precache(t, i) {
          t instanceof Array || (t = [t]);for (var o = t.length, a = 0, r = [], s = n.createElement("img"), l = function l() {
            ++a >= t.length && e.isFunction(i) && i();
          }; o--;) {
            (s = n.createElement("img")).onload = l, s.onerror = l, s.src = t[o], r.push(s);
          }
        }, enableCallbacks: function enableCallbacks() {
          v.debug("Allowing callbacks to occur"), O = !1;
        }, disableCallbacks: function disableCallbacks() {
          v.debug("Disabling all callbacks temporarily"), O = !0;
        }, should: { trackChanges: function trackChanges() {
            return d ? (v.debug("One time query, no need to bind events"), !1) : (v.debug("Callbacks being attached"), !0);
          } }, setup: { cache: function cache() {
            v.cache = { occurred: {}, screen: {}, element: {} };
          }, image: function image() {
            var e = A.data(w.src);e && (v.verbose("Lazy loading image", e), b.once = !0, b.observeChanges = !1, b.onOnScreen = function () {
              v.debug("Image on screen", F), v.precache(e, function () {
                v.set.image(e, function () {
                  ++g == m && b.onAllLoaded.call(this), b.onLoad.call(this);
                });
              });
            });
          }, fixed: function fixed() {
            v.debug("Setting up fixed"), b.once = !1, b.observeChanges = !1, b.initialCheck = !0, b.refreshOnLoad = !0, o.transition || (b.transition = !1), v.create.placeholder(), v.debug("Added placeholder", r), b.onTopPassed = function () {
              v.debug("Element passed, adding fixed position", A), v.show.placeholder(), v.set.fixed(), b.transition && e.fn.transition !== i && A.transition(b.transition, b.duration);
            }, b.onTopPassedReverse = function () {
              v.debug("Element returned to position, removing fixed", A), v.hide.placeholder(), v.remove.fixed();
            };
          } }, create: { placeholder: function placeholder() {
            v.verbose("Creating fixed position placeholder"), r = A.clone(!1).css("display", "none").addClass(y.placeholder).insertAfter(A);
          } }, show: { placeholder: function placeholder() {
            v.verbose("Showing placeholder"), r.css("display", "block").css("visibility", "hidden");
          } }, hide: { placeholder: function placeholder() {
            v.verbose("Hiding placeholder"), r.css("display", "none").css("visibility", "");
          } }, set: { fixed: function fixed() {
            v.verbose("Setting element to fixed position"), A.addClass(y.fixed).css({ position: "fixed", top: b.offset + "px", left: "auto", zIndex: b.zIndex }), b.onFixed.call(F);
          }, image: function image(t, n) {
            if (A.attr("src", t), b.transition) {
              if (e.fn.transition !== i) {
                if (A.hasClass(y.visible)) return void v.debug("Transition already occurred on this image, skipping animation");A.transition(b.transition, b.duration, n);
              } else A.fadeIn(b.duration, n);
            } else A.show();
          } }, is: { onScreen: function onScreen() {
            return v.get.elementCalculations().onScreen;
          }, offScreen: function offScreen() {
            return v.get.elementCalculations().offScreen;
          }, visible: function visible() {
            return !(!v.cache || !v.cache.element) && !(0 === v.cache.element.width && 0 === v.cache.element.offset.top);
          }, verticallyScrollableContext: function verticallyScrollableContext() {
            var e = R.get(0) !== t && R.css("overflow-y");return "auto" == e || "scroll" == e;
          }, horizontallyScrollableContext: function horizontallyScrollableContext() {
            var e = R.get(0) !== t && R.css("overflow-x");return "auto" == e || "scroll" == e;
          } }, refresh: function refresh() {
          v.debug("Refreshing constants (width/height)"), "fixed" == b.type && v.resetFixed(), v.reset(), v.save.position(), b.checkOnRefresh && v.checkVisibility(), b.onRefresh.call(F);
        }, resetFixed: function resetFixed() {
          v.remove.fixed(), v.remove.occurred();
        }, reset: function reset() {
          v.verbose("Resetting all cached values"), e.isPlainObject(v.cache) && (v.cache.screen = {}, v.cache.element = {});
        }, checkVisibility: function checkVisibility(e) {
          v.verbose("Checking visibility of element", v.cache.element), !O && v.is.visible() && (v.save.scroll(e), v.save.calculations(), v.passed(), v.passingReverse(), v.topVisibleReverse(), v.bottomVisibleReverse(), v.topPassedReverse(), v.bottomPassedReverse(), v.onScreen(), v.offScreen(), v.passing(), v.topVisible(), v.bottomVisible(), v.topPassed(), v.bottomPassed(), b.onUpdate && b.onUpdate.call(F, v.get.elementCalculations()));
        }, passed: function passed(t, n) {
          var o = v.get.elementCalculations();if (t && n) b.onPassed[t] = n;else {
            if (t !== i) return v.get.pixelsPassed(t) > o.pixelsPassed;o.passing && e.each(b.onPassed, function (e, t) {
              o.bottomVisible || o.pixelsPassed > v.get.pixelsPassed(e) ? v.execute(t, e) : b.once || v.remove.occurred(t);
            });
          }
        }, onScreen: function onScreen(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onOnScreen,
              o = "onScreen";if (e && (v.debug("Adding callback for onScreen", e), b.onOnScreen = e), t.onScreen ? v.execute(n, o) : b.once || v.remove.occurred(o), e !== i) return t.onOnScreen;
        }, offScreen: function offScreen(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onOffScreen,
              o = "offScreen";if (e && (v.debug("Adding callback for offScreen", e), b.onOffScreen = e), t.offScreen ? v.execute(n, o) : b.once || v.remove.occurred(o), e !== i) return t.onOffScreen;
        }, passing: function passing(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onPassing,
              o = "passing";if (e && (v.debug("Adding callback for passing", e), b.onPassing = e), t.passing ? v.execute(n, o) : b.once || v.remove.occurred(o), e !== i) return t.passing;
        }, topVisible: function topVisible(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onTopVisible,
              o = "topVisible";if (e && (v.debug("Adding callback for top visible", e), b.onTopVisible = e), t.topVisible ? v.execute(n, o) : b.once || v.remove.occurred(o), e === i) return t.topVisible;
        }, bottomVisible: function bottomVisible(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onBottomVisible,
              o = "bottomVisible";if (e && (v.debug("Adding callback for bottom visible", e), b.onBottomVisible = e), t.bottomVisible ? v.execute(n, o) : b.once || v.remove.occurred(o), e === i) return t.bottomVisible;
        }, topPassed: function topPassed(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onTopPassed,
              o = "topPassed";if (e && (v.debug("Adding callback for top passed", e), b.onTopPassed = e), t.topPassed ? v.execute(n, o) : b.once || v.remove.occurred(o), e === i) return t.topPassed;
        }, bottomPassed: function bottomPassed(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onBottomPassed,
              o = "bottomPassed";if (e && (v.debug("Adding callback for bottom passed", e), b.onBottomPassed = e), t.bottomPassed ? v.execute(n, o) : b.once || v.remove.occurred(o), e === i) return t.bottomPassed;
        }, passingReverse: function passingReverse(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onPassingReverse,
              o = "passingReverse";if (e && (v.debug("Adding callback for passing reverse", e), b.onPassingReverse = e), t.passing ? b.once || v.remove.occurred(o) : v.get.occurred("passing") && v.execute(n, o), e !== i) return !t.passing;
        }, topVisibleReverse: function topVisibleReverse(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onTopVisibleReverse,
              o = "topVisibleReverse";if (e && (v.debug("Adding callback for top visible reverse", e), b.onTopVisibleReverse = e), t.topVisible ? b.once || v.remove.occurred(o) : v.get.occurred("topVisible") && v.execute(n, o), e === i) return !t.topVisible;
        }, bottomVisibleReverse: function bottomVisibleReverse(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onBottomVisibleReverse,
              o = "bottomVisibleReverse";if (e && (v.debug("Adding callback for bottom visible reverse", e), b.onBottomVisibleReverse = e), t.bottomVisible ? b.once || v.remove.occurred(o) : v.get.occurred("bottomVisible") && v.execute(n, o), e === i) return !t.bottomVisible;
        }, topPassedReverse: function topPassedReverse(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onTopPassedReverse,
              o = "topPassedReverse";if (e && (v.debug("Adding callback for top passed reverse", e), b.onTopPassedReverse = e), t.topPassed ? b.once || v.remove.occurred(o) : v.get.occurred("topPassed") && v.execute(n, o), e === i) return !t.onTopPassed;
        }, bottomPassedReverse: function bottomPassedReverse(e) {
          var t = v.get.elementCalculations(),
              n = e || b.onBottomPassedReverse,
              o = "bottomPassedReverse";if (e && (v.debug("Adding callback for bottom passed reverse", e), b.onBottomPassedReverse = e), t.bottomPassed ? b.once || v.remove.occurred(o) : v.get.occurred("bottomPassed") && v.execute(n, o), e === i) return !t.bottomPassed;
        }, execute: function execute(e, t) {
          var n = v.get.elementCalculations(),
              i = v.get.screenCalculations();(e = e || !1) && (b.continuous ? (v.debug("Callback being called continuously", t, n), e.call(F, n, i)) : v.get.occurred(t) || (v.debug("Conditions met", t, n), e.call(F, n, i))), v.save.occurred(t);
        }, remove: { fixed: function fixed() {
            v.debug("Removing fixed position"), A.removeClass(y.fixed).css({ position: "", top: "", left: "", zIndex: "" }), b.onUnfixed.call(F);
          }, placeholder: function placeholder() {
            v.debug("Removing placeholder content"), r && r.remove();
          }, occurred: function occurred(e) {
            if (e) {
              var t = v.cache.occurred;t[e] !== i && !0 === t[e] && (v.debug("Callback can now be called again", e), v.cache.occurred[e] = !1);
            } else v.cache.occurred = {};
          } }, save: { calculations: function calculations() {
            v.verbose("Saving all calculations necessary to determine positioning"), v.save.direction(), v.save.screenCalculations(), v.save.elementCalculations();
          }, occurred: function occurred(e) {
            e && (v.cache.occurred[e] !== i && !0 === v.cache.occurred[e] || (v.verbose("Saving callback occurred", e), v.cache.occurred[e] = !0));
          }, scroll: function scroll(e) {
            e = e + b.offset || R.scrollTop() + b.offset, v.cache.scroll = e;
          }, direction: function direction() {
            var e,
                t = v.get.scroll(),
                n = v.get.lastScroll();return e = t > n && n ? "down" : t < n && n ? "up" : "static", v.cache.direction = e, v.cache.direction;
          }, elementPosition: function elementPosition() {
            var e = v.cache.element,
                t = v.get.screenSize();return v.verbose("Saving element position"), e.fits = e.height < t.height, e.offset = A.offset(), e.width = A.outerWidth(), e.height = A.outerHeight(), v.is.verticallyScrollableContext() && (e.offset.top += R.scrollTop() - R.offset().top), v.is.horizontallyScrollableContext() && (e.offset.left += R.scrollLeft - R.offset().left), v.cache.element = e, e;
          }, elementCalculations: function elementCalculations() {
            var e = v.get.screenCalculations(),
                t = v.get.elementPosition();return b.includeMargin ? (t.margin = {}, t.margin.top = parseInt(A.css("margin-top"), 10), t.margin.bottom = parseInt(A.css("margin-bottom"), 10), t.top = t.offset.top - t.margin.top, t.bottom = t.offset.top + t.height + t.margin.bottom) : (t.top = t.offset.top, t.bottom = t.offset.top + t.height), t.topPassed = e.top >= t.top, t.bottomPassed = e.top >= t.bottom, t.topVisible = e.bottom >= t.top && !t.topPassed, t.bottomVisible = e.bottom >= t.bottom && !t.bottomPassed, t.pixelsPassed = 0, t.percentagePassed = 0, t.onScreen = (t.topVisible || t.passing) && !t.bottomPassed, t.passing = t.topPassed && !t.bottomPassed, t.offScreen = !t.onScreen, t.passing && (t.pixelsPassed = e.top - t.top, t.percentagePassed = (e.top - t.top) / t.height), v.cache.element = t, v.verbose("Updated element calculations", t), t;
          }, screenCalculations: function screenCalculations() {
            var e = v.get.scroll();return v.save.direction(), v.cache.screen.top = e, v.cache.screen.bottom = e + v.cache.screen.height, v.cache.screen;
          }, screenSize: function screenSize() {
            v.verbose("Saving window position"), v.cache.screen = { height: R.height() };
          }, position: function position() {
            v.save.screenSize(), v.save.elementPosition();
          } }, get: { pixelsPassed: function pixelsPassed(e) {
            var t = v.get.elementCalculations();return e.search("%") > -1 ? t.height * (parseInt(e, 10) / 100) : parseInt(e, 10);
          }, occurred: function occurred(e) {
            return v.cache.occurred !== i && v.cache.occurred[e] || !1;
          }, direction: function direction() {
            return v.cache.direction === i && v.save.direction(), v.cache.direction;
          }, elementPosition: function elementPosition() {
            return v.cache.element === i && v.save.elementPosition(), v.cache.element;
          }, elementCalculations: function elementCalculations() {
            return v.cache.element === i && v.save.elementCalculations(), v.cache.element;
          }, screenCalculations: function screenCalculations() {
            return v.cache.screen === i && v.save.screenCalculations(), v.cache.screen;
          }, screenSize: function screenSize() {
            return v.cache.screen === i && v.save.screenSize(), v.cache.screen;
          }, scroll: function scroll() {
            return v.cache.scroll === i && v.save.scroll(), v.cache.scroll;
          }, lastScroll: function lastScroll() {
            return v.cache.screen === i ? (v.debug("First scroll event, no last scroll could be found"), !1) : v.cache.screen.top;
          } }, setting: function setting(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, b, t);else {
            if (n === i) return b[t];b[t] = n;
          }
        }, internal: function internal(t, n) {
          if (e.isPlainObject(t)) e.extend(!0, v, t);else {
            if (n === i) return v[t];v[t] = n;
          }
        }, debug: function debug() {
          !b.silent && b.debug && (b.performance ? v.performance.log(arguments) : (v.debug = Function.prototype.bind.call(console.info, console, b.name + ":"), v.debug.apply(console, arguments)));
        }, verbose: function verbose() {
          !b.silent && b.verbose && b.debug && (b.performance ? v.performance.log(arguments) : (v.verbose = Function.prototype.bind.call(console.info, console, b.name + ":"), v.verbose.apply(console, arguments)));
        }, error: function error() {
          b.silent || (v.error = Function.prototype.bind.call(console.error, console, b.name + ":"), v.error.apply(console, arguments));
        }, performance: { log: function log(e) {
            var t, n;b.performance && (n = (t = new Date().getTime()) - (l || t), l = t, c.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: F, "Execution Time": n })), clearTimeout(v.performance.timer), v.performance.timer = setTimeout(v.performance.display, 500);
          }, display: function display() {
            var t = b.name + ":",
                n = 0;l = !1, clearTimeout(v.performance.timer), e.each(c, function (e, t) {
              n += t["Execution Time"];
            }), t += " " + n + "ms", s && (t += " '" + s + "'"), (console.group !== i || console.table !== i) && c.length > 0 && (console.groupCollapsed(t), console.table ? console.table(c) : e.each(c, function (e, t) {
              console.log(t.Name + ": " + t["Execution Time"] + "ms");
            }), console.groupEnd()), c = [];
          } }, invoke: function invoke(t, n, o) {
          var r,
              s,
              l,
              c = P;return n = n || f, o = F || o, "string" == typeof t && c !== i && (t = t.split(/[\. ]/), r = t.length - 1, e.each(t, function (n, o) {
            var a = n != r ? o + t[n + 1].charAt(0).toUpperCase() + t[n + 1].slice(1) : t;if (e.isPlainObject(c[a]) && n != r) c = c[a];else {
              if (c[a] !== i) return s = c[a], !1;if (!e.isPlainObject(c[o]) || n == r) return c[o] !== i ? (s = c[o], !1) : (v.error(C.method, t), !1);c = c[o];
            }
          })), e.isFunction(s) ? l = s.apply(o, n) : s !== i && (l = s), e.isArray(a) ? a.push(l) : a !== i ? a = [a, l] : l !== i && (a = l), s;
        } }, d ? (P === i && v.initialize(), P.save.scroll(), P.save.calculations(), v.invoke(u)) : (P !== i && P.invoke("destroy"), v.initialize());
    }), a !== i ? a : this;
  }, e.fn.visibility.settings = { name: "Visibility", namespace: "visibility", debug: !1, verbose: !1, performance: !0, observeChanges: !0, initialCheck: !0, refreshOnLoad: !0, refreshOnResize: !0, checkOnRefresh: !0, once: !0, continuous: !1, offset: 0, includeMargin: !1, context: t, throttle: !1, type: !1, zIndex: "10", transition: "fade in", duration: 1e3, onPassed: {}, onOnScreen: !1, onOffScreen: !1, onPassing: !1, onTopVisible: !1, onBottomVisible: !1, onTopPassed: !1, onBottomPassed: !1, onPassingReverse: !1, onTopVisibleReverse: !1, onBottomVisibleReverse: !1, onTopPassedReverse: !1, onBottomPassedReverse: !1, onLoad: function onLoad() {}, onAllLoaded: function onAllLoaded() {}, onFixed: function onFixed() {}, onUnfixed: function onUnfixed() {}, onUpdate: !1, onRefresh: function onRefresh() {}, metadata: { src: "src" }, className: { fixed: "fixed", placeholder: "placeholder", visible: "visible" }, error: { method: "The method you called is not defined.", visible: "Element is hidden, you must call refresh after element becomes visible" } };
}(jQuery, window, document);

/***/ }),

/***/ "./js/services/i18nHelper.js":
/*!***********************************!*\
  !*** ./js/services/i18nHelper.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.i18nHelper = undefined;

var _lineI18n = __webpack_require__(/*! line-i18n */ "./node_modules/line-i18n/dist/index.js");

var _lineI18n2 = _interopRequireDefault(_lineI18n);

var _localizedStringsService = __webpack_require__(/*! ./localizedStringsService */ "./js/services/localizedStringsService.js");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var StringTypes = _lineI18n2.default.StringTypes;

var i18nHelper = exports.i18nHelper = Object.freeze({
  i18n: function i18n(identifier) {
    var opts = identifier.split(':');
    var type = opts[0].toLowerCase();
    var id = opts[1];
    if (StringTypes.ERROR === type) {
      return _localizedStringsService.LocalizedStrings.getError(id);
    } else if (StringTypes.MESSAGE === type) {
      return _localizedStringsService.LocalizedStrings.getMessage(id);
    } else if (StringTypes.UI === type) {
      return _localizedStringsService.LocalizedStrings.getUI(id);
    } else {
      console.warn("A string has been passed to the i18n helper function that was not in the form type:id -> " + identifier);
      return _localizedStringsService.LocalizedStrings.getString(identifier, type);
    }
  }
});

/***/ }),

/***/ "./js/services/languageService.js":
/*!****************************************!*\
  !*** ./js/services/languageService.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LanguageService = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _grammar = __webpack_require__(/*! ./../../grammar/ */ "./grammar/index.js");

var _grammar2 = _interopRequireDefault(_grammar);

var _lineI18n = __webpack_require__(/*! line-i18n */ "./node_modules/line-i18n/dist/index.js");

var _lineI18n2 = _interopRequireDefault(_lineI18n);

var _config = __webpack_require__(/*! ./../util/config */ "./js/util/config.js");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var LanguageServiceExtended = function (_line_i18n$LanguageSe) {
  _inherits(LanguageServiceExtended, _line_i18n$LanguageSe);

  function LanguageServiceExtended() {
    _classCallCheck(this, LanguageServiceExtended);

    return _possibleConstructorReturn(this, (LanguageServiceExtended.__proto__ || Object.getPrototypeOf(LanguageServiceExtended)).call(this, typeof iLMparameters === 'undefined' ? _config.Config.default_lang : iLMparameters.lang));
  }

  _createClass(LanguageServiceExtended, [{
    key: 'getCurrentLexer',
    value: function getCurrentLexer() {
      var langInfo = _grammar2.default[this.getLang()];
      if (langInfo === null || langInfo === undefined) {
        return _grammar2.default[this.getDefaultLang()].lexer;
      } else {
        return langInfo.lexer;
      }
    }
  }, {
    key: 'getCurrentLangFuncs',
    value: function getCurrentLangFuncs() {
      var langInfo = _grammar2.default[this.getLang()];
      if (langInfo === null || langInfo === undefined) {
        return _grammar2.default[this.getDefaultLang()].langFuncs;
      } else {
        return langInfo.langFuncs;
      }
    }
  }, {
    key: 'getCurrentLangLibs',
    value: function getCurrentLangLibs() {
      var langInfo = _grammar2.default[this.getLang()];
      if (langInfo === null || langInfo === undefined) {
        return _grammar2.default[this.getDefaultLang()].langLibs;
      }
      return langInfo.langLibs;
    }
  }]);

  return LanguageServiceExtended;
}(_lineI18n2.default.LanguageServiceNoLS);

var LanguageService = exports.LanguageService = new LanguageServiceExtended();

/***/ }),

/***/ "./js/services/localizedStringsService.js":
/*!************************************************!*\
  !*** ./js/services/localizedStringsService.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LocalizedStrings = undefined;

var _languageService = __webpack_require__(/*! ./languageService */ "./js/services/languageService.js");

var _lineI18n = __webpack_require__(/*! line-i18n */ "./node_modules/line-i18n/dist/index.js");

var _lineI18n2 = _interopRequireDefault(_lineI18n);

var _i18n = __webpack_require__(/*! ./../../i18n */ "./i18n/index.js");

var _i18n2 = _interopRequireDefault(_i18n);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var LocalizedStrings = exports.LocalizedStrings = Object.freeze(new _lineI18n2.default.LocalizedStrings(_languageService.LanguageService, _i18n2.default, true));

/***/ }),

/***/ "./js/typeSystem/baseTypes.js":
/*!************************************!*\
  !*** ./js/typeSystem/baseTypes.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var BaseType = function () {
  function BaseType(name, ord) {
    _classCallCheck(this, BaseType);

    this.name = name;
    this.ord = ord;
  }

  _createClass(BaseType, [{
    key: "isCompatible",
    value: function isCompatible(another) {
      if (another instanceof BaseType) {
        return this.name === another.name && this.ord === another.ord;
      }
      return false;
    }
  }, {
    key: "value",
    get: function get() {
      return this.name;
    }
  }]);

  return BaseType;
}();

// Base types names are the same as i18n ui type keys


var BaseTypes = exports.BaseTypes = Object.freeze({
  INTEGER: new BaseType("integer", 0),
  REAL: new BaseType("real", 1),
  STRING: new BaseType("text", 2),
  BOOLEAN: new BaseType("boolean", 3),
  VOID: new BaseType("void", 4),
  UNDEFINED: new BaseType("undefined", 5)
});

/***/ }),

/***/ "./js/typeSystem/compoundType.js":
/*!***************************************!*\
  !*** ./js/typeSystem/compoundType.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CompoundType = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _type = __webpack_require__(/*! ./type */ "./js/typeSystem/type.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var CompoundType = exports.CompoundType = function (_Type) {
  _inherits(CompoundType, _Type);

  function CompoundType(type, dimensions) {
    _classCallCheck(this, CompoundType);

    var _this = _possibleConstructorReturn(this, (CompoundType.__proto__ || Object.getPrototypeOf(CompoundType)).call(this, null));

    _this.innerType = type;
    _this.dimensions = dimensions;
    return _this;
  }

  _createClass(CompoundType, [{
    key: "isCompatible",
    value: function isCompatible(another) {
      if (another instanceof CompoundType) {
        if (this.dimensions !== another.dimensions) {
          return false;
        }
        return this.innerType.isCompatible(another.innerType);
      }
      return false;
    }
  }, {
    key: "stringInfo",
    value: function stringInfo() {
      var _this2 = this;

      var list = this.innerType.stringInfo();
      list.forEach(function (v) {
        v.dim = _this2.dimensions;
      });
      return list;
    }
  }, {
    key: "canAccept",
    value: function canAccept(another) {
      if (another instanceof CompoundType) {
        return this.dimensions > another.dimensions && this.innerType.isCompatible(another.innerType);
      } else {
        return this.innerType.isCompatible(another);
      }
    }
  }]);

  return CompoundType;
}(_type.Type);

/***/ }),

/***/ "./js/typeSystem/multiType.js":
/*!************************************!*\
  !*** ./js/typeSystem/multiType.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.MultiType = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _type = __webpack_require__(/*! ./type */ "./js/typeSystem/type.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MultiType = exports.MultiType = function (_Type) {
  _inherits(MultiType, _Type);

  function MultiType(types) {
    _classCallCheck(this, MultiType);

    var _this = _possibleConstructorReturn(this, (MultiType.__proto__ || Object.getPrototypeOf(MultiType)).call(this, null));

    _this.types = types;
    return _this;
  }

  _createClass(MultiType, [{
    key: "stringInfo",
    value: function stringInfo() {
      var list = [];
      for (var i = 0; i < this.types.length; i++) {
        var t = this.types[i];
        list = list.concat(t.stringInfo());
      }
      return list;
    }
  }, {
    key: "isCompatible",
    value: function isCompatible(another) {
      if (another instanceof _type.Type) {
        for (var i = 0; i < this.types.length; i++) {
          var t = this.types[i];
          if (another.isCompatible(t)) {
            return true;
          }
        }
      }
      return false;
    }
  }, {
    key: "value",
    get: function get() {
      return null;
    }
  }, {
    key: "ord",
    get: function get() {
      return null;
    }
  }]);

  return MultiType;
}(_type.Type);

/***/ }),

/***/ "./js/typeSystem/parsers.js":
/*!**********************************!*\
  !*** ./js/typeSystem/parsers.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.toInt = toInt;
exports.toString = toString;
exports.toReal = toReal;
exports.toBool = toBool;
exports.convertToString = convertToString;

var _languageService = __webpack_require__(/*! ../services/languageService */ "./js/services/languageService.js");

var _types = __webpack_require__(/*! ./types */ "./js/typeSystem/types.js");

var _decimal = __webpack_require__(/*! decimal.js */ "./node_modules/decimal.js/decimal.js");

var _decimal2 = _interopRequireDefault(_decimal);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function toInt(str) {
  return new _decimal2.default(str);
}

function toString(str) {
  var value = str.replace(/^"/, '');
  value = value.replace(/"$/, '');
  value = value.replace(/\\b/g, "\b");
  value = value.replace(/\\t/g, "\t");
  value = value.replace(/\\n/g, "\n");
  value = value.replace(/\\r/g, "\r");
  value = value.replace(/\\\"/g, "\"");
  value = value.replace(/\\\'/g, "\'");
  value = value.replace(/\\\\/g, "\\");
  return value;
}

function toReal(value) {
  return new _decimal2.default(value);
}

function toBool(str) {
  var val = "'" + str + "'";
  var lexer = _languageService.LanguageService.getCurrentLexer();
  var instance = new lexer(null);
  if (instance.literalNames[lexer.RK_TRUE] === val) {
    return true;
  } else if (instance.literalNames[lexer.RK_FALSE] === val) {
    return false;
  } else {
    // TODO: better error message
    throw new Error(str + "not a valid boolean");
  }
}

function convertBoolToString(bool) {
  var lexer = _languageService.LanguageService.getCurrentLexer();
  var instance = new lexer(null);
  if (bool) {
    return instance.literalNames[lexer.RK_TRUE];
  } else {
    return instance.literalNames[lexer.RK_FALSE];
  }
}

function convertToString(value, type) {
  switch (type.ord) {
    case _types.Types.INTEGER.ord:
      return value.toString();
    case _types.Types.REAL.ord:
      {
        if (value.dp() <= 0) {
          return value.toFixed(1);
        } else {
          return value.toNumber();
        }
      }
    case _types.Types.BOOLEAN.ord:
      return convertBoolToString(value);
    default:
      return value;
  }
}

/***/ }),

/***/ "./js/typeSystem/type.js":
/*!*******************************!*\
  !*** ./js/typeSystem/type.js ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Type = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _config = __webpack_require__(/*! ../util/config */ "./js/util/config.js");

var _baseTypes = __webpack_require__(/*! ./baseTypes */ "./js/typeSystem/baseTypes.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Type = exports.Type = function () {
  function Type(baseType) {
    _classCallCheck(this, Type);

    this.baseType = baseType;
  }

  _createClass(Type, [{
    key: "stringInfo",
    value: function stringInfo() {
      return [{ type: this.baseType.name, dim: 0 }];
    }
  }, {
    key: "isCompatible",
    value: function isCompatible(another) {
      if (another instanceof Type) {
        return this.baseType.isCompatible(another.baseType);
      }
      return false;
    }
  }, {
    key: "value",
    get: function get() {
      return this.baseType.value;
    }
  }, {
    key: "ord",
    get: function get() {
      return this.baseType.ord;
    }
  }]);

  return Type;
}();

/***/ }),

/***/ "./js/typeSystem/types.js":
/*!********************************!*\
  !*** ./js/typeSystem/types.js ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Types = undefined;

var _baseTypes = __webpack_require__(/*! ./baseTypes */ "./js/typeSystem/baseTypes.js");

var _type = __webpack_require__(/*! ./type */ "./js/typeSystem/type.js");

var _multiType = __webpack_require__(/*! ./multiType */ "./js/typeSystem/multiType.js");

var INTEGER = new _type.Type(_baseTypes.BaseTypes.INTEGER);
var REAL = new _type.Type(_baseTypes.BaseTypes.REAL);
var STRING = new _type.Type(_baseTypes.BaseTypes.STRING);
var BOOLEAN = new _type.Type(_baseTypes.BaseTypes.BOOLEAN);
var VOID = new _type.Type(_baseTypes.BaseTypes.VOID);
var UNDEFINED = new _type.Type(_baseTypes.BaseTypes.UNDEFINED);
var ALL = new _multiType.MultiType([INTEGER, REAL, STRING, BOOLEAN]);

var Types = exports.Types = Object.freeze({
  INTEGER: INTEGER,
  REAL: REAL,
  STRING: STRING,
  BOOLEAN: BOOLEAN,
  VOID: VOID,
  UNDEFINED: UNDEFINED,
  ALL: ALL
});

/***/ }),

/***/ "./js/util/config.js":
/*!***************************!*\
  !*** ./js/util/config.js ***!
  \***************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var ConfigObject = function () {
  function ConfigObject() {
    _classCallCheck(this, ConfigObject);

    this.loopTimeout = 5000;
    this.decimalPlaces = 5;
    this.intConvertRoundMode = 2;
    this.default_lang = 'pt';
    this.enable_type_casting = true;
  }

  _createClass(ConfigObject, [{
    key: 'setConfig',
    value: function setConfig(opts) {
      for (var key in opts) {
        if (this.hasOwnProperty(key)) {
          this[key] = opts[key];
        }
      }
    }
  }]);

  return ConfigObject;
}();

var config = new ConfigObject();
var Config = exports.Config = config;

/***/ }),

/***/ "./js/util/inputTest.js":
/*!******************************!*\
  !*** ./js/util/inputTest.js ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.InputTest = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _input = __webpack_require__(/*! ./../io/input */ "./js/io/input.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var InputTest = exports.InputTest = function (_Input) {
  _inherits(InputTest, _Input);

  function InputTest(inputList) {
    _classCallCheck(this, InputTest);

    var _this = _possibleConstructorReturn(this, (InputTest.__proto__ || Object.getPrototypeOf(InputTest)).call(this));

    _this.index = 0;
    _this.inputList = inputList;
    return _this;
  }

  _createClass(InputTest, [{
    key: 'requestInput',
    value: function requestInput(callback) {
      if (this.index < this.inputList.length) {
        callback(this.inputList[this.index]);
        this.index++;
      } else {
        throw new Error('The amount of requests exceeded the amount of available inputs');
      }
    }
  }]);

  return InputTest;
}(_input.Input);

/***/ }),

/***/ "./js/util/outputTest.js":
/*!*******************************!*\
  !*** ./js/util/outputTest.js ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.OutputTest = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _output = __webpack_require__(/*! ./../io/output */ "./js/io/output.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var OutputTest = exports.OutputTest = function (_Output) {
  _inherits(OutputTest, _Output);

  function OutputTest() {
    _classCallCheck(this, OutputTest);

    var _this = _possibleConstructorReturn(this, (OutputTest.__proto__ || Object.getPrototypeOf(OutputTest)).call(this));

    _this.list = [];
    return _this;
  }

  _createClass(OutputTest, [{
    key: 'sendOutput',
    value: function sendOutput(text) {
      this.list.push(text);
    }
  }]);

  return OutputTest;
}(_output.Output);

/***/ }),

/***/ "./js/visualUI/algorithm.js":
/*!**********************************!*\
  !*** ./js/visualUI/algorithm.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.renderAlgorithm = renderAlgorithm;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ./types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ./ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ./../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ./globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ./variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _commands = __webpack_require__(/*! ./commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

var _code_generator = __webpack_require__(/*! ./code_generator */ "./js/visualUI/code_generator.js");

var CodeManagement = _interopRequireWildcard(_code_generator);

var _variable_value_menu = __webpack_require__(/*! ./commands/variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenu = _interopRequireWildcard(_variable_value_menu);

var _functions = __webpack_require__(/*! ./functions */ "./js/visualUI/functions.js");

var FunctionsManagement = _interopRequireWildcard(_functions);

var _domConsole = __webpack_require__(/*! ./../io/domConsole */ "./js/io/domConsole.js");

var _ivprogParser = __webpack_require__(/*! ./../ast/ivprogParser */ "./js/ast/ivprogParser.js");

var _ivprogProcessor = __webpack_require__(/*! ./../processor/ivprogProcessor */ "./js/processor/ivprogProcessor.js");

var _languageService = __webpack_require__(/*! ../services/languageService */ "./js/services/languageService.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

window.block_render = false;

function renderAlgorithm() {
	if (window.block_render) {
		return;
	}
	window.block_render = true;

	(0, _jquery2.default)('.all_functions').children().off();
	(0, _jquery2.default)('.all_functions').empty();

	(0, _jquery2.default)('.list_globals').children().off();
	(0, _jquery2.default)('.list_globals').empty();

	for (var i = 0; i < window.program_obj.functions.length; i++) {
		FunctionsManagement.renderFunction(window.program_obj.functions[i]);
	}

	for (var i = 0; i < window.program_obj.globals.length; i++) {
		GlobalsManagement.renderGlobal(window.program_obj.globals[i]);
	}

	setTimeout(function () {
		window.block_render = false;
	}, 500);
}

/***/ }),

/***/ "./js/visualUI/code_generator.js":
/*!***************************************!*\
  !*** ./js/visualUI/code_generator.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.generate = generate;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ./types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ./ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ./../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ./globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ./variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _commands = __webpack_require__(/*! ./commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

var _utils = __webpack_require__(/*! ./utils */ "./js/visualUI/utils.js");

var Utils = _interopRequireWildcard(_utils);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function generate() {

	(0, _jquery2.default)('.ivprog_visual_panel').find('.error_icon').remove();

	var code = _localizedStringsService.LocalizedStrings.getUI('program') + ' { ';

	code += globalsCode();

	code += '\n';

	var has_error = false;

	for (var i = 0; i < window.program_obj.functions.length; i++) {
		var n_code = functionsCode(window.program_obj.functions[i]);
		if (n_code == null) {
			has_error = true;
		}
		code += n_code;
		code += '\n';
	}

	code += '\n}';

	if (has_error) {
		return null;
	} else {
		return code;
	}
}

function functionsCode(function_obj) {
	var ret = '\n\t' + _localizedStringsService.LocalizedStrings.getUI('function') + ' ';

	var has_error = false;

	switch (function_obj.return_type) {
		case _types.Types.INTEGER:
			ret += _localizedStringsService.LocalizedStrings.getUI('integer');
			break;
		case _types.Types.REAL:
			ret += _localizedStringsService.LocalizedStrings.getUI('real');
			break;
		case _types.Types.TEXT:
			ret += _localizedStringsService.LocalizedStrings.getUI('text');
			break;
		case _types.Types.BOOLEAN:
			ret += _localizedStringsService.LocalizedStrings.getUI('boolean');
			break;
		case _types.Types.VOID:
			ret += _localizedStringsService.LocalizedStrings.getUI('void');
			break;
	}
	ret += ' ';

	if (function_obj.return_dimensions == 1) {
		ret += '[] ';
	} else if (function_obj.return_dimensions == 2) {
		ret += '[][] ';
	}

	ret += function_obj.name + ' ( ';

	for (var j = 0; j < function_obj.parameters_list.length; j++) {
		ret += parametersCode(function_obj.parameters_list[j]);
		if (j + 1 < function_obj.parameters_list.length) {
			ret += ',';
		}
	}

	ret += ' )  {';

	for (var j = 0; j < function_obj.variables_list.length; j++) {
		ret += variablesCode(function_obj.variables_list[j]);
	}

	for (var j = 0; j < function_obj.commands.length; j++) {
		try {
			ret += commandsCode(function_obj.commands[j]);
		} catch (err) {

			has_error = true;

			console.error(err.message);

			var todos = (0, _jquery2.default)('body').find('.command_container');

			for (var i = 0; i < todos.length; i++) {
				if ((0, _jquery2.default)(todos[i]).data('command') == function_obj.commands[j]) {
					(0, _jquery2.default)(todos[i]).prepend(' <i class="ui icon red exclamation triangle error_icon"></i> ');
					break;
				}
			}
		}
	}

	ret += '\n\t}';

	if (has_error) {
		return null;
	} else {
		return ret;
	}
}

function commandsCode(command_obj) {
	var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;

	switch (command_obj.type) {
		case Models.COMMAND_TYPES.break:
			return breaksCode(command_obj, indentation);

		case Models.COMMAND_TYPES.comment:
			return commentsCode(command_obj, indentation);

		case Models.COMMAND_TYPES.reader:
			return readersCode(command_obj, indentation);

		case Models.COMMAND_TYPES.writer:
			return writersCode(command_obj, indentation);

		case Models.COMMAND_TYPES.functioncall:
			return functioncallsCode(command_obj, indentation);

		case Models.COMMAND_TYPES.attribution:
			return attributionsCode(command_obj, indentation);

		case Models.COMMAND_TYPES.whiletrue:
			return whiletruesCode(command_obj, indentation);

		case Models.COMMAND_TYPES.dowhiletrue:
			return doWhilesCode(command_obj, indentation);

		case Models.COMMAND_TYPES.iftrue:
			return iftruesCode(command_obj, indentation);

		case Models.COMMAND_TYPES.repeatNtimes:
			return repeatNtimesCode(command_obj, indentation);

		case Models.COMMAND_TYPES.switch:
			return switchsCode(command_obj, indentation);

		case Models.COMMAND_TYPES.return:
			return returnsCode(command_obj, indentation);
	}
}

function returnsCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += _localizedStringsService.LocalizedStrings.getUI('text_return');

	if (command_obj.variable_value_menu) {
		try {
			ret += ' ' + variableValueMenuCode(command_obj.variable_value_menu, true);
		} catch (err) {}
	}

	return ret;
}

function breaksCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += _localizedStringsService.LocalizedStrings.getUI('text_break');

	return ret;
}

function switchsCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += _localizedStringsService.LocalizedStrings.getUI('text_code_switch') + ' ( ';

	ret += variableValueMenuCode(command_obj.variable);

	ret += ' ) { ';

	if (command_obj.cases) {
		for (var i = 0; i < command_obj.cases.length; i++) {
			ret += switchcasesCode(command_obj.cases[i], indentation + 1);
		}
	}

	ret += '\n';
	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}
	ret += '} ';

	return ret;
}

function switchcasesCode(switchcase, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += _localizedStringsService.LocalizedStrings.getUI('text_code_case') + ' ';
	ret += variableValueMenuCode(switchcase.variable_value_menu);
	ret += ' :';

	if (switchcase.commands_block) {
		for (var i = 0; i < switchcase.commands_block.length; i++) {
			ret += commandsCode(switchcase.commands_block[i], indentation + 1);
		}
	}

	return ret;
}

function repeatNtimesCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += _localizedStringsService.LocalizedStrings.getUI('text_for') + ' ( ';

	if (command_obj.var_attribution) {
		ret += variableValueMenuCode(command_obj.var_attribution);
		ret += ' = ';
		ret += variableValueMenuCode(command_obj.expression1);
	}
	ret += ' ; ';

	if (command_obj.expression2) {
		switch (command_obj.expression2.expression.type) {
			case Models.EXPRESSION_TYPES.exp_logic:
				ret += logicExpressionCode(command_obj.expression2.expression);
				break;
			case Models.EXPRESSION_TYPES.exp_arithmetic:
				ret += arithmeticExpressionCode(command_obj.expression2.expression);
				break;
		}
	}

	ret += ' ; ';

	if (command_obj.var_incrementation) {
		ret += variableValueMenuCode(command_obj.var_incrementation);
		ret += ' = ';
		ret += variableValueMenuCode(command_obj.expression3.itens[0]);

		switch (command_obj.expression3.itens[1]) {
			case Models.ARITHMETIC_TYPES.plus:
				ret += ' + ';
				break;
			case Models.ARITHMETIC_TYPES.minus:
				ret += ' - ';
				break;
			case Models.ARITHMETIC_TYPES.multiplication:
				ret += ' * ';
				break;
			case Models.ARITHMETIC_TYPES.division:
				ret += ' / ';
				break;
			case Models.ARITHMETIC_TYPES.module:
				ret += ' % ';
				break;
		}

		ret += variableValueMenuCode(command_obj.expression3.itens[2]);
	}

	ret += ' )  { ';

	if (command_obj.commands_block) {
		for (var i = 0; i < command_obj.commands_block.length; i++) {
			ret += commandsCode(command_obj.commands_block[i], indentation + 1);
		}
	}

	ret += '\n';
	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += '}';
	return ret;
}

function iftruesCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += _localizedStringsService.LocalizedStrings.getUI('text_if');

	if (!command_obj.expression.expression) {
		Utils.renderErrorMessage(command_obj.expression.dom_object, _localizedStringsService.LocalizedStrings.getUI('inform_valid_expression'));
	}

	switch (command_obj.expression.expression.type) {
		case Models.EXPRESSION_TYPES.exp_logic:
			ret += logicExpressionCode(command_obj.expression.expression);
			break;
		case Models.EXPRESSION_TYPES.exp_arithmetic:
			ret += arithmeticExpressionCode(command_obj.expression.expression);
			break;
	}

	ret += ' { ';

	if (command_obj.commands_block) {
		for (var i = 0; i < command_obj.commands_block.length; i++) {
			ret += commandsCode(command_obj.commands_block[i], indentation + 1);
		}
	}

	ret += '\n';
	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += '} ' + _localizedStringsService.LocalizedStrings.getUI('text_else') + ' {';

	if (command_obj.commands_else) {
		for (var i = 0; i < command_obj.commands_else.length; i++) {
			ret += commandsCode(command_obj.commands_else[i], indentation + 1);
		}
	}

	ret += '\n';
	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += '}';

	return ret;
}

function doWhilesCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += _localizedStringsService.LocalizedStrings.getUI('text_code_do') + ' { ';

	if (command_obj.commands_block) {
		for (var i = 0; i < command_obj.commands_block.length; i++) {
			ret += commandsCode(command_obj.commands_block[i], indentation + 1);
		}
	}

	ret += '\n';
	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += '} ' + _localizedStringsService.LocalizedStrings.getUI('text_code_while');

	if (!command_obj.expression.expression) {
		Utils.renderErrorMessage(command_obj.expression.dom_object, _localizedStringsService.LocalizedStrings.getUI('inform_valid_expression'));
	}

	switch (command_obj.expression.expression.type) {
		case Models.EXPRESSION_TYPES.exp_logic:
			ret += logicExpressionCode(command_obj.expression.expression);
			break;
		case Models.EXPRESSION_TYPES.exp_arithmetic:
			ret += arithmeticExpressionCode(command_obj.expression.expression);
			break;
	}

	return ret;
}

function whiletruesCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += _localizedStringsService.LocalizedStrings.getUI('text_code_while');

	if (!command_obj.expression.expression) {
		Utils.renderErrorMessage(command_obj.expression.dom_object, _localizedStringsService.LocalizedStrings.getUI('inform_valid_expression'));
	}

	switch (command_obj.expression.expression.type) {
		case Models.EXPRESSION_TYPES.exp_logic:
			ret += logicExpressionCode(command_obj.expression.expression);
			break;
		case Models.EXPRESSION_TYPES.exp_arithmetic:
			ret += arithmeticExpressionCode(command_obj.expression.expression);
			break;
	}

	ret += ' { ';

	if (command_obj.commands_block) {
		for (var i = 0; i < command_obj.commands_block.length; i++) {
			ret += commandsCode(command_obj.commands_block[i], indentation + 1);
		}
	}

	ret += '\n';
	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += '}';

	return ret;
}

function logicExpressionCode(expression) {
	var ret = ' ( ';

	if (expression.first_operand.type == Models.EXPRESSION_TYPES.exp_logic) {
		ret += logicExpressionCode(expression.first_operand);
	} else if (expression.first_operand.type == Models.EXPRESSION_TYPES.exp_arithmetic) {
		ret += arithmeticExpressionCode(expression.first_operand);
	} else {
		ret += variableValueMenuCode(expression.first_operand);
	}

	if (expression.operator) {
		switch (expression.operator) {
			case Models.LOGIC_COMPARISON.equals_to:
				ret += ' == ';
				break;
			case Models.LOGIC_COMPARISON.not_equals_to:
				ret += ' != ';
				break;
			case Models.LOGIC_COMPARISON.and:
				ret += ' && ';
				break;
			case Models.LOGIC_COMPARISON.or:
				ret += ' || ';
				break;
		}

		if (expression.second_operand.type == Models.EXPRESSION_TYPES.exp_logic) {
			ret += logicExpressionCode(expression.second_operand);
		} else if (expression.second_operand.type == Models.EXPRESSION_TYPES.exp_arithmetic) {
			ret += arithmeticExpressionCode(expression.second_operand);
		} else {
			ret += variableValueMenuCode(expression.second_operand);
		}
	}

	ret += ' ) ';

	return ret;
}

function arithmeticExpressionCode(expression) {
	var ret = ' ( ';

	if (expression.first_operand.type == Models.EXPRESSION_TYPES.exp_logic) {
		ret += logicExpressionCode(expression.first_operand);
	} else if (expression.first_operand.type == Models.EXPRESSION_TYPES.exp_arithmetic) {
		ret += arithmeticExpressionCode(expression.first_operand);
	} else {
		ret += variableValueMenuCode(expression.first_operand);
	}

	switch (expression.operator) {
		case Models.ARITHMETIC_COMPARISON.greater_than:
			ret += ' > ';
			break;
		case Models.ARITHMETIC_COMPARISON.less_than:
			ret += ' < ';
			break;
		case Models.ARITHMETIC_COMPARISON.equals_to:
			ret += ' == ';
			break;
		case Models.ARITHMETIC_COMPARISON.not_equals_to:
			ret += ' != ';
			break;
		case Models.ARITHMETIC_COMPARISON.greater_than_or_equals_to:
			ret += ' >= ';
			break;
		case Models.ARITHMETIC_COMPARISON.less_than_or_equals_to:
			ret += ' <= ';
			break;
	}

	if (expression.second_operand.type == Models.EXPRESSION_TYPES.exp_logic) {
		ret += logicExpressionCode(expression.second_operand);
	} else if (expression.second_operand.type == Models.EXPRESSION_TYPES.exp_arithmetic) {
		ret += arithmeticExpressionCode(expression.second_operand);
	} else {
		ret += variableValueMenuCode(expression.second_operand);
	}

	ret += ' ) ';

	return ret;
}

function attributionsCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += variableValueMenuCode(command_obj.variable) + ' = ';

	for (var i = 0; i < command_obj.expression.length; i++) {
		ret += elementExpressionCode(command_obj.expression[i]);
	}

	return ret;
}

function elementExpressionCode(expression_obj) {

	var ret = '';

	for (var i = 0; i < expression_obj.itens.length; i++) {

		if (expression_obj.itens[i].type) {

			ret += variableValueMenuCode(expression_obj.itens[i]);
		} else if (expression_obj.itens[i].type_exp) {

			if (expression_obj.itens[i].type_exp == Models.EXPRESSION_ELEMENTS.par_exp_par) {
				ret += ' ( ';
			}

			ret += elementExpressionCode(expression_obj.itens[i]);

			if (expression_obj.itens[i].type_exp == Models.EXPRESSION_ELEMENTS.par_exp_par) {
				ret += ' ) ';
			}
		} else {

			switch (expression_obj.itens[i]) {
				case Models.ARITHMETIC_TYPES.plus:
					ret += ' + ';
					break;
				case Models.ARITHMETIC_TYPES.minus:
					ret += ' - ';
					break;
				case Models.ARITHMETIC_TYPES.multiplication:
					ret += ' * ';
					break;
				case Models.ARITHMETIC_TYPES.division:
					ret += ' / ';
					break;
				case Models.ARITHMETIC_TYPES.module:
					ret += ' % ';
					break;
			}
		}
	}

	return ret;
}

function functioncallsCode(command_obj, indentation) {

	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += variableValueMenuCode(command_obj.function_called);

	return ret;
}

function readersCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += _localizedStringsService.LocalizedStrings.getUI('text_command_read') + ' ( ';

	ret += variableValueMenuCode(command_obj.variable_value_menu);

	ret += ' ) ';
	return ret;
}

function variableValueMenuCode(variable_obj) {
	var is_return = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

	var ret = '';
	try {
		if (variable_obj.function_called) {

			if (variable_obj.function_called.name) {
				ret += variable_obj.function_called.name + ' ( ';
			} else {
				ret += _localizedStringsService.LocalizedStrings.getUI(variable_obj.function_called.category) + '.' + _localizedStringsService.LocalizedStrings.getUI(variable_obj.function_called.identifier) + ' ( ';
			}

			if (variable_obj.parameters_list) {
				for (var i = 0; i < variable_obj.parameters_list.length; i++) {
					ret += variableValueMenuCode(variable_obj.parameters_list[i]);
					if (i + 1 < variable_obj.parameters_list.length) {
						ret += ', ';
					}
				}
			}

			ret += ' )';
		} else if (variable_obj.content.type) {

			ret += variable_obj.content.name;

			if (variable_obj.content.dimensions == 1 && variable_obj.dimensions != 1) {
				ret += ' [ ' + variableValueMenuCode(variable_obj.column) + ' ] ';
			}

			if (variable_obj.content.dimensions == 2 && variable_obj.dimensions != 2) {
				ret += ' [ ' + variableValueMenuCode(variable_obj.row) + ' ] ';
				ret += ' [ ' + variableValueMenuCode(variable_obj.column) + ' ] ';
			}
		} else {
			if (isNaN(variable_obj.content)) {
				ret += '"' + variable_obj.content + '"';
			} else {
				ret += variable_obj.content;
			}
		}
	} catch (err) {

		if (!is_return) {
			Utils.renderErrorMessage(variable_obj.dom_object, _localizedStringsService.LocalizedStrings.getUI('inform_valid_content'));
			throw err;
		}
	}

	return ret;
}

function writersCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += _localizedStringsService.LocalizedStrings.getUI('text_command_write') + ' ( ';

	for (var i = 0; i < command_obj.content.length; i++) {
		ret += variableValueMenuCode(command_obj.content[i]);

		if (i + 1 < command_obj.content.length) {
			ret += ' + ';
		}
	}

	ret += ' ) ';
	return ret;
}

function commentsCode(command_obj, indentation) {
	var ret = '\n';

	for (var i = 0; i < indentation; i++) {
		ret += '\t';
	}

	ret += '// ';

	ret += command_obj.comment_text.content;
	return ret;
}

function parametersCode(parameter_obj) {
	var ret = '';
	switch (parameter_obj.type) {
		case _types.Types.INTEGER:
			ret += ' ' + _localizedStringsService.LocalizedStrings.getUI('integer') + ' ';
			break;
		case _types.Types.REAL:
			ret += ' ' + _localizedStringsService.LocalizedStrings.getUI('real') + ' ';
			break;
		case _types.Types.TEXT:
			ret += ' ' + _localizedStringsService.LocalizedStrings.getUI('text') + ' ';
			break;
		case _types.Types.BOOLEAN:
			ret += ' ' + _localizedStringsService.LocalizedStrings.getUI('boolean') + ' ';
			break;
	}
	ret += parameter_obj.name + '';

	if (parameter_obj.dimensions == 1) {
		ret += ' []';
	} else if (parameter_obj.dimensions == 2) {
		ret += ' [][]';
	}
	return ret;
}

function variablesCode(variable_obj) {
	var ret = '';

	var temp = variable_obj;

	ret += '\n\t\t';

	if (temp.is_constant) {
		ret += 'const ';
	}
	switch (temp.type) {
		case _types.Types.INTEGER:
			ret += _localizedStringsService.LocalizedStrings.getUI('integer') + ' ';
			break;
		case _types.Types.REAL:
			ret += _localizedStringsService.LocalizedStrings.getUI('real') + ' ';
			break;
		case _types.Types.TEXT:
			ret += _localizedStringsService.LocalizedStrings.getUI('text') + ' ';
			break;
		case _types.Types.BOOLEAN:
			ret += _localizedStringsService.LocalizedStrings.getUI('boolean') + ' ';
			break;
	}
	ret += temp.name + ' ';

	if (temp.dimensions == 1) {
		ret += '[' + temp.columns + '] ';

		switch (temp.type) {
			case _types.Types.INTEGER:
				ret += '= {' + temp.value + '}';
				break;
			case _types.Types.REAL:
				ret += '= {' + temp.value.toFixed(2) + '}';
				break;
			case _types.Types.TEXT:
				ret += '= {';
				for (var j = 0; j < temp.value.length; j++) {
					ret += '"' + temp.value[j] + '"';
					if (j + 1 < temp.value.length) {
						ret += ',';
					}
				}
				ret += '}';
				break;
			case _types.Types.BOOLEAN:
				ret += '= {';
				for (var j = 0; j < temp.value.length; j++) {
					if (temp.value[j]) {
						ret += _localizedStringsService.LocalizedStrings.getUI("true");
					} else {
						ret += _localizedStringsService.LocalizedStrings.getUI("false");
					}
					if (j + 1 < temp.value.length) {
						ret += ',';
					}
				}
				ret += '}';
				break;
		}
	} else if (temp.dimensions == 2) {
		ret += '[' + temp.rows + '][' + temp.columns + '] ';

		switch (temp.type) {
			case _types.Types.INTEGER:
				ret += '= {';

				for (var j = 0; j < temp.rows; j++) {
					ret += '{' + temp.value[j] + '}';

					if (j + 1 < temp.rows) {
						ret += ',';
					}
				}

				ret += '}';
				break;
			case _types.Types.REAL:
				ret += '= {';

				for (var j = 0; j < temp.rows; j++) {
					ret += '{' + temp.value[j].toFixed(2) + '}';

					if (j + 1 < temp.rows) {
						ret += ',';
					}
				}

				ret += '}';
				break;
			case _types.Types.TEXT:
				ret += '= {';

				for (var j = 0; j < temp.rows; j++) {
					ret += '{';

					for (var k = 0; k < temp.columns; k++) {
						ret += '"' + temp.value[j][k] + '"';

						if (k + 1 < temp.columns) {
							ret += ',';
						}
					}

					ret += '}';
					if (j + 1 < temp.rows) {
						ret += ',';
					}
				}
				ret += '}';
				break;
			case _types.Types.BOOLEAN:
				ret += '= {';
				for (var j = 0; j < temp.rows; j++) {
					ret += '{';

					for (var k = 0; k < temp.columns; k++) {

						if (temp.value[j][k]) {
							ret += _localizedStringsService.LocalizedStrings.getUI("true");
						} else {
							ret += _localizedStringsService.LocalizedStrings.getUI("false");
						}

						if (k + 1 < temp.columns) {
							ret += ',';
						}
					}

					ret += '}';
					if (j + 1 < temp.rows) {
						ret += ',';
					}
				}
				ret += '}';
				break;
		}
	} else {

		switch (temp.type) {
			case _types.Types.INTEGER:
				ret += '= ' + temp.value;
				break;
			case _types.Types.REAL:
				ret += '= ' + temp.value.toFixed(2);
				break;
			case _types.Types.TEXT:
				ret += '= "' + temp.value + '"';
				break;
			case _types.Types.BOOLEAN:
				ret += '= ';
				if (temp.value) {
					ret += _localizedStringsService.LocalizedStrings.getUI("true");
				} else {
					ret += _localizedStringsService.LocalizedStrings.getUI("false");
				}
				break;
		}
	}

	return ret;
}

function globalsCode() {
	var ret = '';

	if (window.program_obj.globals) {
		for (var i = 0; i < window.program_obj.globals.length; i++) {
			var temp = window.program_obj.globals[i];

			ret += '\n\t';

			if (temp.is_constant) {
				ret += 'const ';
			}
			switch (temp.type) {
				case _types.Types.INTEGER:
					ret += _localizedStringsService.LocalizedStrings.getUI('integer');
					break;
				case _types.Types.REAL:
					ret += _localizedStringsService.LocalizedStrings.getUI('real');
					break;
				case _types.Types.TEXT:
					ret += _localizedStringsService.LocalizedStrings.getUI('text');
					break;
				case _types.Types.BOOLEAN:
					ret += _localizedStringsService.LocalizedStrings.getUI('boolean');
					break;
			}
			ret += ' ' + temp.name + ' ';

			if (temp.dimensions == 1) {
				ret += '[' + temp.columns + '] ';

				switch (temp.type) {
					case _types.Types.INTEGER:
						ret += '= {' + temp.value + '}';
						break;
					case _types.Types.REAL:
						ret += '= {';
						for (var j = 0; j < temp.value.length; j++) {
							ret += temp.value[j].toFixed(2);
							if (j + 1 < temp.value.length) {
								ret += ',';
							}
						}
						ret += '}';
						break;
					case _types.Types.TEXT:
						ret += '= {';
						for (var j = 0; j < temp.value.length; j++) {
							ret += '"' + temp.value[j] + '"';
							if (j + 1 < temp.value.length) {
								ret += ',';
							}
						}
						ret += '}';
						break;
					case _types.Types.BOOLEAN:
						ret += '= {';
						for (var j = 0; j < temp.value.length; j++) {
							if (temp.value[j]) {
								ret += _localizedStringsService.LocalizedStrings.getUI("true");
							} else {
								ret += _localizedStringsService.LocalizedStrings.getUI("false");
							}
							if (j + 1 < temp.value.length) {
								ret += ',';
							}
						}
						ret += '}';
						break;
				}
			} else if (temp.dimensions == 2) {
				ret += '[' + temp.rows + '][' + temp.columns + '] ';

				switch (temp.type) {
					case _types.Types.INTEGER:
						ret += '= {';

						for (var j = 0; j < temp.rows; j++) {
							ret += '{' + temp.value[j] + '}';

							if (j + 1 < temp.rows) {
								ret += ',';
							}
						}

						ret += '}';
						break;
					case _types.Types.REAL:
						ret += '= {';

						for (var j = 0; j < temp.rows; j++) {
							ret += '{';

							for (var k = 0; k < temp.columns; k++) {
								ret += temp.value[j][k].toFixed(2);

								if (k + 1 < temp.columns) {
									ret += ',';
								}
							}

							ret += '}';
							if (j + 1 < temp.rows) {
								ret += ',';
							}
						}

						ret += '}';
						break;
					case _types.Types.TEXT:
						ret += '= {';

						for (var j = 0; j < temp.rows; j++) {
							ret += '{';

							for (var k = 0; k < temp.columns; k++) {
								ret += '"' + temp.value[j][k] + '"';

								if (k + 1 < temp.columns) {
									ret += ',';
								}
							}

							ret += '}';
							if (j + 1 < temp.rows) {
								ret += ',';
							}
						}
						ret += '}';
						break;
					case _types.Types.BOOLEAN:
						ret += '= {';
						for (var j = 0; j < temp.rows; j++) {
							ret += '{';

							for (var k = 0; k < temp.columns; k++) {

								if (temp.value[j][k]) {
									ret += _localizedStringsService.LocalizedStrings.getUI("true");
								} else {
									ret += _localizedStringsService.LocalizedStrings.getUI("false");
								}

								if (k + 1 < temp.columns) {
									ret += ',';
								}
							}

							ret += '}';
							if (j + 1 < temp.rows) {
								ret += ',';
							}
						}
						ret += '}';
						break;
				}
			} else {

				switch (temp.type) {
					case _types.Types.INTEGER:
						ret += '= ' + temp.value;
						break;
					case _types.Types.REAL:
						ret += '= ' + temp.value.toFixed(2);
						break;
					case _types.Types.TEXT:
						ret += '= "' + temp.value + '"';
						break;
					case _types.Types.BOOLEAN:
						ret += '= ';
						if (temp.value) {
							ret += _localizedStringsService.LocalizedStrings.getUI("true");;
						} else {
							ret += _localizedStringsService.LocalizedStrings.getUI("false");;
						}
						break;
				}
			}
		}
	}

	return ret;
}

/***/ }),

/***/ "./js/visualUI/commands.js":
/*!*********************************!*\
  !*** ./js/visualUI/commands.js ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.removeCommand = removeCommand;
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;
exports.genericCreateCommand = genericCreateCommand;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ./types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ./ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ./../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ./globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ./variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _comment = __webpack_require__(/*! ./commands/comment */ "./js/visualUI/commands/comment.js");

var CommentsManagement = _interopRequireWildcard(_comment);

var _reader = __webpack_require__(/*! ./commands/reader */ "./js/visualUI/commands/reader.js");

var ReadersManagement = _interopRequireWildcard(_reader);

var _writer = __webpack_require__(/*! ./commands/writer */ "./js/visualUI/commands/writer.js");

var WritersManagement = _interopRequireWildcard(_writer);

var _attribution = __webpack_require__(/*! ./commands/attribution */ "./js/visualUI/commands/attribution.js");

var AttributionsManagement = _interopRequireWildcard(_attribution);

var _iftrue = __webpack_require__(/*! ./commands/iftrue */ "./js/visualUI/commands/iftrue.js");

var IftruesManagement = _interopRequireWildcard(_iftrue);

var _repeatNtimes = __webpack_require__(/*! ./commands/repeatNtimes */ "./js/visualUI/commands/repeatNtimes.js");

var RepeatNtimesManagement = _interopRequireWildcard(_repeatNtimes);

var _whiletrue = __webpack_require__(/*! ./commands/whiletrue */ "./js/visualUI/commands/whiletrue.js");

var WhiletruesManagement = _interopRequireWildcard(_whiletrue);

var _dowhiletrue = __webpack_require__(/*! ./commands/dowhiletrue */ "./js/visualUI/commands/dowhiletrue.js");

var DowhiletruesManagement = _interopRequireWildcard(_dowhiletrue);

var _switch = __webpack_require__(/*! ./commands/switch */ "./js/visualUI/commands/switch.js");

var SwitchesManagement = _interopRequireWildcard(_switch);

var _functioncall = __webpack_require__(/*! ./commands/functioncall */ "./js/visualUI/commands/functioncall.js");

var FunctioncallsManagement = _interopRequireWildcard(_functioncall);

var _variable_value_menu = __webpack_require__(/*! ./commands/variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenuManagement = _interopRequireWildcard(_variable_value_menu);

var _break = __webpack_require__(/*! ./commands/break */ "./js/visualUI/commands/break.js");

var BreaksManagement = _interopRequireWildcard(_break);

var _return = __webpack_require__(/*! ./commands/return */ "./js/visualUI/commands/return.js");

var ReturnsManagement = _interopRequireWildcard(_return);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var has_element_created_draged = false;
var which_element_is_draged = null;

function removeCommand(command, function_obj, dom_obj) {
	if (function_obj.commands.indexOf(command) > -1) {
		function_obj.commands.splice(function_obj.commands.indexOf(command), 1);
		return true;
	}

	// Utilize dois parantNode, pois o primeiro é o div de comandos
	try {
		if (dom_obj.parent().parent().data('command').commands_block.indexOf(command) > -1) {
			dom_obj.parent().parent().data('command').commands_block.splice(dom_obj.parent().parent().data('command').commands_block.indexOf(command), 1);
			return true;
		}
	} catch (err) {}

	try {
		if (dom_obj.parent().parent().data('command').type == Models.COMMAND_TYPES.iftrue) {
			if (dom_obj.parent().parent().data('command').commands_else.indexOf(command) > -1) {
				dom_obj.parent().parent().data('command').commands_else.splice(dom_obj.parent().parent().data('command').commands_else.indexOf(command), 1);
				return true;
			}
		}
	} catch (err) {}

	if (dom_obj.parent().data('switchcase')) {
		console.log("o que encontrei: ");
		console.log(dom_obj.parent().data('switchcase'));
		dom_obj.parent().data('switchcase').commands_block.splice(dom_obj.parent().data('switchcase').commands_block.indexOf(command), 1);
		return true;
	}

	return false;
}

function createFloatingCommand(function_obj, function_container, command_type, mouse_event) {
	var floatingObject;

	switch (command_type) {
		case Models.COMMAND_TYPES.break:
			floatingObject = BreaksManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.comment:
			floatingObject = CommentsManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.reader:
			floatingObject = ReadersManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.writer:
			floatingObject = WritersManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.attribution:
			floatingObject = AttributionsManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.iftrue:
			floatingObject = IftruesManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.repeatNtimes:
			floatingObject = RepeatNtimesManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.whiletrue:
			floatingObject = WhiletruesManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.dowhiletrue:
			floatingObject = DowhiletruesManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.switch:
			floatingObject = SwitchesManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.functioncall:
			floatingObject = FunctioncallsManagement.createFloatingCommand();
			break;

		case Models.COMMAND_TYPES.return:
			floatingObject = ReturnsManagement.createFloatingCommand();
			break;
	}

	floatingObject.draggable({
		drag: function drag(evt) {
			borderMouseDragCommand(function_obj, function_container, evt);
		},
		stop: function stop(evt) {
			function_container.find('.over_command_drag').each(function (index) {
				(0, _jquery2.default)(this).removeClass('over_command_drag');
			});
		}
	}).appendTo("body");

	floatingObject.mouseup(function (evt) {
		manageCommand(function_obj, function_container, evt, command_type);
	});

	floatingObject.css("position", "absolute");
	mouse_event.type = "mousedown.draggable";
	mouse_event.target = floatingObject[0];
	floatingObject.css("left", mouse_event.pageX - 15);
	floatingObject.css("top", mouse_event.pageY - 15);
	floatingObject.trigger(mouse_event);
}

function borderMouseDragCommand(function_obj, function_container, evt) {

	function_container.find('.over_command_drag').each(function (index) {
		(0, _jquery2.default)(this).removeClass('over_command_drag');
	});

	var prev = null;

	function_container.find('.commands_list_div').each(function (index) {
		prev = (0, _jquery2.default)(this);
		if (prev) {
			var objLeft = prev.offset().left;
			var objTop = prev.offset().top;
			var objRight = objLeft + prev.width();
			var objBottom = objTop + prev.height();
			if (evt.pageX > objLeft && evt.pageX < objRight && evt.pageY > objTop && evt.pageY < objBottom) {
				prev.addClass("over_command_drag");
			}
		}
	});

	function_container.find('.command_container').each(function (index) {
		var obj = (0, _jquery2.default)(this);
		var objLeft = obj.offset().left;
		var objTop = obj.offset().top;
		var objRight = objLeft + obj.width();
		var objBottom = objTop + obj.height();
		if (evt.pageX > objLeft && evt.pageX < objRight && evt.pageY > objTop && evt.pageY < objBottom) {
			if (prev) {
				prev.removeClass('over_command_drag');
			}
			obj.addClass("over_command_drag");
			return;
		}
	});
}

// before_after_inside: 1 -> before, 2 -> after, 3 -> inside
function renderCommand(command, element_reference, before_after_inside, function_obj) {
	var createdElement;
	switch (command.type) {
		case Models.COMMAND_TYPES.comment:
			createdElement = CommentsManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.break:
			createdElement = BreaksManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.reader:
			createdElement = ReadersManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.writer:
			createdElement = WritersManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.attribution:
			createdElement = AttributionsManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.functioncall:
			createdElement = FunctioncallsManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.iftrue:
			createdElement = IftruesManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.repeatNtimes:
			createdElement = RepeatNtimesManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.whiletrue:
			createdElement = WhiletruesManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.dowhiletrue:
			createdElement = DowhiletruesManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.switch:
			createdElement = SwitchesManagement.renderCommand(command, function_obj);
			break;

		case Models.COMMAND_TYPES.return:
			createdElement = ReturnsManagement.renderCommand(command, function_obj);
			break;

	}

	switch (before_after_inside) {
		case 1:
			createdElement.insertBefore(element_reference);
			break;

		case 2:
			createdElement.insertAfter(element_reference);
			break;

		case 3:
			element_reference.append(createdElement);
			break;
	}

	createdElement.find('.button_remove_command').mouseover(function () {
		createdElement.css({ 'opacity': '.8' });
	});
	createdElement.find('.button_remove_command').mouseout(function () {
		createdElement.css({ 'opacity': '1' });
	});
}

function genericCreateCommand(command_type) {

	switch (command_type) {

		case Models.COMMAND_TYPES.break:
			return new Models.Break();

		case Models.COMMAND_TYPES.comment:
			return new Models.Comment(new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.only_value, _localizedStringsService.LocalizedStrings.getUI('text_comment'), null, null, false));

		case Models.COMMAND_TYPES.reader:
			return new Models.Reader(new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.only_variable, null, null, null, false));

		case Models.COMMAND_TYPES.writer:
			return new Models.Writer([new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true)]);

		case Models.COMMAND_TYPES.attribution:
			return new Models.Attribution(new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.only_variable, null, null, null, false), []);

		case Models.COMMAND_TYPES.functioncall:
			return new Models.FunctionCall(new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.only_function, null, null, null, false), null);

		case Models.COMMAND_TYPES.iftrue:
			return new Models.IfTrue(new Models.ConditionalExpression(null), null, null);

		case Models.COMMAND_TYPES.repeatNtimes:
			return new Models.RepeatNTimes(new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.only_variable, null, null, null, false), new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.only_variable, null, null, null, false), null, new Models.ConditionalExpression(null), null, null);

		case Models.COMMAND_TYPES.whiletrue:
			return new Models.WhileTrue(new Models.ConditionalExpression(null), null);

		case Models.COMMAND_TYPES.dowhiletrue:
			return new Models.DoWhileTrue(new Models.ConditionalExpression(null), null);

		case Models.COMMAND_TYPES.switch:

			var sc = [new Models.SwitchCase(new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true))];

			return new Models.Switch(new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true), sc);

		case Models.COMMAND_TYPES.return:
			return new Models.Return(new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true));
	}
}

function dragTrash(event) {

	var trash = (0, _jquery2.default)('<i class="ui icon trash alternate outline"></i>');
	(0, _jquery2.default)('body').append(trash);
	trash.css('position', 'absolute');
	trash.css('top', event.clientY);
	trash.css('left', event.clientX - 20);
	trash.css('font-size', '3em');
	trash.css('display', 'none');

	trash.fadeIn(200, function () {
		trash.fadeOut(200, function () {
			trash.remove();
		});
	});
}

function manageCommand(function_obj, function_container, event, command_type) {

	(0, _jquery2.default)(".created_element").each(function (index) {
		(0, _jquery2.default)(this).remove();
	});

	var el = (0, _jquery2.default)(document.elementFromPoint(event.clientX, event.clientY));
	console.log('soltou no: ');
	console.log(el);
	console.log(el.data('fun'));

	// Primeiro verificar se ele soltou no espaço da função correta:
	var hier = el.parentsUntil(".all_functions");
	var esta_correto = false;
	var esta_na_div_correta = false;
	if (el.hasClass("commands_list_div")) {
		esta_na_div_correta = true;
	}
	for (var i = 0; i < hier.length; i++) {
		var temp = (0, _jquery2.default)(hier[i]);
		if (temp.hasClass("commands_list_div")) {
			esta_na_div_correta = true;
		}
		if (temp.data('fun') == function_obj) {
			esta_correto = true;
			break;
		}
	}
	if (!esta_correto) {
		has_element_created_draged = false;
		which_element_is_draged = null;
		dragTrash(event);
		return;
	} else {
		if (!esta_na_div_correta) {
			has_element_created_draged = false;
			which_element_is_draged = null;
			dragTrash(event);
			return;
		}
	}

	// Agora é descobrir qual o escopo para adicionar o comando:

	// Se o elemento clicado possuir o atributo "fun", então, é direto na div dos comandos:
	if (typeof el.data('fun') !== 'undefined') {

		// Se a lista de comandos estiver vazia, então é o primeiro.
		// Portanto, ele deve soltar o elemento obrigatoriamente no objeto vazio
		if (el.data('fun').commands == null || el.data('fun').commands.length == 0) {
			// pode adicionar 
			el.data('fun').commands = [];

			var new_cmd = genericCreateCommand(command_type);

			el.data('fun').commands.push(new_cmd);

			renderCommand(new_cmd, (0, _jquery2.default)(function_container).find('.commands_list_div'), 3, function_obj);
		} else {
			// Entra nesse else, caso já existam outros comandos no bloco:

			findNearbyCommandToAddInFunctionScope(el, event, (0, _jquery2.default)(function_container).find('.commands_list_div'), function_obj, command_type);
		}
	} else {
		console.log("soltou em um comando");
		// descobrir em qual comando ele soltou: 
		var hier_find = el.parentsUntil(".commands_list_div");
		var hierarquia_bottom_up = [];
		if (typeof el.data('command') !== 'undefined') {
			hierarquia_bottom_up.push(el.data('command'));
		}
		for (var i = 0; i < hier_find.length; i++) {
			if (typeof (0, _jquery2.default)(hier_find[i]).data('command') !== 'undefined') {
				hierarquia_bottom_up.push((0, _jquery2.default)(hier_find[i]).data('command'));
			}
		}
		console.log("comando em que soltou: ");
		console.log(hierarquia_bottom_up[0]);
		console.log("hierarquia de baixo para cima na árvore, de onde ele soltou: ");
		for (var i = 0; i < hierarquia_bottom_up.length; i++) {
			console.log(hierarquia_bottom_up[i]);
		}

		// Se for do tipo break, verificar se está no contexto correto: 
		// Caso não esteja no contexto, apenas retorna sem dar continuidade:
		var is_correct_context = false;
		if (command_type == Models.COMMAND_TYPES.break) {
			for (var i = 0; i < hierarquia_bottom_up.length; i++) {
				if (hierarquia_bottom_up[i].type == Models.COMMAND_TYPES.repeatNtimes || hierarquia_bottom_up[i].type == Models.COMMAND_TYPES.whiletrue || hierarquia_bottom_up[i].type == Models.COMMAND_TYPES.dowhiletrue || hierarquia_bottom_up[i].type == Models.COMMAND_TYPES.switch) {

					is_correct_context = true;
					break;
				}
			}

			if (!is_correct_context) {
				console.error("Context not allowed to insert BREAK COMMAND!");
				return;
			}
		}

		// se a hierarquia possuir apenas um elemento, então está na raiz dos comandos: 
		if (hierarquia_bottom_up.length == 1) {
			console.log('QQ1');
			var sub_elemento = false;
			for (var i = 0; i < hier_find.length; i++) {
				if (typeof (0, _jquery2.default)(hier_find[i]).data('command') !== 'undefined') {
					console.log('QQ2');
					findBeforeOrAfterCommandToAdd(hier_find[i], event, function_obj, command_type);
					sub_elemento = true;
					break;
				}
			}
			if (!sub_elemento) {
				console.log('QQ3');
				findBeforeOrAfterCommandToAdd(el[0], event, function_obj, command_type);
			}
		} else {
			console.log('QQ4');
			// caso exista mais de um elemento na hierarquia:
			if (typeof (0, _jquery2.default)(el).data('command') !== 'undefined') {
				console.log('QQ5');
				console.log("PPP1");
				insertCommandInBlockHierar(el[0], event, function_obj, command_type, hier_find, hierarquia_bottom_up);
			} else {
				console.log('QQ6');
				var sub_elemento = false;
				for (var i = 0; i < hier_find.length; i++) {
					if (typeof (0, _jquery2.default)(hier_find[i]).data('command') !== 'undefined') {
						console.log('QQ7');
						insertCommandInBlockHierar(hier_find[i], event, function_obj, command_type, hier_find, hierarquia_bottom_up);
						sub_elemento = true;
						break;
					}
				}
			}
		}
	}

	has_element_created_draged = false;
	which_element_is_draged = null;
}

function insertCommandInBlockHierar(el, event, function_obj, command_type, hier_dom, hier_obj) {
	var el_jq = (0, _jquery2.default)(el);
	var command_parent = el_jq.data('command');

	if (el_jq.data('command').type == Models.COMMAND_TYPES.repeatNtimes || el_jq.data('command').type == Models.COMMAND_TYPES.whiletrue || el_jq.data('command').type == Models.COMMAND_TYPES.dowhiletrue || el_jq.data('command').type == Models.COMMAND_TYPES.switch) {

		console.log('QQ17');

		if (el_jq.data('command').type == Models.COMMAND_TYPES.repeatNtimes || el_jq.data('command').type == Models.COMMAND_TYPES.whiletrue || el_jq.data('command').type == Models.COMMAND_TYPES.dowhiletrue) {

			console.log('QQ18');

			// Se não tiver outro comando ainda no bloco, só adiciona: 
			if (command_parent.commands_block == null || command_parent.commands_block.length == 0) {
				command_parent.commands_block = [];

				var recentComand = genericCreateCommand(command_type);
				command_parent.commands_block.push(recentComand);

				renderCommand(recentComand, el_jq.find('.block_commands'), 3, function_obj);
			} else {
				// Se já tem algum comando no bloco:
				findNearbyCommandToAddInBlockScope(el, event, el, function_obj, command_type, command_parent);
			}
		} else {
			// QUANDO FOR BLOCO DO TIPO IF OU SWITCH/CASE:
			addCommandToSwitchCase(event, function_obj, command_type);
		}
	} else {
		console.log('QQ19');
		// entra neste bloco, se soltou o comando sobre outro comando dentro de um subbloco:
		findBeforeOrAfterCommandToAddInsertBlock(el, event, function_obj, command_type);
	}
}

function findNearbyCommandToAddInBlockScope(el, event, node_list_commands, function_obj, command_type, command_parent) {

	var all_sub = (0, _jquery2.default)(node_list_commands).find('div.command_container');

	var menor_distancia = 999999999;
	var elemento_menor_distancia = null;
	var antes = true;

	var t_bot;
	var t_top;

	// Descobrindo o elemento mais próximo:
	for (var i = 0; i < all_sub.length; i++) {

		t_top = all_sub[i].getBoundingClientRect().top;
		t_bot = all_sub[i].getBoundingClientRect().top + all_sub[i].getBoundingClientRect().height;

		if (t_top - event.clientY < menor_distancia) {
			menor_distancia = event.clientY - t_top;
			elemento_menor_distancia = all_sub[i];
		}
	}

	var borda_inferior = elemento_menor_distancia.parentNode.getBoundingClientRect().top + elemento_menor_distancia.parentNode.getBoundingClientRect().height;

	// Está mais próximo da borda de baixo, ou seja.. inserir por último:
	if (borda_inferior - event.clientY < menor_distancia) {

		var recentComand = genericCreateCommand(command_type);
		command_parent.commands_block.push(recentComand);
		//
		renderCommand(recentComand, node_list_commands, 3, function_obj);
	} else {

		var recentComand = genericCreateCommand(command_type);

		var index = command_parent.commands_block.indexOf((0, _jquery2.default)(elemento_menor_distancia).data('command'));

		if (index > -1) {
			command_parent.commands_block.splice(index, 0, recentComand);
		}

		renderCommand(recentComand, elemento_menor_distancia, 1, function_obj);
	}
}

function findBeforeOrAfterCommandToAddInsertBlock(el, event, function_obj, command_type) {

	var el_jq = (0, _jquery2.default)(el);
	var command_parent = (0, _jquery2.default)(el.parentNode.parentNode).data('command');
	var command_target = el_jq.data('command');
	var temp_parent = (0, _jquery2.default)(el.parentNode.parentNode);

	var is_in_else = false;

	if (!command_parent) {
		command_parent = el_jq.data('command');
		temp_parent = el_jq;
		var hier = el_jq.parentsUntil(".command_container");

		for (var i = 0; i < hier.length; i++) {
			var temp = (0, _jquery2.default)(hier[i]);
			if (typeof temp.data('else') != 'undefined') {
				is_in_else = true;
			}
			if (typeof temp.data('command') != 'undefined') {
				command_parent = temp.data('command');
				temp_parent = temp;
			}
		}
	}

	var hier = el_jq.parentsUntil(".command_container");
	for (var i = 0; i < hier.length; i++) {
		var temp = (0, _jquery2.default)(hier[i]);
		if (typeof temp.data('else') != 'undefined') {
			is_in_else = true;
		}
	}

	if (command_parent == command_target) {
		var hier = el_jq.parentsUntil(".command_container");

		for (var i = 0; i < hier.length; i++) {
			var temp = (0, _jquery2.default)(hier[i]);
			if (typeof temp.data('else') !== 'undefined') {
				is_in_else = true;
				break;
			}
		}
	}

	if (command_parent.type != Models.COMMAND_TYPES.iftrue && command_parent.type != Models.COMMAND_TYPES.switch) {
		var hier = temp_parent.parentsUntil(".all_cases_div");
		console.log("vou procurar!!");
		for (var i = 0; i < hier.length; i++) {
			console.log("estou vasculhando...");
			var temp = (0, _jquery2.default)(hier[i]);
			if (typeof temp.data('switchcase') !== 'undefined') {
				console.log("encontrei");
				command_parent = temp.data('switchcase');
				is_in_else = false;
				break;
			}
		}
	}

	console.log('debugging:');
	console.log('el_jq');
	console.log(el_jq);
	console.log('command_parent');
	console.log(command_parent);
	console.log('command_target');
	console.log(command_target);

	var menor_distancia = 999999999;
	var antes = true;

	var t_bot;
	var t_top;

	t_top = el.getBoundingClientRect().top;
	t_bot = el.getBoundingClientRect().top + el.getBoundingClientRect().height;

	var d_top = event.clientY - t_top; // distancia topo
	var d_bot = t_bot - event.clientY; // distancia baixo

	// Está mais próximo da borda de baixo, ou seja.. inserir por último:

	if (d_top < d_bot) {

		var recentComand = genericCreateCommand(command_type);

		console.log('MMM1');

		if (is_in_else) {

			console.log('MMM2');

			if (command_parent == command_target) {
				console.log('MMM3');
				if (command_parent.commands_else == null || command_parent.commands_else.length == 0) {
					command_parent.commands_else = [];

					var recentComand = genericCreateCommand(command_type);
					command_parent.commands_else.push(recentComand);

					renderCommand(recentComand, el_jq, 3, function_obj);
				} else {
					// Se já tem algum comando no bloco:
					findInBlockCorrectPlace(el_jq, event, function_obj, command_type, true);
				}
				return;
			}
			console.log('MMM7');
			var index = command_parent.commands_else.indexOf(command_target);

			if (index > -1) {
				command_parent.commands_else.splice(index, 0, recentComand);
			}

			renderCommand(recentComand, el, 1, function_obj);
		} else {
			console.log('MMM4');
			if (command_parent == command_target) {
				console.log('Nxxxx5');
				if (command_parent.commands_block == null || command_parent.commands_block.length == 0) {
					command_parent.commands_block = [];
					console.log('SSS4');
					var recentComand = genericCreateCommand(command_type);
					command_parent.commands_block.push(recentComand);

					renderCommand(recentComand, el_jq, 3, function_obj);
				} else {
					console.log('SSS5');
					findInBlockCorrectPlace(el_jq, event, function_obj, command_type);
				}

				return;
			}
			console.log('MMM6');

			var index = command_parent.commands_block.indexOf(command_target);

			if (index > -1) {
				command_parent.commands_block.splice(index, 0, recentComand);
			}

			renderCommand(recentComand, el, 1, function_obj);
		}
	} else {
		console.log('XXX1');
		var recentComand = genericCreateCommand(command_type);

		if (is_in_else) {

			if (command_parent == command_target) {
				console.log('MMM3');
				if (command_parent.commands_else == null || command_parent.commands_else.length == 0) {
					command_parent.commands_else = [];
					console.log('SSS1');
					var recentComand = genericCreateCommand(command_type);
					command_parent.commands_else.push(recentComand);

					renderCommand(recentComand, el_jq, 3, function_obj);
				} else {
					// Se já tem algum comando no bloco:
					console.log('SSS2');
					findInBlockCorrectPlace(el_jq, event, function_obj, command_type, true);
				}
				return;
			}

			console.log('XXX2');
			var index = command_parent.commands_else.indexOf(command_target);

			if (index > -1) {
				command_parent.commands_else.splice(index + 1, 0, recentComand);
			}

			renderCommand(recentComand, el, 2, function_obj);
		} else {

			if (command_parent == command_target) {
				console.log('Nxxxx78');
				if (command_parent.commands_block == null || command_parent.commands_block.length == 0) {
					command_parent.commands_block = [];

					var recentComand = genericCreateCommand(command_type);
					command_parent.commands_block.push(recentComand);
					console.log('SSS6');
					renderCommand(recentComand, el_jq, 3, function_obj);
				} else {
					console.log('SSS7');
					findInBlockCorrectPlace(el_jq, event, function_obj, command_type);
				}

				return;
			}

			console.log('XXX3');
			var index = command_parent.commands_block.indexOf(command_target);

			if (index > -1) {
				command_parent.commands_block.splice(index + 1, 0, recentComand);
			}

			renderCommand(recentComand, el, 2, function_obj);
		}
	}
}

function insertCommandInBlock(el, event, function_obj, command_type) {
	var el_jq = (0, _jquery2.default)(el);
	var command_parent = el_jq.data('command');

	if (el_jq.data('command').type == Models.COMMAND_TYPES.repeatNtimes || el_jq.data('command').type == Models.COMMAND_TYPES.whiletrue || el_jq.data('command').type == Models.COMMAND_TYPES.dowhiletrue) {

		// Se não tiver outro comando ainda no bloco, só adiciona: 
		if (command_parent.commands_block == null || command_parent.commands_block.length == 0) {
			command_parent.commands_block = [];

			var recentComand = genericCreateCommand(command_type);
			command_parent.commands_block.push(recentComand);

			renderCommand(recentComand, el_jq.find('.block_commands'), 3, function_obj);
		} else {
			// Se já tem algum comando no bloco:
			findInBlockCorrectPlace(el, event, function_obj, command_type);
		}
	} else if (el_jq.data('command').type == Models.COMMAND_TYPES.iftrue) {

		console.log('QQ9');

		// no if ou no else?
		var correct_div = (0, _jquery2.default)(document.elementFromPoint(event.pageX, event.pageY));
		var is_in_if = true;
		if (correct_div.data('if')) {
			is_in_if = true;
		} else if (correct_div.data('else')) {
			is_in_if = false;
		} else {
			var hier = correct_div.parentsUntil(".command_container");
			for (var i = 0; i < hier.length; i++) {
				var temp = (0, _jquery2.default)(hier[i]);
				if (typeof temp.data('if') !== 'undefined') {
					is_in_if = true;
					break;
				}
				if (typeof temp.data('else') !== 'undefined') {
					is_in_if = false;
					break;
				}
			}
		}

		if (is_in_if) {
			if (command_parent.commands_block == null || command_parent.commands_block.length == 0) {
				command_parent.commands_block = [];

				var recentComand = genericCreateCommand(command_type);
				command_parent.commands_block.push(recentComand);

				renderCommand(recentComand, el_jq.find('.commands_if'), 3, function_obj);
			} else {
				// Se já tem algum comando no bloco:
				findInBlockCorrectPlace(el_jq.find('.commands_if'), event, function_obj, command_type);
			}
		} else {
			if (command_parent.commands_else == null || command_parent.commands_else.length == 0) {
				command_parent.commands_else = [];

				var recentComand = genericCreateCommand(command_type);
				command_parent.commands_else.push(recentComand);

				renderCommand(recentComand, el_jq.find('.commands_else'), 3, function_obj);
			} else {
				// Se já tem algum comando no bloco:
				findInBlockCorrectPlace(el_jq.find('.commands_else'), event, function_obj, command_type, true);
			}
		}
	} else {
		// é do tipo switch
		console.log("está tentando inserir em um switch que está na raiz!");
		addCommandToSwitchCase(event, function_obj, command_type);
	}
}

function addCommandToSwitchCase(event, function_obj, command_type) {

	var el = (0, _jquery2.default)(document.elementFromPoint(event.clientX, event.clientY));

	var which_case = el.data('switchcase');
	var case_div = el;

	if (!which_case) {
		var hier_find = el.parentsUntil(".all_cases_div");
		for (var i = 0; i < hier_find.length; i++) {
			if (typeof (0, _jquery2.default)(hier_find[i]).data('switchcase') !== 'undefined') {
				which_case = (0, _jquery2.default)(hier_find[i]).data('switchcase');
				case_div = (0, _jquery2.default)(hier_find[i]);
				break;
			}
		}
	}

	if (which_case.commands_block == null || which_case.commands_block.length < 1) {
		which_case.commands_block = [];

		var recentComand = genericCreateCommand(command_type);
		which_case.commands_block.push(recentComand);
		renderCommand(recentComand, case_div.find('.case_commands_block'), 3, function_obj);
	} else {
		findInBlockCorrectPlaceInSwitchCase(which_case, case_div, event, function_obj, command_type);
	}
}

function findInBlockCorrectPlaceInSwitchCase(which_case, case_div, event, function_obj, command_type) {

	var all_sub = case_div.find('div.command_container');

	var menor_distancia = 999999999;
	var elemento_menor_distancia = null;
	var antes = true;

	var t_bot;
	var t_top;

	// Descobrindo o elemento mais próximo:
	for (var i = 0; i < all_sub.length; i++) {

		t_top = all_sub[i].getBoundingClientRect().top;
		t_bot = all_sub[i].getBoundingClientRect().top + all_sub[i].getBoundingClientRect().height;

		if (t_top - event.clientY < menor_distancia) {
			menor_distancia = event.clientY - t_top;
			elemento_menor_distancia = all_sub[i];
		}
	}

	var borda_inferior = elemento_menor_distancia.parentNode.getBoundingClientRect().top + elemento_menor_distancia.parentNode.getBoundingClientRect().height;

	// Está mais próximo da borda de baixo, ou seja.. inserir por último:
	if (borda_inferior - event.clientY < menor_distancia) {
		var recentComand = genericCreateCommand(command_type);

		which_case.commands_block.push(recentComand);

		renderCommand(recentComand, (0, _jquery2.default)(case_div.find('.case_commands_block')[0]), 3, function_obj);
	} else {

		var recentComand = genericCreateCommand(command_type);

		var index = which_case.commands_block.indexOf((0, _jquery2.default)(elemento_menor_distancia).data('command'));

		if (index > -1) {
			which_case.commands_block.splice(index, 0, recentComand);
			renderCommand(recentComand, elemento_menor_distancia, 1, function_obj);
		}
	}
}

function findInBlockCorrectPlace(el, event, function_obj, command_type) {
	var is_in_else = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;

	var el_jq = (0, _jquery2.default)(el);
	var all_sub = el_jq.find('div.command_container');

	var menor_distancia = 999999999;
	var elemento_menor_distancia = null;
	var antes = true;

	var t_bot;
	var t_top;

	// Descobrindo o elemento mais próximo:
	for (var i = 0; i < all_sub.length; i++) {

		t_top = all_sub[i].getBoundingClientRect().top;
		t_bot = all_sub[i].getBoundingClientRect().top + all_sub[i].getBoundingClientRect().height;

		if (t_top - event.clientY < menor_distancia) {
			menor_distancia = event.clientY - t_top;
			elemento_menor_distancia = all_sub[i];
		}
	}

	var borda_inferior = elemento_menor_distancia.parentNode.getBoundingClientRect().top + elemento_menor_distancia.parentNode.getBoundingClientRect().height;

	console.log("menor_distancia: ");
	console.log(elemento_menor_distancia);

	// Está mais próximo da borda de baixo, ou seja.. inserir por último:
	if (borda_inferior - event.clientY < menor_distancia) {

		console.log('QQ11');

		var recentComand = genericCreateCommand(command_type);

		var command_parent = el_jq.data('command');

		if (is_in_else) {
			console.log('QQ15');
			command_parent.commands_else.push(recentComand);
			console.log('el_jq');
			console.log(el_jq);
			console.log("$(el_jq.find('.commands_else')[0]):: ");
			console.log((0, _jquery2.default)(el_jq.find('.commands_else')[0]));

			renderCommand(recentComand, el_jq, 3, function_obj);
		} else {
			console.log('QQ16');
			command_parent.commands_block.push(recentComand);

			renderCommand(recentComand, (0, _jquery2.default)(el_jq.find('.block_commands')[0]), 3, function_obj);
		}
	} else {

		console.log('QQ12');

		var recentComand = genericCreateCommand(command_type);

		var command_parent = el_jq.data('command');

		if (is_in_else) {

			var index = command_parent.commands_else.indexOf((0, _jquery2.default)(elemento_menor_distancia).data('command'));

			if (index > -1) {
				command_parent.commands_else.splice(index, 0, recentComand);
				renderCommand(recentComand, elemento_menor_distancia, 1, function_obj);
			}
		} else {
			var index = command_parent.commands_block.indexOf((0, _jquery2.default)(elemento_menor_distancia).data('command'));

			if (index > -1) {
				command_parent.commands_block.splice(index, 0, recentComand);
				renderCommand(recentComand, elemento_menor_distancia, 1, function_obj);
			}
		}
	}
}

function findBeforeOrAfterCommandToAdd(el, event, function_obj, command_type) {
	switch ((0, _jquery2.default)(el).data('command').type) {
		case Models.COMMAND_TYPES.iftrue:
		case Models.COMMAND_TYPES.switch:
		case Models.COMMAND_TYPES.repeatNtimes:
		case Models.COMMAND_TYPES.whiletrue:
		case Models.COMMAND_TYPES.dowhiletrue:
			insertCommandInBlock(el, event, function_obj, command_type);
			return;
	}

	var menor_distancia = 999999999;
	var antes = true;

	var t_bot;
	var t_top;

	t_top = el.getBoundingClientRect().top;
	t_bot = el.getBoundingClientRect().top + el.getBoundingClientRect().height;

	var d_top = event.clientY - t_top; // distancia topo
	var d_bot = t_bot - event.clientY; // distancia baixo

	// Está mais próximo da borda de baixo, ou seja.. inserir por último:
	if (d_top < d_bot) {

		var recentComand = genericCreateCommand(command_type);

		var index = function_obj.commands.indexOf((0, _jquery2.default)(el).data('command'));

		if (index > -1) {
			function_obj.commands.splice(index, 0, recentComand);
		}

		renderCommand(recentComand, el, 1, function_obj);
	} else {
		var recentComand = genericCreateCommand(command_type);

		var index = function_obj.commands.indexOf((0, _jquery2.default)(el).data('command'));

		if (index > -1) {
			function_obj.commands.splice(index + 1, 0, recentComand);
		}

		renderCommand(recentComand, el, 2, function_obj);
	}
}

function findNearbyCommandToAddInFunctionScope(el, event, node_list_commands, function_obj, command_type) {

	var all_sub = (0, _jquery2.default)(node_list_commands).find('div.command_container');

	var menor_distancia = 999999999;
	var elemento_menor_distancia = null;
	var antes = true;

	var t_bot;
	var t_top;

	// Descobrindo o elemento mais próximo:
	for (var i = 0; i < all_sub.length; i++) {

		t_top = all_sub[i].getBoundingClientRect().top;
		t_bot = all_sub[i].getBoundingClientRect().top + all_sub[i].getBoundingClientRect().height;

		if (t_top - event.clientY < menor_distancia) {
			menor_distancia = event.clientY - t_top;
			elemento_menor_distancia = all_sub[i];
		}
	}

	var borda_inferior = elemento_menor_distancia.parentNode.getBoundingClientRect().top + elemento_menor_distancia.parentNode.getBoundingClientRect().height;

	// Está mais próximo da borda de baixo, ou seja.. inserir por último:
	if (borda_inferior - event.clientY < menor_distancia) {

		var recentComand = genericCreateCommand(command_type);
		function_obj.commands.push(recentComand);
		//
		renderCommand(recentComand, node_list_commands, 3, function_obj);
	} else {

		var recentComand = genericCreateCommand(command_type);

		var index = function_obj.commands.indexOf((0, _jquery2.default)(elemento_menor_distancia).data('command'));

		if (index > -1) {
			function_obj.commands.splice(index, 0, recentComand);
		}

		renderCommand(recentComand, elemento_menor_distancia, 1, function_obj);
	}
}

/***/ }),

/***/ "./js/visualUI/commands/attribution.js":
/*!*********************************************!*\
  !*** ./js/visualUI/commands/attribution.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;
exports.manageExpressionElements = manageExpressionElements;
exports.renderMenuOperations = renderMenuOperations;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _variable_value_menu = __webpack_require__(/*! ./variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenu = _interopRequireWildcard(_variable_value_menu);

var VariableValueMenuManagement = _interopRequireWildcard(_variable_value_menu);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui attribution created_element"> <i class="ui icon small arrow left"></i> <span> x = 1 + 1 </span></div>');
}

function renderCommand(command, function_obj) {

	var el = (0, _jquery2.default)('<div class="ui attribution command_container"><i class="ui icon small arrow left command_drag"></i> <i class="ui icon times red button_remove_command"></i> <div class="var_attributed"></div> <span class="text_attr_receives span_command_spec">' + _localizedStringsService.LocalizedStrings.getUI('text_receives') + '</span> ' + '<div class="expression_elements"></div> </div>');
	el.data('command', command);

	VariableValueMenu.renderMenu(command, command.variable, el.find('.var_attributed'), function_obj);

	if (!command.expression || command.expression.length < 1) {
		var exp = new Models.ExpressionElement(Models.EXPRESSION_ELEMENTS.op_exp, [Models.ARITHMETIC_TYPES.none, new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true)]);

		command.expression.push(exp);
	}

	addHandlers(command, function_obj, el);

	renderExpressionElements(command, function_obj, el);

	return el;
}

function manageExpressionElements(command, ref_object, dom_object, menu_var_or_value, function_obj, selectedItem, expression_element) {

	var index_to_move = expression_element.itens.indexOf(ref_object);

	switch (selectedItem.data('exp')) {
		case Models.EXPRESSION_ELEMENTS.exp_op_exp:

			var exp = new Models.ExpressionElement(Models.EXPRESSION_ELEMENTS.exp_op_exp, [expression_element.itens[index_to_move], Models.ARITHMETIC_TYPES.plus, new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true)]);

			expression_element.itens[index_to_move] = exp;

			break;

		case Models.EXPRESSION_ELEMENTS.op_exp:

			var exp = new Models.ExpressionElement(Models.EXPRESSION_ELEMENTS.op_exp, [Models.ARITHMETIC_TYPES.plus, expression_element.itens[index_to_move]]);

			expression_element.itens[index_to_move] = exp;

			break;

		case Models.EXPRESSION_ELEMENTS.par_exp_par:

			var exp = new Models.ExpressionElement(Models.EXPRESSION_ELEMENTS.par_exp_par, [expression_element.itens[index_to_move]]);

			expression_element.itens[index_to_move] = exp;

			break;
	}

	renderExpressionElements(command, function_obj, dom_object);
}

function renderExpressionElements(command, function_obj, el) {
	var expression_div = el.find('.expression_elements');
	var command_container;

	if (el.hasClass("command_container") == false) {
		var hier = el.parentsUntil(".command_container");
		for (var i = 0; i < hier.length; i++) {
			if ((0, _jquery2.default)(hier[i]).hasClass("command_container")) {
				command_container = (0, _jquery2.default)(hier[i]);
				break;
			}
			if ((0, _jquery2.default)(hier[i]).hasClass("expression_elements")) {
				expression_div = (0, _jquery2.default)(hier[i]);
				break;
			}
		}
	}

	if (command_container) {
		expression_div = command_container.find('.expression_elements');
	}

	expression_div.text('');

	for (var i = 0; i < command.expression.length; i++) {

		var temp = (0, _jquery2.default)('<div class="expression_element"></div>');
		temp.data('ref_element', command.expression[i]);
		temp.data('ref_index', i);

		expression_div.append(temp);

		renderElement(command, function_obj, temp, command.expression[i]);
	}
}

function renderOperator(command, function_obj, temp_op, expression_element, index_op) {

	var context_menu = '<div class="ui dropdown"><div class="text">';

	switch (expression_element.itens[index_op]) {
		case Models.ARITHMETIC_TYPES.plus:
			context_menu += '+';
			break;

		case Models.ARITHMETIC_TYPES.minus:
			context_menu += '-';
			break;

		case Models.ARITHMETIC_TYPES.multiplication:
			context_menu += '*';
			break;

		case Models.ARITHMETIC_TYPES.division:
			context_menu += '/';
			break;

		case Models.ARITHMETIC_TYPES.module:
			context_menu += '%';
			break;

		case Models.ARITHMETIC_TYPES.none:
			context_menu += '...';
			break;
	}

	context_menu += '</div><div class="menu">';
	context_menu += '<div class="item" data-value="' + Models.ARITHMETIC_TYPES.plus + '">+</div>';
	context_menu += '<div class="item" data-value="' + Models.ARITHMETIC_TYPES.minus + '">-</div>';
	context_menu += '<div class="item" data-value="' + Models.ARITHMETIC_TYPES.multiplication + '">*</div>';
	context_menu += '<div class="item" data-value="' + Models.ARITHMETIC_TYPES.division + '">/</div>';
	context_menu += '<div class="item" data-value="' + Models.ARITHMETIC_TYPES.module + '">%</div>';
	context_menu += '<div class="item" data-value="' + Models.ARITHMETIC_TYPES.none + '" data-text="...">Nenhum</div>';
	context_menu += '</div></div>';

	context_menu = (0, _jquery2.default)(context_menu);

	temp_op.append(context_menu);

	context_menu.dropdown({
		onChange: function onChange(value, text, $selectedItem) {
			expression_element.itens[index_op] = value;
		}
	});
}

function renderMenuAddExpression(command, function_obj, el, dom_append_menu, expression_append_new_expression) {

	if (el.hasClass("command_container") == false) {
		var hier = el.parentsUntil(".commands_list_div");

		for (var i = 0; i < hier.length; i++) {
			if ((0, _jquery2.default)(hier[i]).hasClass("command_container")) {
				el = (0, _jquery2.default)(hier[i]);
				break;
			}
		}
	}

	if (dom_append_menu.hasClass("expression_elements") == false) {
		var hier = el.parentsUntil(".commands_list_div");

		for (var i = 0; i < hier.length; i++) {
			if ((0, _jquery2.default)(hier[i]).hasClass("expression_elements")) {
				dom_append_menu = (0, _jquery2.default)(hier[i]);
				break;
			}
		}
	}

	var context_menu = '<div class="ui dropdown"><div class="text"></div><i class="ui icon arrow alternate circle right outline"></i><div class="menu">';
	context_menu += '<div class="item" data-value="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
	context_menu += '<div class="item" data-value="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
	context_menu += '<div class="item" data-value="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
	context_menu += '</div></div>';

	context_menu = (0, _jquery2.default)(context_menu);

	dom_append_menu.append(context_menu);

	context_menu.dropdown({
		onChange: function onChange(value, text, $selectedItem) {
			switch (value) {
				case Models.EXPRESSION_ELEMENTS.exp_op_exp:

					var exp = new Models.ExpressionElement(Models.EXPRESSION_ELEMENTS.exp_op_exp, [new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true), Models.ARITHMETIC_TYPES.plus, new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true)]);

					expression_append_new_expression.push(exp);
					break;

				case Models.EXPRESSION_ELEMENTS.op_exp:
					var exp = new Models.ExpressionElement(Models.EXPRESSION_ELEMENTS.op_exp, [Models.ARITHMETIC_TYPES.plus, new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true)]);

					expression_append_new_expression.push(exp);
					break;

				case Models.EXPRESSION_ELEMENTS.par_exp_par:

					var exp = new Models.ExpressionElement(Models.EXPRESSION_ELEMENTS.par_exp_par, [new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true)]);

					expression_append_new_expression.push(exp);

					break;
			}

			renderExpressionElements(command, function_obj, el);
		}
	});
}

function renderElement(command, function_obj, el, expression_element) {

	switch (expression_element.type_exp) {
		case Models.EXPRESSION_ELEMENTS.exp_op_exp:

			var temp_op = (0, _jquery2.default)('<div class="component_element"></div>');
			var temp_exp_1 = (0, _jquery2.default)('<div class="component_element"></div>');
			var temp_exp_2 = (0, _jquery2.default)('<div class="component_element"></div>');

			el.append(temp_exp_1);
			el.append(temp_op);
			el.append(temp_exp_2);

			if (expression_element.itens[0].type) {
				VariableValueMenu.renderMenu(command, expression_element.itens[0], temp_exp_1, function_obj, 2, expression_element);
			} else {
				renderElement(command, function_obj, temp_exp_1, expression_element.itens[0]);
			}

			renderOperator(command, function_obj, temp_op, expression_element, 1);

			if (expression_element.itens[2].type) {
				VariableValueMenu.renderMenu(command, expression_element.itens[2], temp_exp_2, function_obj, 2, expression_element);
			} else {
				renderElement(command, function_obj, temp_exp_2, expression_element.itens[2]);
			}

			break;

		case Models.EXPRESSION_ELEMENTS.op_exp:
			var temp_op = (0, _jquery2.default)('<div class="component_element"></div>');
			var temp_exp = (0, _jquery2.default)('<div class="component_element"></div>');

			el.append(temp_op);
			el.append(temp_exp);

			renderOperator(command, function_obj, temp_op, expression_element, 0);

			if (expression_element.itens[1].type) {
				VariableValueMenu.renderMenu(command, expression_element.itens[1], temp_exp, function_obj, 2, expression_element);
			} else {
				renderElement(command, function_obj, temp_exp, expression_element.itens[1]);
			}
			break;

		case Models.EXPRESSION_ELEMENTS.par_exp_par:

			var temp_par_1 = (0, _jquery2.default)('<div class="component_element"> ( </div>');
			var temp_exp = (0, _jquery2.default)('<div class="component_element"></div>');
			var temp_par_2 = (0, _jquery2.default)('<div class="component_element"> ) </div>');

			el.append(temp_par_1);
			el.append(temp_exp);

			for (var j = 0; j < expression_element.itens.length; j++) {
				if (expression_element.itens[j].type) {
					VariableValueMenu.renderMenu(command, expression_element.itens[j], temp_exp, function_obj, 2, expression_element);
				} else {
					renderElement(command, function_obj, temp_exp, expression_element.itens[j]);
				}
			}

			//renderMenuAddExpression(command, function_obj, el, el, expression_element.itens);

			el.append(temp_par_2);

			break;
	}
}

function renderExpression(command, function_obj, el) {

	var expression_div = el.find('.expression_elements');
	expression_div.text('');

	var menu_add_item = (0, _jquery2.default)('<div class="menu_add_item"></div>');
	menu_add_item.data('index_add', 0);

	expression_div.append(menu_add_item);

	for (var i = 0; i < command.expression.length; i++) {

		if (command.expression[i].type) {

			var temp = (0, _jquery2.default)('<div class="expression_element"></div>');
			temp.data('ref_element', command.expression[i]);
			temp.data('ref_index', i);

			expression_div.append(temp);

			VariableValueMenu.renderMenu(command, command.expression[i], temp, function_obj);
		} else if (command.expression[i] == "(" || command.expression[i] == ")") {

			var temp = (0, _jquery2.default)('<div class="expression_element">' + command.expression[i] + '</div>');
			temp.data('ref_element', command.expression[i]);
			temp.data('ref_index', i);

			expression_div.append(temp);
		} else {

			var temp = '<div class="expression_element">';

			switch (command.expression[i]) {
				case Models.ARITHMETIC_TYPES.plus:
					temp += '+';
					break;
				case Models.ARITHMETIC_TYPES.minus:
					temp += '-';
					break;
				case Models.ARITHMETIC_TYPES.multiplication:
					temp += '*';
					break;
				case Models.ARITHMETIC_TYPES.division:
					temp += '/';
					break;
				case Models.ARITHMETIC_TYPES.module:
					temp += '%';
					break;
			}

			temp += '</div>';
			temp = (0, _jquery2.default)(temp);
			temp.data('ref_element', command.expression[i]);
			temp.data('ref_index', i);

			expression_div.append(temp);
		}

		var menu_add_item_seq = (0, _jquery2.default)('<div class="menu_add_item"></div>');
		var index_temp = i + 1;
		menu_add_item_seq.data('index_add', index_temp);
		expression_div.append(menu_add_item_seq);
	}

	addMenuItens(command, function_obj, el);
}

function addMenuItens(command, function_obj, expression_div) {
	var divs_expression = expression_div.find('.menu_add_item');

	for (var i = 0; i < divs_expression.length; i++) {

		var temp = (0, _jquery2.default)(divs_expression[i]).data('index_add');

		var context_menu = '<div class="ui dropdown context_menu_clear"><i class="ui icon plus square outline"></i><div class="menu">';
		context_menu += '<div class="item" data-option="value" data-index="' + temp + '">' + _localizedStringsService.LocalizedStrings.getUI('text_value') + '</div>';
		context_menu += '<div class="item" data-option="operator" data-index="' + temp + '">' + _localizedStringsService.LocalizedStrings.getUI('text_operator') + '</div>';
		context_menu += '<div class="item" data-option="parentheses" data-index="' + temp + '">' + _localizedStringsService.LocalizedStrings.getUI('text_parentheses') + '</div>';
		context_menu += '</div></div>';

		context_menu = (0, _jquery2.default)(context_menu);

		(0, _jquery2.default)(divs_expression[i]).append(context_menu);

		context_menu.dropdown({
			on: 'hover',
			onChange: function onChange(value, text, $selectedItem) {
				switch ($selectedItem.data('option')) {
					case "value":
						command.expression.splice($selectedItem.data('index'), 0, new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true));
						renderExpression(command, function_obj, expression_div);
						break;
					case "operator":
						command.expression.splice($selectedItem.data('index'), 0, Models.ARITHMETIC_TYPES.plus);
						renderExpression(command, function_obj, expression_div);
						break;
					case "parentheses":
						command.expression.splice($selectedItem.data('index'), 0, "(");
						command.expression.splice($selectedItem.data('index') + 1, 0, new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true));
						command.expression.splice($selectedItem.data('index') + 2, 0, ")");
						renderExpression(command, function_obj, expression_div);
						break;
				}
			}
		});
	}
}

function addHandlers(command, function_obj, attribution_dom) {

	attribution_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, attribution_dom)) {
			attribution_dom.fadeOut();
		}
	});

	attribution_dom.find('.button_refresh_attribution').on('click', function () {
		renderExpressionElements(command, function_obj, attribution_dom);
	});
}

function renderMenuOperations(command, ref_object, dom_object, menu_var_or_value, function_obj, variable_selected) {

	/*console.log("recebido o seguinte DOM: ");
 console.log(dom_object);
 	if (dom_object.hasClass('var_attributed')) {
 	return;
 } else {
 	var hier = dom_object.parentsUntil(".command_container");
 	for (var i = 0; i < hier.length; i++) {
 		if ($(hier[i]).hasClass('var_attributed') || $(hier[i]).hasClass('parameters_function_called')) {
 			return;
 		}
 	}
 
 	
 }
 	dom_object.find('.context_menu_clear').remove();
 
 var menu_operations = '<div class="ui dropdown menu_operations"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
 	for (var tm in Models.ARITHMETIC_TYPES) {
 		menu_operations += '<div class="item" data-option="'+tm+'">'+LocalizedStrings.getUI('btn_arithmetic_' + tm)+'</div>';
    }
    menu_operations += '<div class="item" data-option="clear">'+LocalizedStrings.getUI('btn_clear')+'</div>';
 
    menu_operations += '</div></div>';
     menu_operations = $(menu_operations);
     dom_object.append(menu_operations);
     menu_operations.dropdown({
    	onChange: function(value, text, $selectedItem) {
    		switch ($($selectedItem).data('option')) {
    			case "clear":
     			$(dom_object).text('');
 	     	 	VariableValueMenu.renderMenu(command, ref_object, dom_object, function_obj);
    				break;
    			default:
    				createExpressionAround(command, ref_object, dom_object, function_obj);
    				menu_operations.find('.text').text('');
    		}
        }
    });*/
}

function createExpressionAround(command, ref_object, dom_object, function_obj) {
	(0, _jquery2.default)('<span> ( </span>').insertBefore(dom_object);
	(0, _jquery2.default)('<span> ) </span>').insertAfter(dom_object);

	VariableValueMenu.renderMenu(command, new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true), dom_object, function_obj);
}

/***/ }),

/***/ "./js/visualUI/commands/break.js":
/*!***************************************!*\
  !*** ./js/visualUI/commands/break.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui comment created_element"> <i class="ui icon small quote left"></i> <span> ' + _localizedStringsService.LocalizedStrings.getUI('text_break') + ' </span></div>');
}

function renderCommand(command, function_obj) {
	var el = (0, _jquery2.default)('<div class="ui comment command_container"> <i class="ui icon small quote left"></i> <i class="ui icon times red button_remove_command"></i> <span>' + _localizedStringsService.LocalizedStrings.getUI('text_break') + '</span> </div>');
	el.data('command', command);

	addHandlers(command, function_obj, el);

	return el;
}

function addHandlers(command, function_obj, break_dom) {

	break_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, break_dom)) {
			break_dom.fadeOut();
		}
	});
}

/***/ }),

/***/ "./js/visualUI/commands/comment.js":
/*!*****************************************!*\
  !*** ./js/visualUI/commands/comment.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _variable_value_menu = __webpack_require__(/*! ./variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenu = _interopRequireWildcard(_variable_value_menu);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui comment created_element"> <i class="ui icon small quote left"></i> <span class="span_comment_text" "> ' + _localizedStringsService.LocalizedStrings.getUI('text_comment') + ' </span></div>');
}

function renderCommand(command, function_obj) {
	var el = (0, _jquery2.default)('<div class="ui comment command_container"> <i class="ui icon small quote left command_drag"></i> <i class="ui icon times red button_remove_command"></i> <div class="var_value_menu_div"></div> <div class="div_comment_text">' + '</div> </div>');
	el.data('command', command);

	addHandlers(command, function_obj, el);

	renderTextComment(command, function_obj, el);

	return el;
}

function renderTextComment(command, function_obj, el) {
	VariableValueMenu.renderMenu(command, command.comment_text, el.find('.var_value_menu_div'), function_obj, 20);
}

function addHandlers(command, function_obj, comment_dom) {

	comment_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, comment_dom)) {
			comment_dom.fadeOut();
		}
	});
}

/***/ }),

/***/ "./js/visualUI/commands/conditional_expression.js":
/*!********************************************************!*\
  !*** ./js/visualUI/commands/conditional_expression.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.renderExpression = renderExpression;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _variable_value_menu = __webpack_require__(/*! ./variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenuManagement = _interopRequireWildcard(_variable_value_menu);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function renderExpression(command, expression, function_obj, initial_el_to_render) {

	expression.dom_object = initial_el_to_render;

	if (expression.expression == null || expression.expression.length < 1) {

		renderStartMenu(command, expression, function_obj, initial_el_to_render);
	} else {

		var main_div = (0, _jquery2.default)('<div class="expression_elements"></div>');

		switch (expression.expression.type) {
			case Models.EXPRESSION_TYPES.exp_logic:
				renderLogicExpression(command, expression, expression.expression, function_obj, main_div, initial_el_to_render);
				break;
			case Models.EXPRESSION_TYPES.exp_arithmetic:
				renderArithmeticExpression(command, expression, expression.expression, function_obj, main_div);
				break;
		}

		initial_el_to_render.append(main_div);
		var restartMenu = (0, _jquery2.default)('<div class="ui restart_expression"><i class="ui icon undo"></i></div>');
		initial_el_to_render.append(restartMenu);
		restartMenu.on('click', function (e) {
			expression.expression = null;
			initial_el_to_render.empty();
			renderExpression(command, expression, function_obj, initial_el_to_render);
		});
	}
}

function renderArithmeticOperator(command, all_expression, expression_arithmetic, arithmetic_operator, function_obj, element_to_append) {

	var menu_operator = (0, _jquery2.default)('<div class="ui dropdown"><div class="text"></div><i class="dropdown icon"></i></div>');
	menu_operator.dropdown({
		values: [{
			name: '>',
			value: Models.ARITHMETIC_COMPARISON.greater_than,
			selected: arithmetic_operator == Models.ARITHMETIC_COMPARISON.greater_than
		}, {
			name: '<',
			value: Models.ARITHMETIC_COMPARISON.less_than,
			selected: arithmetic_operator == Models.ARITHMETIC_COMPARISON.less_than
		}, {
			name: '==',
			value: Models.ARITHMETIC_COMPARISON.equals_to,
			selected: arithmetic_operator == Models.ARITHMETIC_COMPARISON.equals_to
		}, {
			name: '!=',
			value: Models.ARITHMETIC_COMPARISON.not_equals_to,
			selected: arithmetic_operator == Models.ARITHMETIC_COMPARISON.not_equals_to
		}, {
			name: '>=',
			value: Models.ARITHMETIC_COMPARISON.greater_than_or_equals_to,
			selected: arithmetic_operator == Models.ARITHMETIC_COMPARISON.greater_than_or_equals_to
		}, {
			name: '<=',
			value: Models.ARITHMETIC_COMPARISON.less_than_or_equals_to,
			selected: arithmetic_operator == Models.ARITHMETIC_COMPARISON.less_than_or_equals_to
		}],
		onChange: function onChange(value, text, $selectedItem) {
			expression_arithmetic.operator = value;
		}
	});

	element_to_append.append(menu_operator);
}

function renderLogicOperator(command, all_expression, expression_logic, logic_operator, function_obj, element_to_append, initial_el_to_render) {

	var menu_operator = (0, _jquery2.default)('<div class="ui dropdown"><div class="text"></div><i class="dropdown icon"></i></div>');
	menu_operator.dropdown({
		values: [{
			name: '==',
			value: Models.LOGIC_COMPARISON.equals_to,
			selected: logic_operator == Models.LOGIC_COMPARISON.equals_to
		}, {
			name: '!=',
			value: Models.LOGIC_COMPARISON.not_equals_to,
			selected: logic_operator == Models.LOGIC_COMPARISON.not_equals_to
		}, {
			name: '&&',
			value: Models.LOGIC_COMPARISON.and,
			selected: logic_operator == Models.LOGIC_COMPARISON.and
		}, {
			name: '||',
			value: Models.LOGIC_COMPARISON.or,
			selected: logic_operator == Models.LOGIC_COMPARISON.or
		}],
		onChange: function onChange(value, text, $selectedItem) {
			if ($selectedItem) {
				expression_logic.operator = value;
				if (expression_logic.second_operand == null) {
					expression_logic.second_operand = new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true);
					initial_el_to_render.empty();
					renderExpression(command, all_expression, function_obj, initial_el_to_render);
				}
			}
		}
	});

	element_to_append.append(menu_operator);
}

function renderLogicExpression(command, all_expression, expression_logic, function_obj, element_to_append, initial_el_to_render) {

	var exp_el_par_1 = (0, _jquery2.default)(' <span class="span_command_spec"> </span> ');
	var exp_el_expr_el_1 = (0, _jquery2.default)('<div class="expression_element"></div>');
	var exp_el_expr_operand = (0, _jquery2.default)('<div class="expression_element"></div>');
	var exp_el_expr_el_2 = (0, _jquery2.default)('<div class="expression_element"></div>');
	var exp_el_par_2 = (0, _jquery2.default)(' <span class="span_command_spec"> </span> ');

	if (expression_logic.first_operand.type == Models.EXPRESSION_TYPES.exp_logic) {
		renderLogicExpression(command, all_expression, expression_logic.first_operand, function_obj, exp_el_expr_el_1);
	} else if (expression_logic.first_operand.type == Models.EXPRESSION_TYPES.exp_arithmetic) {
		renderArithmeticExpression(command, all_expression, expression_logic.first_operand, function_obj, exp_el_expr_el_1);
	} else {
		VariableValueMenuManagement.renderMenu(command, expression_logic.first_operand, exp_el_expr_el_1, function_obj);
	}

	element_to_append.append(exp_el_par_1);
	element_to_append.append(exp_el_expr_el_1);

	renderLogicOperator(command, all_expression, expression_logic, expression_logic.operator, function_obj, exp_el_expr_operand, initial_el_to_render);

	element_to_append.append(exp_el_expr_operand);

	if (expression_logic.second_operand) {
		if (expression_logic.second_operand.type == Models.EXPRESSION_TYPES.exp_logic) {
			renderLogicExpression(command, all_expression, expression_logic.second_operand, function_obj, exp_el_expr_el_2);
		} else if (expression_logic.second_operand.type == Models.EXPRESSION_TYPES.exp_arithmetic) {
			renderArithmeticExpression(command, all_expression, expression_logic.second_operand, function_obj, exp_el_expr_el_2);
		} else {
			VariableValueMenuManagement.renderMenu(command, expression_logic.second_operand, exp_el_expr_el_2, function_obj);
		}

		element_to_append.append(exp_el_expr_el_2);
	}

	element_to_append.append(exp_el_par_2);
}

function renderArithmeticExpression(command, all_expression, expression_arithmetic, function_obj, element_to_append) {

	var exp_el_par_1 = (0, _jquery2.default)(' <span class="span_command_spec"> </span> ');
	var exp_el_expr_el_1 = (0, _jquery2.default)('<div class="expression_element"></div>');
	var exp_el_expr_operand = (0, _jquery2.default)('<div class="expression_element"></div>');
	var exp_el_expr_el_2 = (0, _jquery2.default)('<div class="expression_element"></div>');
	var exp_el_par_2 = (0, _jquery2.default)(' <span class="span_command_spec"> </span> ');

	if (expression_arithmetic.first_operand.type == Models.EXPRESSION_TYPES.exp_logic) {
		renderLogicExpression(command, all_expression, expression_arithmetic.first_operand, function_obj, exp_el_expr_el_1);
	} else if (expression_arithmetic.first_operand.type == Models.EXPRESSION_TYPES.exp_arithmetic) {
		renderArithmeticExpression(command, all_expression, expression_arithmetic.first_operand, function_obj, exp_el_expr_el_1);
	} else {
		VariableValueMenuManagement.renderMenu(command, expression_arithmetic.first_operand, exp_el_expr_el_1, function_obj);
	}

	if (expression_arithmetic.second_operand.type == Models.EXPRESSION_TYPES.exp_logic) {
		renderLogicExpression(command, all_expression, expression_arithmetic.second_operand, function_obj, exp_el_expr_el_2);
	} else if (expression_arithmetic.second_operand.type == Models.EXPRESSION_TYPES.exp_arithmetic) {
		renderArithmeticExpression(command, all_expression, expression_arithmetic.second_operand, function_obj, exp_el_expr_el_2);
	} else {
		VariableValueMenuManagement.renderMenu(command, expression_arithmetic.second_operand, exp_el_expr_el_2, function_obj);
	}

	renderArithmeticOperator(command, all_expression, expression_arithmetic, expression_arithmetic.operator, function_obj, exp_el_expr_operand);

	element_to_append.append(exp_el_par_1);
	element_to_append.append(exp_el_expr_el_1);
	element_to_append.append(exp_el_expr_operand);
	element_to_append.append(exp_el_expr_el_2);
	element_to_append.append(exp_el_par_2);
}

function renderStartMenu(command, expression, function_obj, initial_el_to_render) {
	var start_menu = '';
	start_menu += '<div class="ui dropdown menu_start_rendered"><div class="text"><i>' + _localizedStringsService.LocalizedStrings.getUI('expression_menu_select') + '</i></div><i class="dropdown icon"></i><div class="menu">';
	start_menu += '<div class="item" data-exp="' + Models.EXPRESSION_TYPES.exp_logic + '">' + _localizedStringsService.LocalizedStrings.getUI('text_logic_expression') + ' (EL == EL and EL)</div>';
	start_menu += '<div class="item" data-exp="' + Models.EXPRESSION_TYPES.exp_arithmetic + '">' + _localizedStringsService.LocalizedStrings.getUI('text_arithmetic_expression') + ' (EA < EA)</div>';
	start_menu += '</div></div>';
	start_menu = (0, _jquery2.default)(start_menu);

	start_menu.dropdown({
		onChange: function onChange(value, text, $selectedItem) {
			switch ($selectedItem.data('exp')) {
				case Models.EXPRESSION_TYPES.exp_logic:
					expression.expression = new Models.LogicExpression(false, new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true));
					break;
				case Models.EXPRESSION_TYPES.exp_arithmetic:
					expression.expression = new Models.ArithmeticExpression(new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true), new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true), Models.ARITHMETIC_COMPARISON.less_than);
					break;
			}

			initial_el_to_render.html('');

			renderExpression(command, expression, function_obj, initial_el_to_render);
		},
		selectOnKeydown: false
	});

	initial_el_to_render.append(' <span class="span_command_spec"> </span> ');

	initial_el_to_render.append(start_menu);

	initial_el_to_render.append(' <span class="span_command_spec"> </span> ');
}

/***/ }),

/***/ "./js/visualUI/commands/contextualized_menu.js":
/*!*****************************************************!*\
  !*** ./js/visualUI/commands/contextualized_menu.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.renderMenu = renderMenu;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

var _variable_value_menu = __webpack_require__(/*! ./variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenuManagement = _interopRequireWildcard(_variable_value_menu);

var _switch = __webpack_require__(/*! ./switch */ "./js/visualUI/commands/switch.js");

var SwitchManagement = _interopRequireWildcard(_switch);

var _repeatNtimes = __webpack_require__(/*! ./repeatNtimes */ "./js/visualUI/commands/repeatNtimes.js");

var RepeatNTimesManagement = _interopRequireWildcard(_repeatNtimes);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function renderMenu(command, dom_where_render, function_obj, dom_command) {

	var menu_div = '<div class="ui dropdown menu_commands" ><i class="icon code"></i> <div class="menu"> ';

	if (command.type == Models.COMMAND_TYPES.repeatNtimes || command.type == Models.COMMAND_TYPES.whiletrue || command.type == Models.COMMAND_TYPES.dowhiletrue) {

		menu_div += '<a class="item" data-command="' + Models.COMMAND_TYPES.break + '"><i class="download icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('btn_break') + ' </a>';
	} else {

		menu_div += '<a class="item" data-command="' + Models.COMMAND_TYPES.break + '"><i class="download icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('btn_break') + ' </a>';
		menu_div += '<a class="item" data-command="' + Models.COMMAND_TYPES.switchcase + '"><i class="download icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('btn_case') + ' </a>';
	}

	menu_div += '</div></div>';

	menu_div = (0, _jquery2.default)(menu_div);

	dom_where_render.append(menu_div);

	addHandlers(command, dom_where_render, function_obj, dom_command);
}

function addHandlers(command, dom_where_render, function_obj, dom_command) {

	console.log('command, dom_where_render, function_obj, dom_command');
	console.log(command, dom_where_render, function_obj, dom_command);

	console.log(dom_where_render.parents());

	dom_where_render.find('.menu_commands').dropdown({
		on: 'hover'
	});

	dom_where_render.find('.menu_commands a').on('click', function (evt) {

		if (command.type == Models.COMMAND_TYPES.repeatNtimes || command.type == Models.COMMAND_TYPES.whiletrue || command.type == Models.COMMAND_TYPES.dowhiletrue) {

			if (command.commands_block == null || command.commands_block.length == 0) {

				command.commands_block = [];

				var new_cmd = CommandsManagement.genericCreateCommand((0, _jquery2.default)(this).data('command'));
				command.commands_block.push(new_cmd);

				CommandsManagement.renderCommand(new_cmd, dom_command.find('.block_commands'), 3, function_obj);
			} else {
				CommandsManagement.createFloatingCommand(function_obj, dom_command.find('.block_commands'), (0, _jquery2.default)(this).data('command'), evt);
			}
		} else {

			switch ((0, _jquery2.default)(this).data('command')) {
				case Models.COMMAND_TYPES.break:
					CommandsManagement.createFloatingCommand(function_obj, dom_command.find('.block_commands'), (0, _jquery2.default)(this).data('command'), evt);
					break;

				case Models.COMMAND_TYPES.switchcase:
					addCaseToSwitch(command, dom_where_render, function_obj, dom_command);
					break;
			}
		}
	});
}

function addCaseToSwitch(command, dom_where_render, function_obj, dom_command) {

	if (command.cases == null) {
		command.cases = [];
	}

	var sc = new Models.SwitchCase(new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true));

	command.cases.push(sc);

	SwitchManagement.renderCase(sc, command, function_obj, dom_command.find('.all_cases_div'));
}

/***/ }),

/***/ "./js/visualUI/commands/dowhiletrue.js":
/*!*********************************************!*\
  !*** ./js/visualUI/commands/dowhiletrue.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

var _conditional_expression = __webpack_require__(/*! ./conditional_expression */ "./js/visualUI/commands/conditional_expression.js");

var ConditionalExpressionManagement = _interopRequireWildcard(_conditional_expression);

var _contextualized_menu = __webpack_require__(/*! ./contextualized_menu */ "./js/visualUI/commands/contextualized_menu.js");

var ContextualizedMenu = _interopRequireWildcard(_contextualized_menu);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui dowhiletrue created_element"> <i class="ui icon small sync"></i> <span> ' + _localizedStringsService.LocalizedStrings.getUI('text_command_do') + ' {<br>} ' + _localizedStringsService.LocalizedStrings.getUI('text_code_while') + '(x < 10) </span></div>');
}

function renderCommand(command, function_obj) {
	var ret = '';
	ret += '<div class="ui dowhiletrue command_container"> <i class="ui icon small random command_drag"></i> <i class="ui icon times red button_remove_command"></i> <div class="ui context_menu"></div>  <span class="span_command_spec"> ' + _localizedStringsService.LocalizedStrings.getUI('text_command_do') + ' </span>';
	ret += '<div class="ui block_commands" data-subblock="" data-idcommand="">';
	ret += '</div>';
	ret += ' <span class="span_command_spec"> ' + _localizedStringsService.LocalizedStrings.getUI('text_code_while') + ' </span> <span class="span_command_spec"> ( </span> <div class="conditional_expression"></div> <span class="span_command_spec"> ) </span>';
	ret += '</div>';

	var el = (0, _jquery2.default)(ret);
	el.data('command', command);

	addHandlers(command, function_obj, el);

	ContextualizedMenu.renderMenu(command, el.find('.context_menu'), function_obj, el);

	ConditionalExpressionManagement.renderExpression(command, command.expression, function_obj, el.find('.conditional_expression'));

	if (command.commands_block) {
		for (var j = 0; j < command.commands_block.length; j++) {
			CommandsManagement.renderCommand(command.commands_block[j], (0, _jquery2.default)(el.find('.block_commands')[0]), 3, function_obj);
		}
	}

	return el;
}

function addHandlers(command, function_obj, dowhiletrue_dom) {

	dowhiletrue_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, dowhiletrue_dom)) {
			dowhiletrue_dom.fadeOut();
		}
	});
}

/***/ }),

/***/ "./js/visualUI/commands/functioncall.js":
/*!**********************************************!*\
  !*** ./js/visualUI/commands/functioncall.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _variable_value_menu = __webpack_require__(/*! ./variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenu = _interopRequireWildcard(_variable_value_menu);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui functioncall created_element"> <i class="hand point right icon"></i> <span> funcao() </span></div>');
}

function renderCommand(command, function_obj) {
	var el = (0, _jquery2.default)('<div class="ui functioncall command_container"> <i class="hand point right icon command_drag"></i> <i class="ui icon times red button_remove_command"></i> <div class="var_value_menu_div"></div> </div>');
	el.data('command', command);

	VariableValueMenu.renderMenu(command, command.function_called, el.find('.var_value_menu_div'), function_obj);

	addHandlers(command, function_obj, el);

	return el;
}

function addHandlers(command, function_obj, functioncall_dom) {

	functioncall_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, functioncall_dom)) {
			functioncall_dom.fadeOut();
		}
	});
}

/***/ }),

/***/ "./js/visualUI/commands/iftrue.js":
/*!****************************************!*\
  !*** ./js/visualUI/commands/iftrue.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

var _conditional_expression = __webpack_require__(/*! ./conditional_expression */ "./js/visualUI/commands/conditional_expression.js");

var ConditionalExpressionManagement = _interopRequireWildcard(_conditional_expression);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui iftrue created_element"> <i class="ui icon small random"></i> <span> if (x < 1) { } </span></div>');
}

function renderCommand(command, function_obj) {
	var ret = '';
	ret += '<div class="ui iftrue command_container"><div class="ui data_block_if" data-if="true">  <i class="ui icon small random command_drag"></i> <i class="ui icon times red button_remove_command"></i>';
	ret += '<span class="span_command_spec"> ' + _localizedStringsService.LocalizedStrings.getUI('text_if') + '</span>';
	ret += ' <span class="span_command_spec"> ( </span> <div class="conditional_expression"></div> <span class="span_command_spec"> ) </span>';
	ret += '<span> </span> ';
	ret += '<div class="ui block_commands commands_if conditional_comands_block" data-if="true">';
	ret += '</div></div>';
	ret += '<div class="ui data_block_else" data-else="true"> <span class="span_command_spec"> ' + _localizedStringsService.LocalizedStrings.getUI('text_else') + ' </span>';
	ret += '<div class="ui block_commands commands_else conditional_comands_block" data-else="true">';
	ret += '</div>';
	ret += '<span></span></div>';
	ret += '</div>';

	var el = (0, _jquery2.default)(ret);
	el.data('command', command);
	el.find('.block_commands').data('command', command);
	el.find('.data_block_if').data('command', command);
	el.find('.data_block_else').data('command', command);

	addHandlers(command, function_obj, el);

	ConditionalExpressionManagement.renderExpression(command, command.expression, function_obj, el.find('.conditional_expression'));

	if (command.commands_block) {
		for (var j = 0; j < command.commands_block.length; j++) {
			CommandsManagement.renderCommand(command.commands_block[j], (0, _jquery2.default)(el.find('.commands_if')[0]), 3, function_obj);
		}
	}
	if (command.commands_else) {
		for (var j = 0; j < command.commands_else.length; j++) {
			CommandsManagement.renderCommand(command.commands_else[j], (0, _jquery2.default)(el.find('.commands_else')[0]), 3, function_obj);
		}
	}

	return el;
}

function addHandlers(command, function_obj, iftrue_dom) {

	iftrue_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, iftrue_dom)) {
			iftrue_dom.fadeOut();
		}
	});
}

/***/ }),

/***/ "./js/visualUI/commands/reader.js":
/*!****************************************!*\
  !*** ./js/visualUI/commands/reader.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _variable_value_menu = __webpack_require__(/*! ./variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenu = _interopRequireWildcard(_variable_value_menu);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui reader created_element"> <i class="ui icon small download"></i> <span> ' + _localizedStringsService.LocalizedStrings.getUI('text_command_read') + ' var </span></div>');
}

function renderCommand(command, function_obj) {
	var el = '<div class="ui reader command_container"> <i class="ui icon small download command_drag"></i> <i class="ui icon times red button_remove_command"></i> <span class="span_command_spec">' + _localizedStringsService.LocalizedStrings.getUI('text_command_read') + ' ( </span> <div class="var_value_menu_div"></div> <span class="close_parentheses span_command_spec">)</span> </div>';

	el = (0, _jquery2.default)(el);
	el.data('command', command);

	VariableValueMenu.renderMenu(command, command.variable_value_menu, el.find('.var_value_menu_div'), function_obj);

	addHandlers(command, function_obj, el);

	return el;
}

function addHandlers(command, function_obj, reader_dom) {
	reader_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, reader_dom)) {
			reader_dom.fadeOut();
		}
	});
}

/***/ }),

/***/ "./js/visualUI/commands/repeatNtimes.js":
/*!**********************************************!*\
  !*** ./js/visualUI/commands/repeatNtimes.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;
exports.manageExpressionElements = manageExpressionElements;
exports.manageClearExpressionElements = manageClearExpressionElements;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

var _conditional_expression = __webpack_require__(/*! ./conditional_expression */ "./js/visualUI/commands/conditional_expression.js");

var ConditionalExpressionManagement = _interopRequireWildcard(_conditional_expression);

var _variable_value_menu = __webpack_require__(/*! ./variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenu = _interopRequireWildcard(_variable_value_menu);

var _contextualized_menu = __webpack_require__(/*! ./contextualized_menu */ "./js/visualUI/commands/contextualized_menu.js");

var ContextualizedMenu = _interopRequireWildcard(_contextualized_menu);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui repeatNtimes created_element"> <i class="ui icon small sync"></i> <span> para (x = 0; x < 10; x ++) { } </span></div>');
}

function renderCommand(command, function_obj) {
	var ret = '<div class="ui repeatNtimes command_container"> <i class="ui icon small random command_drag"></i> <i class="ui icon times red button_remove_command"></i> <div class="ui context_menu"></div>  <span class="span_command_spec"> ' + _localizedStringsService.LocalizedStrings.getUI('text_for') + ' ( </span>  <div class="ui attribution_expression"><div class="ui variable_attribution"></div> <span class="text_receives span_command_spec"></span> <div class="ui var_value_expression div_expression_st"></div> </div> <span class="span_command_spec separator_character">;</span> <div class="conditional_expression"></div> <span class="span_command_spec separator_character">;</span>  <div class="ui incrementation_field"><div class="ui incrementation_variable"></div> <span class="text_inc_receives span_command_spec"></span> <div class="ui first_operand"></div><div class="ui operator"></div><div class="ui second_operand"></div></div>  <span class="span_command_spec"> ) </span>';
	ret += '<div class="ui block_commands">';
	ret += '</div>';
	ret += '<span> </span>';
	ret += '</div>';

	var el = (0, _jquery2.default)(ret);
	el.data('command', command);

	addHandlers(command, function_obj, el);

	ContextualizedMenu.renderMenu(command, el.find('.context_menu'), function_obj, el);

	VariableValueMenu.renderMenu(command, command.var_attribution, el.find('.variable_attribution'), function_obj);

	ConditionalExpressionManagement.renderExpression(command, command.expression2, function_obj, el.find('.conditional_expression'));

	VariableValueMenu.renderMenu(command, command.var_incrementation, el.find('.incrementation_variable'), function_obj);

	if (command.expression1) {
		el.find('.text_receives').text(_localizedStringsService.LocalizedStrings.getUI('text_receives'));
		VariableValueMenu.renderMenu(command, command.expression1, el.find('.var_value_expression'), function_obj);
	}

	if (command.expression3) {
		el.find('.text_inc_receives').text(_localizedStringsService.LocalizedStrings.getUI('text_receives'));
		VariableValueMenu.renderMenu(command, command.expression3.itens[0], el.find('.first_operand'), function_obj);
		renderOperator(command, function_obj, el.find('.operator'), command.expression3, 1);
		VariableValueMenu.renderMenu(command, command.expression3.itens[2], el.find('.second_operand'), function_obj);
	}

	if (command.commands_block) {
		for (var j = 0; j < command.commands_block.length; j++) {
			CommandsManagement.renderCommand(command.commands_block[j], (0, _jquery2.default)(el.find('.block_commands')[0]), 3, function_obj);
		}
	}

	return el;
}

function manageExpressionElements(command, ref_object, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element) {

	if (dom_object.hasClass('variable_attribution')) {
		if (!command.expression3) {
			var exp = new Models.ExpressionElement(Models.EXPRESSION_ELEMENTS.exp_op_exp, [command.var_attribution, Models.ARITHMETIC_TYPES.plus, new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, "1", null, null, true)]);

			command.expression3 = exp;
			command.var_incrementation = command.var_attribution;

			var cond_exp = new Models.ArithmeticExpression(command.var_attribution, new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), Models.ARITHMETIC_COMPARISON.less_than);

			command.expression2.expression = cond_exp;
		}

		dom_object.parent().find('.text_receives').text(_localizedStringsService.LocalizedStrings.getUI('text_receives'));

		command.expression1 = new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, "0", null, null, true);

		dom_object.parent().find('.var_value_expression').empty();

		VariableValueMenu.renderMenu(command, command.expression1, dom_object.parent().find('.var_value_expression'), function_obj);

		renderAlgorithm();
	}

	if (dom_object.hasClass('incrementation_variable')) {
		dom_object.parent().find('.text_inc_receives').text(_localizedStringsService.LocalizedStrings.getUI('text_receives'));

		var exp = new Models.ExpressionElement(Models.EXPRESSION_ELEMENTS.exp_op_exp, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), Models.ARITHMETIC_TYPES.plus, new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)]);

		command.expression3 = exp;

		VariableValueMenu.renderMenu(command, command.expression3.itens[0], dom_object.parent().find('.first_operand'), function_obj);

		renderOperator(command, function_obj, dom_object.parent().find('.operator'), command.expression3, 1);

		VariableValueMenu.renderMenu(command, command.expression3.itens[2], dom_object.parent().find('.second_operand'), function_obj);
	}
}

function manageClearExpressionElements(command, ref_object, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element) {
	if (dom_object.hasClass('variable_attribution')) {
		(0, _jquery2.default)(dom_object).parent().find('.text_receives').text('');
		command.expression1 = null;
		(0, _jquery2.default)(dom_object).parent().find('.var_value_expression').empty();
	}

	if (dom_object.hasClass('incrementation_variable')) {
		(0, _jquery2.default)(dom_object).parent().find('.text_inc_receives').text('');
		command.expression3 = null;
		(0, _jquery2.default)(dom_object).parent().find('.first_operand').empty();
		(0, _jquery2.default)(dom_object).parent().find('.operator').empty();
		(0, _jquery2.default)(dom_object).parent().find('.second_operand').empty();
	}
}

function addHandlers(command, function_obj, repeatNtimes_dom) {

	repeatNtimes_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, repeatNtimes_dom)) {
			repeatNtimes_dom.fadeOut();
		}
	});
}

function renderOperator(command, function_obj, temp_op, expression_element, index_op) {

	var menu_operator = (0, _jquery2.default)('<div class="ui dropdown"><div class="text"></div></div>');
	menu_operator.dropdown({
		values: [{
			name: '+',
			value: Models.ARITHMETIC_TYPES.plus,
			selected: expression_element.itens[index_op] == Models.ARITHMETIC_TYPES.plus
		}, {
			name: '-',
			value: Models.ARITHMETIC_TYPES.minus,
			selected: expression_element.itens[index_op] == Models.ARITHMETIC_TYPES.minus
		}, {
			name: '*',
			value: Models.ARITHMETIC_TYPES.multiplication,
			selected: expression_element.itens[index_op] == Models.ARITHMETIC_TYPES.multiplication
		}, {
			name: '/',
			value: Models.ARITHMETIC_TYPES.division,
			selected: expression_element.itens[index_op] == Models.ARITHMETIC_TYPES.division
		}, {
			name: '%',
			value: Models.ARITHMETIC_TYPES.module,
			selected: expression_element.itens[index_op] == Models.ARITHMETIC_TYPES.module
		}],
		onChange: function onChange(value, text, $selectedItem) {
			expression_element.itens[index_op] = value;
		}
	});
	temp_op.append(menu_operator);
}

/***/ }),

/***/ "./js/visualUI/commands/return.js":
/*!****************************************!*\
  !*** ./js/visualUI/commands/return.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _variable_value_menu = __webpack_require__(/*! ./variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenu = _interopRequireWildcard(_variable_value_menu);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui return created_element"> <i class="ui icon small reply"></i> <span> ' + _localizedStringsService.LocalizedStrings.getUI('text_return') + ' </span></div>');
}

function renderCommand(command, function_obj) {
	var el = (0, _jquery2.default)('<div class="ui return command_container"> <i class="ui icon small reply command_drag"></i> <i class="ui icon times red button_remove_command"></i> <span class="span_command_spec"> ' + _localizedStringsService.LocalizedStrings.getUI('text_return') + ' </span>  <div class="var_value_menu_div"></div></div>');
	el.data('command', command);

	addHandlers(command, function_obj, el);

	if (function_obj.return_type != _types.Types.VOID) {
		VariableValueMenu.renderMenu(command, command.variable_value_menu, el.find('.var_value_menu_div'), function_obj);
	} else {
		el.find('.var_value_menu_div').remove();
	}

	return el;
}

function addHandlers(command, function_obj, return_dom) {

	return_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, return_dom)) {
			return_dom.fadeOut();
		}
	});
}

/***/ }),

/***/ "./js/visualUI/commands/switch.js":
/*!****************************************!*\
  !*** ./js/visualUI/commands/switch.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;
exports.renderCase = renderCase;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

var _variable_value_menu = __webpack_require__(/*! ./variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenu = _interopRequireWildcard(_variable_value_menu);

var _contextualized_menu = __webpack_require__(/*! ./contextualized_menu */ "./js/visualUI/commands/contextualized_menu.js");

var ContextualizedMenu = _interopRequireWildcard(_contextualized_menu);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui switch created_element"> <i class="ui icon small random"></i> <span> ' + _localizedStringsService.LocalizedStrings.getUI('text_code_switch') + ' ( x ) { <br> ' + _localizedStringsService.LocalizedStrings.getUI('text_code_case') + ' 1: <br> ' + _localizedStringsService.LocalizedStrings.getUI('text_code_case') + ' 2: <br> } </span></div>');
}

function renderCommand(command, function_obj) {
	var ret = '';
	ret += '<div class="ui switch command_container"> <i class="ui icon small random command_drag" ></i> <i class="ui icon times red button_remove_command"></i> <div class="ui context_menu"></div> <span> ' + _localizedStringsService.LocalizedStrings.getUI('text_code_switch') + ' ( <div class="ui variable_to_switch"></div> ) <div class="ui all_cases_div"></div></span>';
	ret += '</div>';

	var el = (0, _jquery2.default)(ret);
	el.data('command', command);

	addHandlers(command, function_obj, el);

	ContextualizedMenu.renderMenu(command, el.find('.context_menu'), function_obj, el);

	VariableValueMenu.renderMenu(command, command.variable, el.find('.variable_to_switch'), function_obj);

	if (command.cases) {
		for (var i = 0; i < command.cases.length; i++) {
			renderCase(command.cases[i], command, function_obj, el.find('.all_cases_div'));
		}
	}

	return el;
}

function renderCase(switchcase, command, function_obj, el) {

	var casediv = (0, _jquery2.default)('<div class="ui case_div"><i class="ui icon times red button_remove_command"></i><span>' + _localizedStringsService.LocalizedStrings.getUI('text_code_case') + '</span> <div class="ui variable_case"></div>: <div class="case_commands_block"></div></div>');

	VariableValueMenu.renderMenu(command, switchcase.variable_value_menu, casediv.find('.variable_case'), function_obj);

	casediv.data('switchcase', switchcase);
	casediv.find('.case_commands_block').data('switchcase', switchcase);

	el.append(casediv);

	if (switchcase.commands_block) {
		for (var j = 0; j < switchcase.commands_block.length; j++) {
			CommandsManagement.renderCommand(switchcase.commands_block[j], (0, _jquery2.default)(casediv.find('.case_commands_block')[0]), 3, function_obj);
		}
	}

	casediv.find('.button_remove_command').on('click', function () {
		for (var i = 0; i < command.cases.length; i++) {
			if (switchcase == command.cases[i]) {
				delete command.cases[i];
				command.cases.splice(i, 1);
				casediv.remove();
				break;
			}
		}
	});
}

function addHandlers(command, function_obj, switch_dom) {

	switch_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, switch_dom)) {
			switch_dom.fadeOut();
		}
	});
}

/***/ }),

/***/ "./js/visualUI/commands/variable_value_menu.js":
/*!*****************************************************!*\
  !*** ./js/visualUI/commands/variable_value_menu.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.VAR_OR_VALUE_TYPES = undefined;
exports.renderMenu = renderMenu;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _attribution = __webpack_require__(/*! ./attribution */ "./js/visualUI/commands/attribution.js");

var AttribuitionsManagement = _interopRequireWildcard(_attribution);

var _writer = __webpack_require__(/*! ./writer */ "./js/visualUI/commands/writer.js");

var WritersManagement = _interopRequireWildcard(_writer);

var _repeatNtimes = __webpack_require__(/*! ./repeatNtimes */ "./js/visualUI/commands/repeatNtimes.js");

var RepeatNTimesManagement = _interopRequireWildcard(_repeatNtimes);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var VAR_OR_VALUE_TYPES = exports.VAR_OR_VALUE_TYPES = Object.freeze({ only_variable: 1, only_value: 2, only_function: 3, variable_and_function: 4, variable_and_value_opt: 5,
	value_and_function: 6, all: 7 });

function renderMenu(command, ref_object, dom_object, function_obj) {
	var size_field = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 2;
	var expression_element = arguments[5];

	// Verificar se o objeto atual trata-se de uma chamada de função e conferir se possui a quantidade correta de parâmetros
	// Caso não possua, tem que adicionar as variáveis que servirão de parâmetros:
	if (ref_object.function_called) {
		if (ref_object.function_called.parameters_list) {

			while (ref_object.function_called.parameters_list.length != ref_object.parameters_list.length) {
				if (ref_object.parameters_list.length > ref_object.function_called.parameters_list.length) {
					ref_object.parameters_list.pop();
				} else {
					ref_object.parameters_list.push(new Models.VariableValueMenu(VAR_OR_VALUE_TYPES.all, null, null, null, true));
				}
			}
		}
	}

	var menu_var_or_value = '<div class="ui dropdown menu_var_or_value_dom" data-varmenu="true"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';

	if (ref_object.variable_and_value == VAR_OR_VALUE_TYPES.only_variable) {

		menu_var_or_value = '<div class="ui dropdown menu_var_or_value_dom" data-varmenu="true"><div class="text"></div><i class="dropdown icon"></i><div class="menu menu_only_vars">';
		menu_var_or_value += '</div>';
	}

	if (ref_object.variable_and_value == VAR_OR_VALUE_TYPES.variable_and_function || ref_object.variable_and_value == VAR_OR_VALUE_TYPES.variable_and_value_opt || ref_object.variable_and_value == VAR_OR_VALUE_TYPES.all) {

		menu_var_or_value += '<div class="item" data-option="' + VAR_OR_VALUE_TYPES.only_variable + '"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('variable');
		menu_var_or_value += '<div class="menu menu_only_vars">';
		menu_var_or_value += '</div></div>';
	}

	if (ref_object.variable_and_value == VAR_OR_VALUE_TYPES.only_value) {
		menu_var_or_value = '<input type="text" class="width-dynamic" size="' + size_field + '" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />';
	}

	if (ref_object.variable_and_value == VAR_OR_VALUE_TYPES.variable_and_value_opt || ref_object.variable_and_value == VAR_OR_VALUE_TYPES.value_and_function || ref_object.variable_and_value == VAR_OR_VALUE_TYPES.all) {

		menu_var_or_value += '<div class="item" data-option="' + VAR_OR_VALUE_TYPES.only_value + '">' + _localizedStringsService.LocalizedStrings.getUI('text_value') + '</div>';
	}

	if (ref_object.variable_and_value == VAR_OR_VALUE_TYPES.only_function) {

		menu_var_or_value = '<div class="ui dropdown menu_var_or_value_dom" data-varmenu="true"><div class="text"></div><i class="dropdown icon"></i><div class="menu menu_only_functions">';
		menu_var_or_value += '</div>';
	}

	if (ref_object.variable_and_value == VAR_OR_VALUE_TYPES.variable_and_function || ref_object.variable_and_value == VAR_OR_VALUE_TYPES.value_and_function || ref_object.variable_and_value == VAR_OR_VALUE_TYPES.all) {

		menu_var_or_value += '<div class="item" data-option="' + VAR_OR_VALUE_TYPES.only_function + '"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('btn_function');
		menu_var_or_value += '<div class="menu menu_only_functions">';
		menu_var_or_value += '</div></div>';

		if (command.type == Models.COMMAND_TYPES.attribution) {
			menu_var_or_value += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
			menu_var_or_value += '<div class="menu">';
			menu_var_or_value += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
			menu_var_or_value += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
			menu_var_or_value += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
			menu_var_or_value += '</div></div>';
		}
	}

	menu_var_or_value += '</div></div>';

	menu_var_or_value = (0, _jquery2.default)(menu_var_or_value);

	dom_object.append(menu_var_or_value);

	ref_object.dom_object = menu_var_or_value;

	addHandlers(command, ref_object, dom_object, menu_var_or_value, function_obj, expression_element);

	addVariablesToMenu(function_obj, menu_var_or_value, ref_object, expression_element);

	addFunctionsToMenu(function_obj, menu_var_or_value, ref_object, expression_element);

	addIVProgFunctionsToMenu(function_obj, menu_var_or_value, ref_object, expression_element);

	if (ref_object.content || ref_object.function_called) {
		if (ref_object.content) {
			// Verificar se a variável ainda existe:
			var variable_fun = isVarInProgram(ref_object.content, function_obj);
			if (variable_fun) {
				ref_object.content = variable_fun;
				renderPreviousContent(function_obj, menu_var_or_value, ref_object, dom_object, command, expression_element);
			} else {
				if (ref_object.content && ref_object.content.type) {
					ref_object.content = null;
					appendSelectText(ref_object, menu_var_or_value);
				} else {
					renderPreviousContent(function_obj, menu_var_or_value, ref_object, dom_object, command, expression_element);
				}
			}
		} else if (ref_object.function_called) {
			// Verificar se a função ainda existe:
			var ret_function = isFunctionInProgram(ref_object.function_called);
			if (ret_function) {
				ref_object.function_called = ret_function;
				renderPreviousContent(function_obj, menu_var_or_value, ref_object, dom_object, command, expression_element);
			} else {
				ref_object.content = null;
				ref_object.row = null;
				ref_object.column = null;
				delete ref_object.function_called;
				delete ref_object.parameters_list;
				appendSelectText(ref_object, menu_var_or_value);
			}
		}
	} else {
		appendSelectText(ref_object, menu_var_or_value);
	}
}

function appendSelectText(ref_object, menu_var_or_value) {
	switch (ref_object.variable_and_value) {
		case VAR_OR_VALUE_TYPES.only_variable:
			menu_var_or_value.find('.text').append('<i>' + _localizedStringsService.LocalizedStrings.getUI('var_menu_select_var') + '</i>');
			break;
		case VAR_OR_VALUE_TYPES.all:
			menu_var_or_value.find('.text').append('<i>' + _localizedStringsService.LocalizedStrings.getUI('var_menu_select_all') + '</i>');
			break;
		case VAR_OR_VALUE_TYPES.variable_and_function:
			menu_var_or_value.find('.text').append('<i>' + _localizedStringsService.LocalizedStrings.getUI('var_menu_select_all') + '</i>');
			break;
		case VAR_OR_VALUE_TYPES.only_function:
			menu_var_or_value.find('.text').append('<i>' + _localizedStringsService.LocalizedStrings.getUI('var_menu_select_function') + '</i>');
			break;
	}
}

function isFunctionInProgram(function_called_obj) {
	if (function_called_obj.name) {
		if (window.program_obj.functions) {
			for (var i = 0; i < window.program_obj.functions.length; i++) {
				if (window.program_obj.functions[i] == function_called_obj) {
					return window.program_obj.functions[i];
				}
			}
			for (var i = 0; i < window.program_obj.functions.length; i++) {
				if (window.program_obj.functions[i].name == function_called_obj.name) {
					return window.program_obj.functions[i];
				}
			}
		}
	} else if (function_called_obj.identifier) {
		for (var i = 0; i < window.system_functions.length; i++) {
			if (window.system_functions[i].identifier == function_called_obj.identifier) {
				return window.system_functions[i];
			}
		}
	}

	return null;
}

function isVarInProgram(var_obj, function_obj) {
	// Verify in locals:
	if (function_obj.variables_list) {
		for (var i = 0; i < function_obj.variables_list.length; i++) {
			if (function_obj.variables_list[i] == var_obj) {
				return function_obj.variables_list[i];
			}
		}
	}
	// Verify in parameters:
	if (function_obj.parameters_list) {
		for (var i = 0; i < function_obj.parameters_list.length; i++) {
			if (function_obj.parameters_list[i] == var_obj) {
				return function_obj.parameters_list[i];
			}
		}
	}
	// Verify in globals:
	if (window.program_obj.globals) {
		for (var i = 0; i < window.program_obj.globals.length; i++) {
			if (window.program_obj.globals[i] == var_obj) {
				return window.program_obj.globals[i];
			}
		}
	}

	// If not found, verify if the reference was lost
	if (var_obj) {
		if (function_obj.variables_list) {
			for (var i = 0; i < function_obj.variables_list.length; i++) {
				if (function_obj.variables_list[i].name == var_obj.name) {
					return function_obj.variables_list[i];
				}
			}
		}
		if (function_obj.parameters_list) {
			for (var i = 0; i < function_obj.parameters_list.length; i++) {
				if (function_obj.parameters_list[i].name == var_obj.name) {
					return function_obj.parameters_list[i];
				}
			}
		}
		if (window.program_obj.globals) {
			for (var i = 0; i < window.program_obj.globals.length; i++) {
				if (window.program_obj.globals[i].name == var_obj.name) {
					return window.program_obj.globals[i];
				}
			}
		}
	}

	return null;
}

function renderPreviousContent(function_obj, menu_var_or_value, ref_object, dom_object, command, expression_element) {

	if (ref_object.function_called) {

		menu_var_or_value.remove();
		variableValueMenuCode(command, ref_object, dom_object, function_obj, menu_var_or_value, expression_element);
	} else if (ref_object.content.type) {

		menu_var_or_value.remove();
		variableValueMenuCode(command, ref_object, dom_object, function_obj, menu_var_or_value, expression_element);
	} else {

		menu_var_or_value.remove();
		variableValueMenuCode(command, ref_object, dom_object, function_obj, menu_var_or_value, expression_element);
	}
}

function variableValueMenuCode(command, variable_obj, dom_object, function_obj, menu_var_or_value, expression_element) {

	if (variable_obj.content || variable_obj.function_called) {
		// Verificar se a variável ainda existe:
		var var_fun = isVarInProgram(variable_obj.content, function_obj);

		if (var_fun) {
			variable_obj.content = var_fun;
		} else {
			if (variable_obj.content && variable_obj.content.type) {
				variable_obj.content = null;
				appendSelectText(variable_obj, menu_var_or_value);
			}
		}
	} else {
		appendSelectText(variable_obj, menu_var_or_value);
	}

	if (variable_obj.content == null && variable_obj.function_called == null) {
		renderMenu(command, variable_obj, dom_object, function_obj, 2, expression_element);
		return;
	}

	var ret = '';
	if (variable_obj.function_called) {

		if (variable_obj.function_called.parameters_list == null || variable_obj.function_called.length == 0) {

			menu_var_or_value.find('.text').text(' ');
			dom_object.find('.menu_var_or_value_dom').remove();

			var parameters_menu;

			if (variable_obj.function_called.name) {
				parameters_menu = '<div class="parameters_function_called"> ' + variable_obj.function_called.name + ' <span> ( </span>';
			} else {
				parameters_menu = '<div class="parameters_function_called"> <i>' + _localizedStringsService.LocalizedStrings.getUI(variable_obj.function_called.category) + '.' + _localizedStringsService.LocalizedStrings.getUI(variable_obj.function_called.identifier) + '</i> <span> ( </span>';
			}

			parameters_menu += '<span> ) </span></div>';

			parameters_menu = (0, _jquery2.default)(parameters_menu);

			dom_object.append(parameters_menu);

			var context_menu = '<div class="ui dropdown context_menu_clear"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
			context_menu += '<div class="item" data-clear="true">' + _localizedStringsService.LocalizedStrings.getUI('btn_clear') + '</div>';

			if (command.type == Models.COMMAND_TYPES.attribution) {
				context_menu += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
				context_menu += '<div class="menu">';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
				context_menu += '</div></div>';
			}

			context_menu += '</div></div>';

			context_menu = (0, _jquery2.default)(context_menu);

			context_menu.insertAfter(dom_object.find('.parameters_function_called'));

			context_menu.dropdown({
				onChange: function onChange(value, text, $selectedItem) {
					console.log('S1');
					if ($selectedItem.data('clear')) {
						console.log('PP1');
						dom_object.text('');

						variable_obj.content = null;
						variable_obj.row = null;
						variable_obj.column = null;
						delete variable_obj.function_called;
						delete variable_obj.parameters_list;

						renderMenu(command, variable_obj, dom_object, function_obj, 2, expression_element);
					}

					if ($selectedItem.data('exp')) {
						AttribuitionsManagement.manageExpressionElements(command, variable_obj, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
					}
				},
				selectOnKeydown: false
			});
		} else {

			menu_var_or_value.find('.text').text(' ');
			dom_object.find('.menu_var_or_value_dom').remove();

			var parameters_menu;

			if (variable_obj.function_called.name) {
				parameters_menu = '<div class="parameters_function_called"> ' + variable_obj.function_called.name + ' <span> ( </span>';
			} else {
				parameters_menu = '<div class="parameters_function_called"> <i>' + _localizedStringsService.LocalizedStrings.getUI(variable_obj.function_called.category) + '.' + _localizedStringsService.LocalizedStrings.getUI(variable_obj.function_called.identifier) + '</i> <span> ( </span>';
			}

			for (var j = 0; j < variable_obj.function_called.parameters_list.length; j++) {
				parameters_menu += '<div class="render_style_param parameter_' + j + '"></div>';
				if (j + 1 != variable_obj.function_called.parameters_list.length) {
					parameters_menu += ' , ';
				}
			}
			parameters_menu += '<span> ) </span></div>';

			parameters_menu = (0, _jquery2.default)(parameters_menu);

			dom_object.append(parameters_menu);

			for (var j = 0; j < variable_obj.function_called.parameters_list.length; j++) {
				renderMenu(command, variable_obj.parameters_list[j], parameters_menu.find('.parameter_' + j), function_obj, 2, expression_element);
			}

			var context_menu = '<div class="ui dropdown context_menu_clear"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
			context_menu += '<div class="item" data-clear="true">' + _localizedStringsService.LocalizedStrings.getUI('btn_clear') + '</div>';

			if (command.type == Models.COMMAND_TYPES.attribution) {
				context_menu += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
				context_menu += '<div class="menu">';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
				context_menu += '</div></div>';
			}

			context_menu += '</div></div>';

			context_menu = (0, _jquery2.default)(context_menu);

			context_menu.insertAfter(parameters_menu);

			context_menu.dropdown({
				onChange: function onChange(value, text, $selectedItem) {
					console.log('S2');
					if ($selectedItem.data('clear')) {
						console.log('PP2');
						dom_object.text('');

						variable_obj.content = null;
						variable_obj.row = null;
						variable_obj.column = null;
						delete variable_obj.function_called;
						delete variable_obj.parameters_list;

						renderMenu(command, variable_obj, dom_object, function_obj, 2, expression_element);
					}

					if ($selectedItem.data('exp')) {
						AttribuitionsManagement.manageExpressionElements(command, variable_obj, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
					}
				},
				selectOnKeydown: false
			});
		}
	} else if (variable_obj.content.type) {

		var variable_render = "";

		if (variable_obj.content.dimensions == 1 && variable_obj.dimensions != 1) {

			variable_render = '<div class="variable_rendered"> <span class="var_name">' + variable_obj.content.name + '</span>';

			variable_render += ' <span>[ </span> <div class="column_container"></div> <span> ]</span>';

			variable_render += '</div>';

			variable_render = (0, _jquery2.default)(variable_render);

			dom_object.append(variable_render);

			var context_menu = '<div class="ui dropdown context_menu_clear"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
			context_menu += '<div class="item" data-clear="true">' + _localizedStringsService.LocalizedStrings.getUI('btn_clear') + '</div>';

			if (command.type == Models.COMMAND_TYPES.attribution) {
				context_menu += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
				context_menu += '<div class="menu">';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
				context_menu += '</div></div>';
			}

			context_menu += '</div></div>';

			context_menu = (0, _jquery2.default)(context_menu);

			variable_render.append(context_menu);

			context_menu.dropdown({
				onChange: function onChange(value, text, $selectedItem) {
					console.log('S3');
					if ($selectedItem.data('clear')) {
						console.log('PP3');
						dom_object.text('');

						variable_obj.content = null;
						variable_obj.row = null;
						variable_obj.column = null;
						delete variable_obj.function_called;
						delete variable_obj.parameters_list;

						renderMenu(command, variable_obj, dom_object, function_obj, 2, expression_element);
					}

					if ($selectedItem.data('exp')) {
						AttribuitionsManagement.manageExpressionElements(command, variable_obj, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
					}
				},
				selectOnKeydown: false
			});

			if (!variable_obj.column) {
				variable_obj.column = new Models.VariableValueMenu(VAR_OR_VALUE_TYPES.all, null, null, null, true);
			}

			variableValueMenuCode(command, variable_obj.column, (0, _jquery2.default)(variable_render.find('.column_container')), function_obj, menu_var_or_value, expression_element);
		} else if (variable_obj.content.dimensions == 2 && variable_obj.dimensions != 2) {

			variable_render = '<div class="variable_rendered"> <span class="var_name">' + variable_obj.content.name + '</span>';

			variable_render += ' <span>[ </span> <div class="row_container"></div> <span> ]</span>';
			variable_render += ' <span>[ </span> <div class="column_container"></div> <span> ] </span>';

			variable_render += '</div>';

			variable_render = (0, _jquery2.default)(variable_render);

			dom_object.append(variable_render);

			var context_menu = '<div class="ui dropdown context_menu_clear"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
			context_menu += '<div class="item" data-clear="true">' + _localizedStringsService.LocalizedStrings.getUI('btn_clear') + '</div>';

			if (command.type == Models.COMMAND_TYPES.attribution) {
				context_menu += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
				context_menu += '<div class="menu">';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
				context_menu += '</div></div>';
			}

			context_menu += '</div></div>';

			context_menu = (0, _jquery2.default)(context_menu);

			variable_render.append(context_menu);

			context_menu.dropdown({
				onChange: function onChange(value, text, $selectedItem) {
					console.log('S4');
					if ($selectedItem.data('clear')) {
						console.log('PP4');
						dom_object.text('');

						variable_obj.content = null;
						variable_obj.row = null;
						variable_obj.column = null;
						delete variable_obj.function_called;
						delete variable_obj.parameters_list;

						renderMenu(command, variable_obj, dom_object, function_obj, 2, expression_element);
					}

					if ($selectedItem.data('exp')) {
						AttribuitionsManagement.manageExpressionElements(command, variable_obj, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
					}
				},
				selectOnKeydown: false
			});

			if (!variable_obj.column) {
				variable_obj.column = new Models.VariableValueMenu(VAR_OR_VALUE_TYPES.all, null, null, null, true);
			}
			if (!variable_obj.row) {
				variable_obj.row = new Models.VariableValueMenu(VAR_OR_VALUE_TYPES.all, null, null, null, true);
			}

			variableValueMenuCode(command, variable_obj.row, (0, _jquery2.default)(variable_render.find('.row_container')), function_obj, menu_var_or_value, expression_element);
			variableValueMenuCode(command, variable_obj.column, (0, _jquery2.default)(variable_render.find('.column_container')), function_obj, menu_var_or_value, expression_element);
		} else {

			variable_render = '<div class="variable_rendered"> <span class="var_name">' + variable_obj.content.name + '</span>';

			variable_render += '</div>';

			variable_render = (0, _jquery2.default)(variable_render);

			dom_object.append(variable_render);

			var context_menu = '<div class="ui dropdown context_menu_clear"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
			context_menu += '<div class="item" data-clear="true">' + _localizedStringsService.LocalizedStrings.getUI('btn_clear') + '</div>';

			if (command.type == Models.COMMAND_TYPES.attribution && !dom_object.hasClass('var_attributed')) {
				console.log('dom_object6');
				console.log(dom_object);
				context_menu += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
				context_menu += '<div class="menu">';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
				context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
				context_menu += '</div></div>';
			}

			context_menu += '</div></div>';

			context_menu = (0, _jquery2.default)(context_menu);

			variable_render.append(context_menu);

			context_menu.dropdown({
				onChange: function onChange(value, text, $selectedItem) {
					console.log('S5');
					if ($selectedItem.data('clear')) {
						console.log('PP5');
						dom_object.text('');

						variable_obj.content = null;
						variable_obj.row = null;
						variable_obj.column = null;

						delete variable_obj.function_called;
						delete variable_obj.parameters_list;

						renderMenu(command, variable_obj, dom_object, function_obj, 2, expression_element);
					}

					if ($selectedItem.data('exp')) {
						AttribuitionsManagement.manageExpressionElements(command, variable_obj, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
					}
				},
				selectOnKeydown: false
			});
		}
	} else {

		var variable_render = '<div class="variable_rendered"> <span class="var_name">' + variable_obj.content + '</span>';
		variable_render += '</div>';

		variable_render = (0, _jquery2.default)(variable_render);

		dom_object.append(variable_render);

		var context_menu = '<div class="ui dropdown context_menu_clear"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
		context_menu += '<div class="item" data-clear="true">' + _localizedStringsService.LocalizedStrings.getUI('btn_clear') + '</div>';

		if (command.type == Models.COMMAND_TYPES.attribution) {
			context_menu += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
			context_menu += '<div class="menu">';
			context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
			context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
			context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
			context_menu += '</div></div>';
		}

		context_menu += '</div></div>';

		context_menu = (0, _jquery2.default)(context_menu);

		if (variable_obj.variable_and_value != VAR_OR_VALUE_TYPES.only_value) {
			context_menu.insertAfter(variable_render);
		}

		context_menu.dropdown({
			onChange: function onChange(value, text, $selectedItem) {
				console.log('S6');
				if ($selectedItem.data('clear')) {
					console.log('PP6');
					dom_object.text('');

					variable_obj.content = null;
					variable_obj.row = null;
					variable_obj.column = null;

					delete variable_obj.function_called;
					delete variable_obj.parameters_list;

					dom_object.find('.value_rendered').remove();
					dom_object.find('.context_menu_clear').remove();
					dom_object.find('.width-dynamic-minus').remove();

					renderMenu(command, variable_obj, dom_object, function_obj, 2, expression_element);
				}

				if ($selectedItem.data('exp')) {
					AttribuitionsManagement.manageExpressionElements(command, variable_obj, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
				}
			},
			selectOnKeydown: false
		});

		variable_render.on('click', function (e) {
			variable_render.remove();
			variable_render.empty();
			variable_render.remove();
			dom_object.empty();
			dom_object.append('<span class="menu_var_or_value_dom"> </span>');

			openInputToValue(command, variable_obj, dom_object, menu_var_or_value, function_obj, expression_element);
		});
	}
}

function addIVProgFunctionsToMenu(function_obj, menu_var_or_value, ref_object, expression_element) {
	var sub_menu = menu_var_or_value.find('.menu_only_functions');
	sub_menu.append('<div class="divider"></div><div class="header">' + _localizedStringsService.LocalizedStrings.getUI('text_header_ivprog_functions') + '</div>');
	sub_menu.append('<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_menu_functions_math') + '<div class="menu menu_math_functions"></div></div>');
	sub_menu.append('<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_menu_functions_text') + '<div class="menu menu_text_functions"></div></div>');
	sub_menu.append('<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_menu_functions_arrangement') + '<div class="menu menu_arrangement_functions"></div></div>');
	sub_menu.append('<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_menu_functions_conversion') + '<div class="menu menu_conversion_functions"></div></div>');

	// Insert Math functions:
	for (var i = 0; i < window.system_functions.length; i++) {
		var t = (0, _jquery2.default)('<div class="item"></div>');
		t.data('function_reference', window.system_functions[i]);
		t.data('option', VAR_OR_VALUE_TYPES.only_function);
		t.text(_localizedStringsService.LocalizedStrings.getUI(window.system_functions[i].identifier));

		switch (window.system_functions[i].category) {
			case Models.SYSTEM_FUNCTIONS_CATEGORIES.math:
				sub_menu.find('.menu_math_functions').append(t);
				break;
			case Models.SYSTEM_FUNCTIONS_CATEGORIES.text:
				sub_menu.find('.menu_text_functions').append(t);
				break;
			case Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement:
				sub_menu.find('.menu_arrangement_functions').append(t);
				break;
			case Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion:
				sub_menu.find('.menu_conversion_functions').append(t);
				break;
		}
	}
}

function addFunctionsToMenu(function_obj, menu_var_or_value, ref_object, expression_element) {
	var sub_menu = menu_var_or_value.find('.menu_only_functions');
	sub_menu.text('');

	for (var i = 0; i < window.program_obj.functions.length; i++) {
		var temp = (0, _jquery2.default)('<div class="item" data-option="' + VAR_OR_VALUE_TYPES.only_function + '">' + window.program_obj.functions[i].name + ' </div>');
		temp.data('function_reference', window.program_obj.functions[i]);
		sub_menu.append(temp);
	}
}

function addVariablesToMenu(function_obj, menu_var_or_value, ref_object, expression_element) {

	var sub_menu = menu_var_or_value.find('.menu_only_vars');
	sub_menu.text('');
	var is_there = false;

	if (window.program_obj.globals) {

		if (ref_object.include_constant) {
			for (var i = 0; i < window.program_obj.globals.length; i++) {
				var temp = (0, _jquery2.default)('<div class="item" data-option="' + VAR_OR_VALUE_TYPES.only_variable + '">' + window.program_obj.globals[i].name + ' </div>');
				temp.data('variable_reference', window.program_obj.globals[i]);
				sub_menu.append(temp);
				is_there = true;
			}
		} else {
			for (var i = 0; i < window.program_obj.globals.length; i++) {
				if (!window.program_obj.globals[i].is_constant) {
					var temp = (0, _jquery2.default)('<div class="item" data-option="' + VAR_OR_VALUE_TYPES.only_variable + '">' + window.program_obj.globals[i].name + ' </div>');
					temp.data('variable_reference', window.program_obj.globals[i]);
					sub_menu.append(temp);
					is_there = true;
				}
			}
		}
	}

	if (function_obj.parameters_list) {
		for (var i = 0; i < function_obj.parameters_list.length; i++) {
			var temp = (0, _jquery2.default)('<div class="item" data-option="' + VAR_OR_VALUE_TYPES.only_variable + '">' + function_obj.parameters_list[i].name + ' </div>');
			temp.data('variable_reference', function_obj.parameters_list[i]);
			sub_menu.append(temp);
			is_there = true;
		}
	}

	if (function_obj.variables_list) {
		for (var i = 0; i < function_obj.variables_list.length; i++) {
			var temp = (0, _jquery2.default)('<div class="item" data-option="' + VAR_OR_VALUE_TYPES.only_variable + '">' + function_obj.variables_list[i].name + ' </div>');
			temp.data('variable_reference', function_obj.variables_list[i]);
			sub_menu.append(temp);
			is_there = true;
		}
	}
	if (!is_there) {
		sub_menu.append((0, _jquery2.default)('<div class="header">' + _localizedStringsService.LocalizedStrings.getUI('text_none_variable') + '</div>'));
		sub_menu.append((0, _jquery2.default)('<div class="item disabled">' + _localizedStringsService.LocalizedStrings.getUI('text_none_variable_instruction') + '</div>'));
	}
}

function addHandlers(command, ref_object, dom_object, menu_var_or_value, function_obj, expression_element) {

	if (ref_object.variable_and_value != VAR_OR_VALUE_TYPES.only_value) {
		menu_var_or_value.dropdown({
			onChange: function onChange(value, text, $selectedItem) {
				console.log('S7');
				dom_object.find('.var_name').remove();
				switch ($selectedItem.data('option')) {
					case VAR_OR_VALUE_TYPES.only_function:
						openInputToFunction(command, ref_object, dom_object, menu_var_or_value, function_obj, (0, _jquery2.default)($selectedItem).data('function_reference'), expression_element);
						break;

					case VAR_OR_VALUE_TYPES.only_value:
						openInputToValue(command, ref_object, dom_object, menu_var_or_value, function_obj, expression_element);
						break;

					case VAR_OR_VALUE_TYPES.only_variable:
						openInputToVariable(command, ref_object, dom_object, menu_var_or_value, function_obj, (0, _jquery2.default)($selectedItem).data('variable_reference'), expression_element);
						break;
				}

				if ($selectedItem.data('exp')) {
					AttribuitionsManagement.manageExpressionElements(command, ref_object, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
				}

				if (command.type == Models.COMMAND_TYPES.repeatNtimes) {
					RepeatNTimesManagement.manageExpressionElements(command, ref_object, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
				}
			},
			selectOnKeydown: false
		});
	}

	dom_object.find('.width-dynamic').on('input', function () {
		var inputWidth = (0, _jquery2.default)(this).textWidth() + 10;
		(0, _jquery2.default)(this).focus();

		var tmpStr = (0, _jquery2.default)(this).val();
		(0, _jquery2.default)(this).val('');
		(0, _jquery2.default)(this).val(tmpStr);

		(0, _jquery2.default)(this).css({
			width: inputWidth
		});
	}).trigger('input');

	if (command.type == Models.COMMAND_TYPES.comment) {
		dom_object.parent().on('click', function (e) {
			dom_object.find('.value_rendered').remove();
			dom_object.find('.value_rendered').empty();
			dom_object.find('.value_rendered').remove();
			dom_object.empty();
			dom_object.append('<span class="menu_var_or_value_dom"> </span>');

			openInputToValue(command, ref_object, dom_object, menu_var_or_value, function_obj, expression_element);
		});
	}
}

function openInputToFunction(command, ref_object, dom_object, menu_var_or_value, function_obj, function_selected, expression_element) {

	ref_object.function_called = function_selected;
	ref_object.parameters_list = [];

	if (function_selected.parameters_list != null && function_selected.parameters_list.length > 0) {

		menu_var_or_value.find('.text').text(' ');
		dom_object.find('.menu_var_or_value_dom').remove();

		var parameters_menu;
		if (function_selected.name) {
			parameters_menu = '<div class="parameters_function_called"> ' + function_selected.name + ' <span> ( </span>';
		} else {
			parameters_menu = '<div class="parameters_function_called"> <i>' + _localizedStringsService.LocalizedStrings.getUI(function_selected.category) + '.' + _localizedStringsService.LocalizedStrings.getUI(function_selected.identifier) + '</i> <span> ( </span>';
		}
		for (var j = 0; j < function_selected.parameters_list.length; j++) {
			parameters_menu += '<div class="render_style_param parameter_' + j + '"></div>';
			if (j + 1 != function_selected.parameters_list.length) {
				parameters_menu += ' , ';
			}
		}
		parameters_menu += '<span> ) </span></div>';

		parameters_menu = (0, _jquery2.default)(parameters_menu);

		dom_object.append(parameters_menu);

		for (var j = 0; j < function_selected.parameters_list.length; j++) {
			var temp;
			if (function_selected.parameters_list[j].dimensions > 0) {
				temp = new Models.VariableValueMenu(VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true, function_selected.parameters_list[j].dimensions);
			} else {
				temp = new Models.VariableValueMenu(VAR_OR_VALUE_TYPES.all, null, null, null, true);
			}
			ref_object.parameters_list.push(temp);
			renderMenu(command, temp, parameters_menu.find('.parameter_' + j), function_obj, 2, expression_element);
		}

		var context_menu = '<div class="ui dropdown context_menu_clear"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
		context_menu += '<div class="item" data-clear="true">' + _localizedStringsService.LocalizedStrings.getUI('btn_clear') + '</div>';

		if (command.type == Models.COMMAND_TYPES.attribution) {
			context_menu += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
			context_menu += '<div class="menu">';
			context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
			context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
			context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
			context_menu += '</div></div>';
		}

		context_menu += '</div></div>';

		context_menu = (0, _jquery2.default)(context_menu);

		context_menu.insertAfter(dom_object.find('.parameters_function_called'));

		context_menu.dropdown({
			onChange: function onChange(value, text, $selectedItem) {
				console.log('S8');
				if ($selectedItem.data('clear')) {
					console.log('PP7');
					dom_object.text('');

					ref_object.content = null;
					ref_object.row = null;
					ref_object.column = null;
					delete ref_object.function_called;
					delete ref_object.parameters_list;

					renderMenu(command, ref_object, dom_object, function_obj, 2, expression_element);
				}

				if ($selectedItem.data('exp')) {
					AttribuitionsManagement.manageExpressionElements(command, ref_object, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
				}
			},
			selectOnKeydown: false
		});
	} else {
		menu_var_or_value.find('.text').text(' ');
		dom_object.find('.menu_var_or_value_dom').remove();

		var parameters_menu;

		if (function_selected.name) {
			parameters_menu = '<div class="parameters_function_called"> ' + function_selected.name + ' <span> ( </span>';
		} else {
			parameters_menu = '<div class="parameters_function_called"> <i>' + _localizedStringsService.LocalizedStrings.getUI(function_selected.category) + '.' + _localizedStringsService.LocalizedStrings.getUI(function_selected.identifier) + '</i> <span> ( </span>';
		}

		parameters_menu += '<span> ) </span></div>';

		parameters_menu = (0, _jquery2.default)(parameters_menu);

		dom_object.append(parameters_menu);

		var context_menu = '<div class="ui dropdown context_menu_clear"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
		context_menu += '<div class="item" data-clear="true">' + _localizedStringsService.LocalizedStrings.getUI('btn_clear') + '</div>';

		if (command.type == Models.COMMAND_TYPES.attribution) {
			context_menu += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
			context_menu += '<div class="menu">';
			context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
			context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
			context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
			context_menu += '</div></div>';
		}

		context_menu += '</div></div>';

		context_menu = (0, _jquery2.default)(context_menu);

		context_menu.insertAfter(dom_object.find('.parameters_function_called'));

		context_menu.dropdown({
			onChange: function onChange(value, text, $selectedItem) {
				console.log('S9');
				if ($selectedItem.data('clear')) {
					console.log('PP8');
					dom_object.text('');

					ref_object.content = null;
					ref_object.row = null;
					ref_object.column = null;
					delete ref_object.function_called;
					delete ref_object.parameters_list;

					renderMenu(command, ref_object, dom_object, function_obj, 2, expression_element);
				}

				if ($selectedItem.data('exp')) {
					AttribuitionsManagement.manageExpressionElements(command, ref_object, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
				}
			},
			selectOnKeydown: false
		});
	}

	if (command.type == Models.COMMAND_TYPES.attribution) {
		AttribuitionsManagement.renderMenuOperations(command, ref_object, dom_object, menu_var_or_value, function_obj);
	}
}

function openInputToVariable(command, ref_object, dom_object, menu_var_or_value, function_obj, variable_selected, expression_element) {

	ref_object.content = variable_selected;

	menu_var_or_value.find('.text').text(' ');
	dom_object.find('.menu_var_or_value_dom').remove();

	var variable_render = '<div class="variable_rendered"> <span class="var_name">' + variable_selected.name + '</span>';

	if (variable_selected.dimensions == 1 && ref_object.dimensions != 1) {
		variable_render += ' <span>[ </span> <div class="column_container"></div> <span> ]</span>';
	}
	if (variable_selected.dimensions == 2 && ref_object.dimensions != 2) {
		variable_render += ' <span>[ </span> <div class="row_container"></div> <span> ]</span> ';
		variable_render += ' <span>[ </span> <div class="column_container"></div> <span> ]</span>';
	}

	variable_render += '</div>';

	variable_render = (0, _jquery2.default)(variable_render);

	dom_object.append(variable_render);

	if (variable_selected.dimensions == 1 && ref_object.dimensions != 1) {
		ref_object.column = new Models.VariableValueMenu(VAR_OR_VALUE_TYPES.all, null, null, null, true);
		renderMenu(command, ref_object.column, variable_render.find('.column_container'), function_obj, 2, expression_element);
	}
	if (variable_selected.dimensions == 2 && ref_object.dimensions != 2) {
		ref_object.row = new Models.VariableValueMenu(VAR_OR_VALUE_TYPES.all, null, null, null, true);
		renderMenu(command, ref_object.row, variable_render.find('.row_container'), function_obj, 2, expression_element);

		ref_object.column = new Models.VariableValueMenu(VAR_OR_VALUE_TYPES.all, null, null, null, true);
		renderMenu(command, ref_object.column, variable_render.find('.column_container'), function_obj, 2, expression_element);
	}

	var context_menu = '<div class="ui dropdown context_menu_clear"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
	context_menu += '<div class="item" data-clear="true">' + _localizedStringsService.LocalizedStrings.getUI('btn_clear') + '</div>';

	if (command.type == Models.COMMAND_TYPES.attribution && !dom_object.hasClass('var_attributed')) {
		console.log("dom_object 10: ");
		console.log(dom_object);
		context_menu += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
		context_menu += '<div class="menu">';
		context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
		context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
		context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
		context_menu += '</div></div>';
	}

	context_menu += '</div></div>';

	context_menu = (0, _jquery2.default)(context_menu);

	context_menu.insertAfter(dom_object.find('.variable_rendered'));

	context_menu.dropdown({
		onChange: function onChange(value, text, $selectedItem) {
			console.log('S10');
			if ($selectedItem.data('clear')) {
				console.log('PP9');
				dom_object.text('');

				ref_object.content = null;
				ref_object.row = null;
				ref_object.column = null;

				delete ref_object.function_called;
				delete ref_object.parameters_list;

				renderMenu(command, ref_object, dom_object, function_obj, 2, expression_element);
			}

			if ($selectedItem.data('exp')) {
				AttribuitionsManagement.manageExpressionElements(command, ref_object, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
			}

			if (command.type == Models.COMMAND_TYPES.repeatNtimes) {
				RepeatNTimesManagement.manageClearExpressionElements(command, ref_object, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
			}
		},
		selectOnKeydown: false
	});

	if (command.type == Models.COMMAND_TYPES.attribution) {
		AttribuitionsManagement.renderMenuOperations(command, ref_object, dom_object, menu_var_or_value, function_obj, variable_selected);
	}
}

function openInputToValue(command, ref_object, dom_object, menu_var_or_value, function_obj, expression_element) {

	if (ref_object.content == null) {
		ref_object.content = "";
	}

	menu_var_or_value.find('.text').text(' ');
	var field = (0, _jquery2.default)('<input type="text" size="2" class="width-dynamic-minus" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />');
	field.insertBefore(dom_object.find('.menu_var_or_value_dom'));
	var rendered = (0, _jquery2.default)('<div class="value_rendered"></div>');
	rendered.insertBefore(field);

	field.focus();
	field.val(ref_object.content);

	var context_menu = '<div class="ui dropdown context_menu_clear"><div class="text"></div><i class="dropdown icon"></i><div class="menu">';
	context_menu += '<div class="item" data-clear="true">' + _localizedStringsService.LocalizedStrings.getUI('btn_clear') + '</div>';

	if (command.type == Models.COMMAND_TYPES.attribution) {
		context_menu += '<div class="item"><i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('text_change');
		context_menu += '<div class="menu">';
		context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.exp_op_exp + '">EXP OP EXP</div>';
		context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.op_exp + '">OP EXP</div>';
		context_menu += '<div class="item" data-exp="' + Models.EXPRESSION_ELEMENTS.par_exp_par + '">( EXP )</div>';
		context_menu += '</div></div>';
	}

	context_menu += '</div></div>';

	context_menu = (0, _jquery2.default)(context_menu);

	dom_object.find('.menu_var_or_value_dom').remove();

	if (ref_object.variable_and_value != VAR_OR_VALUE_TYPES.only_value) {
		context_menu.insertAfter(field);
	}

	context_menu.dropdown({
		onChange: function onChange(value, text, $selectedItem) {
			console.log('S11');
			if ($selectedItem.data('clear')) {
				console.log('PP10');
				dom_object.text('');

				dom_object.find('.value_rendered').remove();
				dom_object.find('.context_menu_clear').remove();
				dom_object.find('.width-dynamic-minus').remove();

				ref_object.content = null;
				ref_object.row = null;
				ref_object.column = null;

				delete ref_object.function_called;
				delete ref_object.parameters_list;

				renderMenu(command, ref_object, dom_object, function_obj, 2, expression_element);
			}

			if ($selectedItem.data('exp')) {
				AttribuitionsManagement.manageExpressionElements(command, ref_object, dom_object, menu_var_or_value, function_obj, $selectedItem, expression_element);
			}
		},
		selectOnKeydown: false
	});

	dom_object.find('.width-dynamic-minus').focusout(function () {
		if ((0, _jquery2.default)(this).val().trim()) {
			ref_object.content = (0, _jquery2.default)(this).val().trim();
		}

		rendered.text(ref_object.content);
		(0, _jquery2.default)(this).remove();
	});

	dom_object.find('.width-dynamic-minus').on('keydown', function (e) {
		var code = e.keyCode || e.which;
		if (code == 13) {
			if ((0, _jquery2.default)(this).val().trim()) {
				ref_object.content = (0, _jquery2.default)(this).val().trim();
			}
			rendered.text(ref_object.content);

			(0, _jquery2.default)(this).remove();
		}
		if (code == 27) {
			rendered.text(ref_object.content);

			(0, _jquery2.default)(this).remove();
		}
	});

	if (command.type == Models.COMMAND_TYPES.comment) {
		/*rendered.parent().on('click', function(e) {
  	rendered.parent().off();
  	console.log("TTT14");
  	rendered.remove();
  	rendered.empty();
  	rendered.remove();
  	dom_object.empty();
  	dom_object.append('<span class="menu_var_or_value_dom"> </span>');
  	
  	openInputToValue(command, ref_object, dom_object, menu_var_or_value, function_obj, expression_element)
  });*/
	}

	rendered.on('click', function (e) {
		console.log("TTT2");
		rendered.remove();
		rendered.empty();
		rendered.remove();
		dom_object.empty();
		dom_object.append('<span class="menu_var_or_value_dom"> </span>');

		openInputToValue(command, ref_object, dom_object, menu_var_or_value, function_obj, expression_element);
	});

	if (command.type == Models.COMMAND_TYPES.attribution) {
		AttribuitionsManagement.renderMenuOperations(command, ref_object, dom_object, menu_var_or_value, function_obj);
	}
}

_jquery2.default.fn.textWidth = function (text, font) {

	if (!_jquery2.default.fn.textWidth.fakeEl) _jquery2.default.fn.textWidth.fakeEl = (0, _jquery2.default)('<span>').hide().appendTo(document.body);

	_jquery2.default.fn.textWidth.fakeEl.text(text || this.val() || this.text() || this.attr('placeholder')).css('font', font || this.css('font'));

	return _jquery2.default.fn.textWidth.fakeEl.width();
};

/***/ }),

/***/ "./js/visualUI/commands/whiletrue.js":
/*!*******************************************!*\
  !*** ./js/visualUI/commands/whiletrue.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

var _conditional_expression = __webpack_require__(/*! ./conditional_expression */ "./js/visualUI/commands/conditional_expression.js");

var ConditionalExpressionManagement = _interopRequireWildcard(_conditional_expression);

var _contextualized_menu = __webpack_require__(/*! ./contextualized_menu */ "./js/visualUI/commands/contextualized_menu.js");

var ContextualizedMenu = _interopRequireWildcard(_contextualized_menu);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui whiletrue created_element"> <i class="ui icon small sync"></i> <span> ' + _localizedStringsService.LocalizedStrings.getUI('text_code_while') + ' ( x < 10 ) { } </span></div>');
}

function renderCommand(command, function_obj) {
	var ret = '';
	ret += '<div class="ui whiletrue command_container"> <i class="ui icon small random command_drag"></i> <i class="ui icon times red button_remove_command"></i> <div class="ui context_menu"></div>  <span class="span_command_spec"> ' + _localizedStringsService.LocalizedStrings.getUI('text_code_while') + ' </span>';
	ret += '<span class="span_command_spec"> ( </span> <div class="conditional_expression"></div> <span class="span_command_spec"> ) </span>';
	ret += ' </span>';
	ret += '<div class="ui block_commands">';
	ret += '</div>';
	ret += '<span> </span>';
	ret += '</div>';

	var el = (0, _jquery2.default)(ret);
	el.data('command', command);

	addHandlers(command, function_obj, el);

	ContextualizedMenu.renderMenu(command, el.find('.context_menu'), function_obj, el);

	ConditionalExpressionManagement.renderExpression(command, command.expression, function_obj, el.find('.conditional_expression'));

	if (command.commands_block) {
		for (var j = 0; j < command.commands_block.length; j++) {
			CommandsManagement.renderCommand(command.commands_block[j], (0, _jquery2.default)(el.find('.block_commands')[0]), 3, function_obj);
		}
	}

	return el;
}

function addHandlers(command, function_obj, whiletrue_dom) {

	whiletrue_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, whiletrue_dom)) {
			whiletrue_dom.fadeOut();
		}
	});
}

/***/ }),

/***/ "./js/visualUI/commands/writer.js":
/*!****************************************!*\
  !*** ./js/visualUI/commands/writer.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.createFloatingCommand = createFloatingCommand;
exports.renderCommand = renderCommand;
exports.addContent = addContent;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ../types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ../ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ../../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ../globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ../variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _variable_value_menu = __webpack_require__(/*! ./variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenu = _interopRequireWildcard(_variable_value_menu);

var VariableValueMenuManagement = _interopRequireWildcard(_variable_value_menu);

var _commands = __webpack_require__(/*! ../commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

__webpack_require__(/*! ../../Sortable.js */ "./js/Sortable.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function createFloatingCommand() {
	return (0, _jquery2.default)('<div class="ui writer created_element"> <i class="ui icon small upload"></i> <span> ' + _localizedStringsService.LocalizedStrings.getUI('text_command_write') + ' var </span></div>');
}

function renderCommand(command, function_obj) {
	var ret = '';
	ret += '<div class="ui writer command_container"> <i class="ui icon small upload command_drag"></i> <i class="ui icon times red button_remove_command"></i> <span class="span_command_spec">' + _localizedStringsService.LocalizedStrings.getUI('text_command_write') + ' ( </span><div class="all_elements_write"></div> <span class="close_parentheses span_command_spec">)</span> </div>';

	var el = (0, _jquery2.default)(ret);
	el.data('command', command);

	for (var i = 0; i < command.content.length; i++) {
		var new_div_item = (0, _jquery2.default)('<div class="var_value_menu_div"></div>');
		var div_parent_with_handler = (0, _jquery2.default)('<div class="div_parent_handler"></div>');
		div_parent_with_handler.append((0, _jquery2.default)('<i class="ui icon ellipsis vertical inverted handler"></i>'));
		div_parent_with_handler.append(new_div_item);
		div_parent_with_handler.append((0, _jquery2.default)('<i class="white inverted icon times handler"></i>'));

		el.find('.all_elements_write').append(div_parent_with_handler);
		VariableValueMenu.renderMenu(command, command.content[i], new_div_item, function_obj);

		addHandlerIconAdd(el.find('.all_elements_write'), command, function_obj);

		addHandlersManager(command, function_obj, el, div_parent_with_handler, command.content[i]);
	}

	if (command.content.length == 0) {
		addHandlerIconAdd(el.find('.all_elements_write'), command, function_obj);
	}

	addHandlers(command, function_obj, el);
	return el;
}

function addHandlersManager(command, function_obj, writer_dom, item_div, content_element) {

	item_div.find('.times').on('click', function () {
		for (var i = 0; i < command.content.length; i++) {
			if (command.content[i] == content_element) {
				delete command.content[i];
				command.content.splice(i, 1);

				item_div.children().off();
				item_div.off();
				item_div.fadeOut();

				if (command.content.length > 0) {
					item_div.next('.icon_add_item_to_writer').fadeOut();
				}
				break;
			}
		}
	});
}

function addHandlers(command, function_obj, writer_dom) {

	writer_dom.find('.button_remove_command').on('click', function () {
		if (CommandsManagement.removeCommand(command, function_obj, writer_dom)) {
			writer_dom.fadeOut();
		}
	});

	Sortable.create(writer_dom.find(".all_elements_write")[0], {
		handle: '.ellipsis',
		animation: 100,
		ghostClass: 'ghost',
		group: 'writer_' + Math.floor(Math.random() * 10000000),
		draggable: '.div_parent_handler',
		onEnd: function onEnd(evt) {

			command.content.splice(evt.newIndex, 0, command.content.splice(evt.oldIndex, 1)[0]);

			writer_dom.empty();
			writer_dom.replaceWith(renderCommand(command, function_obj));
		}
	});
}

function addHandlerIconAdd(dom_object, command, function_obj) {
	var insert_after = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
	var after_which = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;

	var icon_add_item = (0, _jquery2.default)('<i class="ui icon plus square outline icon_add_item_to_writer"></i> ');
	if (!insert_after) {
		dom_object.append(icon_add_item);
	} else {
		icon_add_item.insertAfter(after_which);
	}

	icon_add_item.on('click', function (e) {
		var div_parent_with_handler = (0, _jquery2.default)('<div class="div_parent_handler" style="display:none;"></div>');
		var new_div_item = (0, _jquery2.default)('<div class="var_value_menu_div"></div>');
		div_parent_with_handler.append((0, _jquery2.default)('<i class="ui icon ellipsis vertical inverted handler"></i>'));
		div_parent_with_handler.append(new_div_item);
		div_parent_with_handler.append((0, _jquery2.default)('<i class="white inverted icon times handler"></i>'));
		div_parent_with_handler.insertAfter(icon_add_item);

		var new_related_menu = new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true);

		VariableValueMenu.renderMenu(command, new_related_menu, new_div_item, function_obj);

		addHandlerIconAdd(dom_object, command, function_obj, true, div_parent_with_handler);

		addHandlersManager(command, function_obj, dom_object, div_parent_with_handler, new_related_menu);
		var pos = 1;
		dom_object.find('.icon_add_item_to_writer').each(function () {
			if ((0, _jquery2.default)(this).get(0) === icon_add_item.get(0)) {
				command.content.splice(pos, 0, new_related_menu);
			} else {
				pos++;
			}
		});
		if (command.content.length == 1) {
			icon_add_item.remove();
		}
		div_parent_with_handler.fadeIn();
	});
}

function addContent(command, ref_object, dom_object, menu_var_or_value, function_obj, ref_object_content) {

	if (dom_object.hasClass('var_value_menu_div')) {
		var icon_add_item = (0, _jquery2.default)('<i class="ui icon plus square outline icon_add_item_to_writer"></i> ');
		icon_add_item.insertAfter(dom_object);

		icon_add_item.on('click', function (e) {
			var div_parent_with_handler = (0, _jquery2.default)('<div class="div_parent_handler"></div>');
			div_parent_with_handler.append((0, _jquery2.default)('<i class="ui icon ellipsis vertical inverted handler"></i>'));
			div_parent_with_handler.append(new_div_item);
			div_parent_with_handler.append((0, _jquery2.default)('<i class="white inverted icon times handler"></i>'));

			div_parent_with_handler.insertAfter(icon_add_item);
			var new_related_menu = new Models.VariableValueMenu(VariableValueMenuManagement.VAR_OR_VALUE_TYPES.all, null, null, null, true);

			VariableValueMenu.renderMenu(command, new_related_menu, new_div_item, function_obj);

			addHandlersManager(command, function_obj, dom_object, div_parent_with_handler, new_related_menu);

			command.content.push(new_related_menu);

			if (command.content.length == 1) {
				icon_add_item.remove();
			}
		});
	}
}

/***/ }),

/***/ "./js/visualUI/functions.js":
/*!**********************************!*\
  !*** ./js/visualUI/functions.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.renderFunction = renderFunction;
exports.initVisualUI = initVisualUI;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ./types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ./ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ./../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _globals = __webpack_require__(/*! ./globals */ "./js/visualUI/globals.js");

var GlobalsManagement = _interopRequireWildcard(_globals);

var _variables = __webpack_require__(/*! ./variables */ "./js/visualUI/variables.js");

var VariablesManagement = _interopRequireWildcard(_variables);

var _commands = __webpack_require__(/*! ./commands */ "./js/visualUI/commands.js");

var CommandsManagement = _interopRequireWildcard(_commands);

var _code_generator = __webpack_require__(/*! ./code_generator */ "./js/visualUI/code_generator.js");

var CodeManagement = _interopRequireWildcard(_code_generator);

var _variable_value_menu = __webpack_require__(/*! ./commands/variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenu = _interopRequireWildcard(_variable_value_menu);

var _domConsole = __webpack_require__(/*! ./../io/domConsole */ "./js/io/domConsole.js");

var _ivprogParser = __webpack_require__(/*! ./../ast/ivprogParser */ "./js/ast/ivprogParser.js");

var _ivprogProcessor = __webpack_require__(/*! ./../processor/ivprogProcessor */ "./js/processor/ivprogProcessor.js");

var _melankeWatchjs = __webpack_require__(/*! melanke-watchjs */ "./node_modules/melanke-watchjs/src/watch.js");

var _melankeWatchjs2 = _interopRequireDefault(_melankeWatchjs);

var _semanticAnalyser = __webpack_require__(/*! ../processor/semantic/semanticAnalyser */ "./js/processor/semantic/semanticAnalyser.js");

var _ivprogAssessment = __webpack_require__(/*! ../assessment/ivprogAssessment */ "./js/assessment/ivprogAssessment.js");

var _algorithm = __webpack_require__(/*! ./algorithm */ "./js/visualUI/algorithm.js");

var AlgorithmManagement = _interopRequireWildcard(_algorithm);

var _utils = __webpack_require__(/*! ./utils */ "./js/visualUI/utils.js");

var Utils = _interopRequireWildcard(_utils);

__webpack_require__(/*! ../Sortable.js */ "./js/Sortable.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var counter_new_functions = 0;
var counter_new_parameters = 0;

var studentTemp = null;
var domConsole = null;
window.studentGrade = null;
window.LocalizedStrings = _localizedStringsService.LocalizedStrings;
var program = new Models.Program();

window.system_functions = [];
// Adding math functions:
window.system_functions.push(new Models.SystemFunction('$sin', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
window.system_functions.push(new Models.SystemFunction('$cos', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
window.system_functions.push(new Models.SystemFunction('$tan', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
window.system_functions.push(new Models.SystemFunction('$sqrt', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
window.system_functions.push(new Models.SystemFunction('$pow', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
window.system_functions.push(new Models.SystemFunction('$log', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
window.system_functions.push(new Models.SystemFunction('$abs', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
window.system_functions.push(new Models.SystemFunction('$negate', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
window.system_functions.push(new Models.SystemFunction('$invert', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
window.system_functions.push(new Models.SystemFunction('$max', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
window.system_functions.push(new Models.SystemFunction('$min', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
// Adding text functions:
window.system_functions.push(new Models.SystemFunction('$substring', _types.Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
window.system_functions.push(new Models.SystemFunction('$length', _types.Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
window.system_functions.push(new Models.SystemFunction('$uppercase', _types.Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
window.system_functions.push(new Models.SystemFunction('$lowercase', _types.Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
window.system_functions.push(new Models.SystemFunction('$charAt', _types.Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
// Adding arrangement functions:
window.system_functions.push(new Models.SystemFunction('$numElements', _types.Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true, 1)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
window.system_functions.push(new Models.SystemFunction('$matrixLines', _types.Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true, 2)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
window.system_functions.push(new Models.SystemFunction('$matrixColumns', _types.Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true, 2)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
// Adding conversion functions:
window.system_functions.push(new Models.SystemFunction('$isReal', _types.Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
window.system_functions.push(new Models.SystemFunction('$isInt', _types.Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
window.system_functions.push(new Models.SystemFunction('$isBool', _types.Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
window.system_functions.push(new Models.SystemFunction('$castReal', _types.Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
window.system_functions.push(new Models.SystemFunction('$castInt', _types.Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
window.system_functions.push(new Models.SystemFunction('$castBool', _types.Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
window.system_functions.push(new Models.SystemFunction('$castString', _types.Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)], null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));

console.log('       ___           ___                    ________          \n      /   /         /   /                  /   ____/  \n     /   /         /   /                  /   /        \n    /   /         /   /  ______    ___   /   /__         \n   /   /         /   /  /      \\  /  /  /   ___/      \n  /   /______   /   /  /   /\\   \\/  /  /   /      \n /          /  /   /  /   /  \\     /  /   /____     \n/__________/  /___/  /___/    \\___/  /________/       \n\n Laboratório de Informática na Educação\n http://line.ime.usp.br');

var mainFunction = new Models.Function(_localizedStringsService.LocalizedStrings.getUI("start"), _types.Types.VOID, 0, [], true, false);
mainFunction.function_comment = new Models.Comment(_localizedStringsService.LocalizedStrings.getUI('text_comment_main'));
program.addFunction(mainFunction);

window.program_obj = program;

window.generator = CodeManagement.generate;
window.runCodeAssessment = runCodeAssessment;
window.renderAlgorithm = AlgorithmManagement.renderAlgorithm;
window.insertContext = false;
window.watchW = _melankeWatchjs2.default;

_melankeWatchjs2.default.watch(window.program_obj.globals, function () {
  if (window.insertContext) {
    setTimeout(function () {
      AlgorithmManagement.renderAlgorithm();
    }, 300);
    window.insertContext = false;
  } else {
    AlgorithmManagement.renderAlgorithm();
  }
}, 1);

_melankeWatchjs2.default.watch(window.program_obj.functions, function () {
  if (window.insertContext) {
    setTimeout(function () {
      AlgorithmManagement.renderAlgorithm();
    }, 300);
    window.insertContext = false;
  } else {
    AlgorithmManagement.renderAlgorithm();
  }
}, 0);

function addFunctionHandler() {

  var new_function = new Models.Function(_localizedStringsService.LocalizedStrings.getUI("new_function") + "_" + counter_new_functions, _types.Types.VOID, 0, [], false, false, [], new Models.Comment(_localizedStringsService.LocalizedStrings.getUI('text_comment_start')));
  program.addFunction(new_function);

  counter_new_functions++;

  window.insertContext = true;

  var newe = renderFunction(new_function);

  newe.css('display', 'none');
  newe.fadeIn();
}

function addParameter(function_obj, function_container) {
  var is_from_click = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

  if (function_obj.parameters_list == null) {
    function_obj.parameters_list = [];
  }
  var new_parameter = new Models.Variable(_types.Types.INTEGER, _localizedStringsService.LocalizedStrings.getUI("new_parameter") + "_" + counter_new_parameters);
  function_obj.parameters_list.push(new_parameter);
  counter_new_parameters++;

  var newe = renderParameter(function_obj, new_parameter, function_container);

  if (is_from_click) {
    newe.css('display', 'none');
    newe.fadeIn();
  }
}

function updateReturnType(function_obj, new_type) {
  var new_dimensions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;

  function_obj.return_type = new_type;
  function_obj.return_dimensions = new_dimensions;
}

function removeFunction(function_obj) {
  var index = program.functions.indexOf(function_obj);
  if (index > -1) {
    program.functions.splice(index, 1);
  }
}

function minimizeFunction(function_obj) {
  function_obj.is_hidden = !function_obj.is_hidden;
}

function addHandlers(function_obj, function_container) {

  function_container.find('.ui.dropdown.function_return').dropdown({
    onChange: function onChange(value, text, $selectedItem) {
      if ($selectedItem.data('dimensions')) {
        updateReturnType(function_obj, _types.Types[$selectedItem.data('type')], $selectedItem.data('dimensions'));
      } else {
        updateReturnType(function_obj, _types.Types[$selectedItem.data('type')]);
      }
    },
    selectOnKeydown: false
  });

  function_container.find(".name_function_updated").on('click', function (e) {
    enableNameFunctionUpdate(function_obj, function_container);
  });

  function_container.find(".add_parameter_button").on('click', function (e) {
    window.insertContext = true;
    addParameter(function_obj, function_container, true);
  });

  function_container.find('.menu_commands').dropdown({
    on: 'hover'
  });

  function_container.find('.menu_commands a').on('click', function (evt) {
    if (function_obj.commands == null || function_obj.commands.length == 0) {
      function_obj.commands = [];
      var new_cmd = CommandsManagement.genericCreateCommand((0, _jquery2.default)(this).data('command'));
      function_obj.commands.push(new_cmd);

      CommandsManagement.renderCommand(new_cmd, function_container.find('.commands_list_div'), 3, function_obj);
    } else {
      CommandsManagement.createFloatingCommand(function_obj, function_container, (0, _jquery2.default)(this).data('command'), evt);
    }
  });

  function_container.find('.add_var_button_function').on('click', function (e) {
    window.insertContext = true;
    VariablesManagement.addVariable(function_obj, function_container, true);
  });

  function_container.find('.remove_function_button').on('click', function (e) {
    removeFunction(function_obj);
    function_container.fadeOut();
  });

  function_container.find('.minimize_function_button').on('click', function (e) {
    minimizeFunction(function_obj);
    if (function_obj.is_hidden) {
      function_container.find(".add_var_button_function").toggle();
      function_container.find(".inline_add_command").toggle();
      function_container.find(".function_area").slideToggle();
    } else {
      function_container.find(".function_area").slideToggle(function () {
        function_container.find(".add_var_button_function").toggle();
        function_container.find(".inline_add_command").toggle();
      });
    }
  });
}

// Essa função imprime o tipo de retorno da função e cria o menu do tipo 'select' para alteração
function renderFunctionReturn(function_obj, function_element) {

  var ret = '<div class="ui dropdown function_return">';

  if (function_obj.return_dimensions > 0) {
    ret += '<div class="text">' + _localizedStringsService.LocalizedStrings.getUI("vector") + ':' + _localizedStringsService.LocalizedStrings.getUI(function_obj.return_type);
    if (function_obj.return_dimensions == 1) {
      ret += ' [ ] ';
    } else {
      ret += ' [ ] [ ] ';
    }
    ret += '</div>';
  } else {
    ret += '<div class="text">' + _localizedStringsService.LocalizedStrings.getUI(function_obj.return_type) + '</div>';
  }

  ret += '<div class="menu">';

  for (var tm in _types.Types) {
    ret += '<div class="item ' + (function_obj.return_type == tm.toLowerCase() && function_obj.return_dimensions < 1 ? ' selected ' : '') + '" data-type="' + tm + '" >' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + '</div>';
  }

  for (var tm in _types.Types) {
    if (tm == _types.Types.VOID.toUpperCase()) {
      continue;
    }
    ret += '<div class="item">' + '<i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + '<div class="menu">' + '<div class="item ' + (function_obj.return_type == tm.toLowerCase() && function_obj.return_dimensions > 0 ? ' selected ' : '') + '" data-text="' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + ' [ ] " data-type="' + tm + '" data-dimensions="1">[ ]</div>' + '<div class="item ' + (function_obj.return_type == tm.toLowerCase() && function_obj.return_dimensions > 0 ? ' selected ' : '') + '" data-text="' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + ' [ ] [ ] " data-type="' + tm + '" data-dimensions="2">[ ] [ ] </div>' + '</div>' + '</div>';
  }

  ret += '</div></div>';

  ret = (0, _jquery2.default)(ret);

  function_element.find('.function_return').append(ret);
}

function renderFunction(function_obj) {

  var appender = '<div class="ui secondary segment function_div list-group-item">';

  if (function_obj.function_comment) {
    //appender += renderComment(function_obj.function_comment, sequence, true, -1);
  }

  appender += '<span class="glyphicon glyphicon-move move_function" aria-hidden="true"><i class="icon sort alternate vertical"></i></span>';

  appender += (function_obj.is_main ? '<div class="div_start_minimize_v"> </div>' : '<button class="ui icon button large remove_function_button"><i class="red icon times"></i></button>') + '<button class="ui icon button tiny minimize_function_button"><i class="icon window minimize"></i></button>';

  appender += '<div class="function_signature_div">' + _localizedStringsService.LocalizedStrings.getUI("function") + ' ';

  if (function_obj.is_main) {
    appender += '<div class="function_name_div">  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ' + _localizedStringsService.LocalizedStrings.getUI('void') + ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="span_name_function" >' + function_obj.name + '</span> </div> ' + ' <span class="parethesis_function">( </span> <div class="ui large labels parameters_list">';
  } else {
    appender += '<div class="ui function_return"></div>';

    appender += '<div class="function_name_div function_name_div_updated"><span class="span_name_function name_function_updated">' + function_obj.name + '</span> </div> ' + ' <span class="parethesis_function"> ( </span> <i class="ui icon plus square outline add_parameter_button"></i> <div class="ui large labels parameters_list container_parameters_list">';
  }

  appender += '</div> <span class="parethesis_function"> ) </span> </div>' + (function_obj.is_hidden ? ' <div class="function_area" style="display: none;"> ' : ' <div class="function_area"> ');

  appender += '<div class="ui add_var_context add_var_button_function" style="float: left;"><i class="icon plus circle purple"></i><i class="icon circle white back"></i><div class="ui icon button purple"><i class="icon superscript"></i></div></div>';

  appender += '<div class="ui top attached segment variables_list_div"></div>';

  appender += '<div class="ui inline_add_command"><i class="icon plus circle purple"></i><i class="icon circle white back"></i><div class="ui icon button dropdown menu_commands orange" style="float: left;" ><i class="icon code"></i> <div class="menu"> ';
  appender += '<a class="item" data-command="' + Models.COMMAND_TYPES.reader + '"><i class="download icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_read_var') + '</a>' + '<a class="item" data-command="' + Models.COMMAND_TYPES.writer + '"><i class="upload icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_write_var') + '</a>' + '<a class="item" data-command="' + Models.COMMAND_TYPES.comment + '"><i class="quote left icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_comment') + '</a>' + '<a class="item" data-command="' + Models.COMMAND_TYPES.attribution + '"><i class="arrow left icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_attribution') + '</a>' + '<a class="item" data-command="' + Models.COMMAND_TYPES.functioncall + '"><i class="hand point right icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_functioncall') + '</a>' + '<a class="item" data-command="' + Models.COMMAND_TYPES.iftrue + '" ><i class="random icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_iftrue') + '</a>' + '<a class="item" data-command="' + Models.COMMAND_TYPES.repeatNtimes + '"><i class="sync icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_repeatNtimes') + '</a>' + '<a class="item" data-command="' + Models.COMMAND_TYPES.whiletrue + '"><i class="sync icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_whiletrue') + '</a>' + '<a class="item" data-command="' + Models.COMMAND_TYPES.dowhiletrue + '"><i class="sync icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_dowhiletrue') + '</a>' + '<a class="item" data-command="' + Models.COMMAND_TYPES.switch + '"><i class="list icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_switch') + '</a>' + '<a class="item" data-command="' + Models.COMMAND_TYPES.return + '"><i class="reply icon"></i> ' + _localizedStringsService.LocalizedStrings.getUI('text_btn_return') + '</a>' + '</div></div></div>';

  appender += '<div class="ui bottom attached segment commands_list_div"></div>';

  appender += '</div></div>';

  appender = (0, _jquery2.default)(appender);

  (0, _jquery2.default)('.all_functions').append(appender);

  appender.data('fun', function_obj);
  appender.find('.commands_list_div').data('fun', function_obj);

  renderFunctionReturn(function_obj, appender);

  addHandlers(function_obj, appender);

  // Rendering parameters: 
  for (var j = 0; j < function_obj.parameters_list.length; j++) {
    renderParameter(function_obj, function_obj.parameters_list[j], appender);
  }

  // Rendering variables:
  for (var j = 0; j < function_obj.variables_list.length; j++) {
    VariablesManagement.renderVariable(appender, function_obj.variables_list[j], function_obj);
  }
  // Rendering commands:
  for (var j = 0; j < function_obj.commands.length; j++) {
    CommandsManagement.renderCommand(function_obj.commands[j], (0, _jquery2.default)(appender.find('.commands_list_div')[0]), 3, function_obj);
  }
  (0, _jquery2.default)('.minimize_function_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_minimize"),
    delay: {
      show: 750,
      hide: 0
    }
  });

  Sortable.create(appender.find(".variables_list_div")[0], {
    handle: '.ellipsis',
    animation: 100,
    ghostClass: 'ghost',
    group: 'local_vars_drag_' + program.functions.indexOf(function_obj),
    onEnd: function onEnd(evt) {
      updateSequenceLocals(evt.oldIndex, evt.newIndex, function_obj);
    }
  });

  Sortable.create(appender.find(".commands_list_div")[0], {
    handle: '.command_drag',
    animation: 100,
    ghostClass: 'ghost',
    group: 'commands_drag_' + program.functions.indexOf(function_obj),
    onEnd: function onEnd(evt) {
      //updateSequenceLocals(evt.oldIndex, evt.newIndex, function_obj);
    }
  });

  if (!function_obj.is_main) {
    Sortable.create(appender.find(".container_parameters_list")[0], {
      handle: '.ellipsis',
      animation: 100,
      ghostClass: 'ghost',
      group: 'parameters_drag_' + program.functions.indexOf(function_obj),
      onEnd: function onEnd(evt) {
        updateSequenceParameters(evt.oldIndex, evt.newIndex, function_obj);
      }
    });
  }
  return appender;
}

function initVisualUI() {
  // MUST USE CONST, LET, OR VAR !!!!!!
  var mainDiv = (0, _jquery2.default)('#visual-main-div');
  // fill mainDiv with functions and globals...
  // renderAlgorithm()...
  (0, _jquery2.default)('.add_function_button').on('click', function () {
    addFunctionHandler();
  });
  (0, _jquery2.default)('.add_global_button').on('click', function () {
    window.insertContext = true;
    GlobalsManagement.addGlobal(program, true);
  });

  (0, _jquery2.default)('.run_button').on('click', function () {
    runCode();
  });

  (0, _jquery2.default)('.visual_coding_button').on('click', function () {
    toggleVisualCoding();
  });

  (0, _jquery2.default)('.textual_coding_button').on('click', function () {
    toggleTextualCoding();
  });

  (0, _jquery2.default)('.assessment').on('click', function () {
    runCodeAssessment();
    is_iassign = true;
  });

  (0, _jquery2.default)('.div_toggle_console').on('click', function () {
    toggleConsole();
  });
  (0, _jquery2.default)('.expand_button').on('click', function () {
    full_screen();
  });
  (0, _jquery2.default)('.main_title h2').prop('title', _localizedStringsService.LocalizedStrings.getUI('text_ivprog_description'));
}

var is_iassign = false;

(0, _jquery2.default)(document).ready(function () {

  var time_show = 750;
  (0, _jquery2.default)('.visual_coding_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_visual"),
    delay: {
      show: time_show,
      hide: 0
    }
  });
  (0, _jquery2.default)('.textual_coding_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_textual"),
    delay: {
      show: time_show,
      hide: 0
    }
  });
  (0, _jquery2.default)('.upload_file_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_upload"),
    delay: {
      show: time_show,
      hide: 0
    }
  });
  (0, _jquery2.default)('.download_file_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_download"),
    delay: {
      show: time_show,
      hide: 0
    }
  });
  (0, _jquery2.default)('.undo_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_undo"),
    delay: {
      show: time_show,
      hide: 0
    }
  });
  (0, _jquery2.default)('.redo_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_redo"),
    delay: {
      show: time_show,
      hide: 0
    }
  });
  (0, _jquery2.default)('.run_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_run"),
    delay: {
      show: time_show,
      hide: 0
    }
  });
  (0, _jquery2.default)('.assessment_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_evaluate"),
    delay: {
      show: time_show,
      hide: 0
    }
  });
  (0, _jquery2.default)('.help_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_help") + ' - ' + _localizedStringsService.LocalizedStrings.getUI("text_ivprog_version"),
    delay: {
      show: time_show,
      hide: 0
    }
  });
  (0, _jquery2.default)('.add_global_button').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_add_global"),
    delay: {
      show: time_show,
      hide: 0
    }
  });
  (0, _jquery2.default)('.div_toggle_console').popup({
    content: _localizedStringsService.LocalizedStrings.getUI("tooltip_console"),
    delay: {
      show: time_show,
      hide: 0
    }
  });

  Sortable.create(listWithHandle, {
    handle: '.glyphicon-move',
    animation: 100,
    ghostClass: 'ghost',
    group: 'functions_divs_drag',
    onEnd: function onEnd(evt) {
      updateSequenceFunction(evt.oldIndex, evt.newIndex);
    }
  });

  var listGlobalsHandle = document.getElementById("listGlobalsHandle");
  Sortable.create(listGlobalsHandle, {
    handle: '.ellipsis',
    animation: 100,
    ghostClass: 'ghost',
    group: 'globals_divs_drag',
    onEnd: function onEnd(evt) {
      updateSequenceGlobals(evt.oldIndex, evt.newIndex);
    }
  });
});

function updateSequenceParameters(oldIndex, newIndex, function_obj) {
  function_obj.parameters_list.splice(newIndex, 0, function_obj.parameters_list.splice(oldIndex, 1)[0]);
}

function updateSequenceLocals(oldIndex, newIndex, function_obj) {
  function_obj.variables_list.splice(newIndex, 0, function_obj.variables_list.splice(oldIndex, 1)[0]);
}

function updateSequenceGlobals(oldIndex, newIndex) {
  program_obj.globals.splice(newIndex, 0, program_obj.globals.splice(oldIndex, 1)[0]);
}

function updateSequenceFunction(oldIndex, newIndex) {
  program_obj.functions.splice(newIndex, 0, program_obj.functions.splice(oldIndex, 1)[0]);
}

function runCodeAssessment() {

  window.studentGrade = null;
  studentTemp = null;
  var strCode = CodeManagement.generate();
  if (strCode == null) {
    return;
  }

  toggleConsole(true);

  if (domConsole == null) domConsole = new _domConsole.DOMConsole("#ivprog-term");
  (0, _jquery2.default)("#ivprog-term").slideDown(500);
  var runner = new _ivprogAssessment.IVProgAssessment(strCode, testCases, domConsole);

  runner.runTest().then(function (grade) {
    if (!is_iassign) {
      parent.getEvaluationCallback(grade);
    } else {
      is_iassign = false;
    }
  }).catch(function (err) {
    return console.log(err);
  });
}

function runCode() {

  var strCode = CodeManagement.generate();
  if (strCode == null) {
    return;
  }

  toggleConsole(true);

  if (domConsole == null) domConsole = new _domConsole.DOMConsole("#ivprog-term");
  (0, _jquery2.default)("#ivprog-term").slideDown(500);
  try {
    var parser = _ivprogParser.IVProgParser.createParser(strCode);
    var analyser = new _semanticAnalyser.SemanticAnalyser(parser.parseTree());
    var data = analyser.analyseTree();
    var proc = new _ivprogProcessor.IVProgProcessor(data);
    proc.registerInput(domConsole);
    proc.registerOutput(domConsole);
    (0, _jquery2.default)("#ivprog-term").addClass('ivprog-term-active');

    proc.interpretAST().then(function (_) {
      domConsole.info("Programa executado com sucesso!");
      (0, _jquery2.default)("#ivprog-term").removeClass('ivprog-term-active');
    }).catch(function (err) {
      domConsole.err(err.message);
      (0, _jquery2.default)("#ivprog-term").removeClass('ivprog-term-active');
    });
  } catch (error) {
    domConsole.err(error.message);
    console.log(error);
  }
}

function toggleConsole(is_running) {

  if (is_running) {
    (0, _jquery2.default)('.ivprog-term-div').css('display', 'block');
    (0, _jquery2.default)('#ivprog-term').css('min-height', '160px');
    (0, _jquery2.default)('#ivprog-term').css('margin-top', '-170px');
    return;
  }

  if ((0, _jquery2.default)('#ivprog-term').css('min-height') == '160px') {
    // esconder
    (0, _jquery2.default)('.ivprog-term-div').css('display', 'none');
    (0, _jquery2.default)('#ivprog-term').css('min-height', '0');
    (0, _jquery2.default)('#ivprog-term').css('margin-top', '-30px');
    (0, _jquery2.default)('#ivprog-term').css('padding', '5px');
  } else {
    // mostrar
    (0, _jquery2.default)('.ivprog-term-div').css('display', 'block');
    (0, _jquery2.default)('#ivprog-term').css('min-height', '160px');
    (0, _jquery2.default)('#ivprog-term').css('margin-top', '-170px');
  }
}

function waitToCloseConsole() {
  domConsole.info("Aperte qualquer tecla para fechar...");
  var p = new Promise(function (resolve, _) {
    domConsole.requestInput(resolve, true);
  });
  p.then(function (_) {
    domConsole.dispose();
    domConsole = null;
    (0, _jquery2.default)("#ivprog-term").hide();
  });
}

function toggleTextualCoding() {
  var code = CodeManagement.generate();

  if (code == null) {
    return;
  }

  (0, _jquery2.default)('.ivprog_visual_panel').css('display', 'none');
  (0, _jquery2.default)('.ivprog_textual_panel').css('display', 'block');
  (0, _jquery2.default)('.ivprog_textual_panel').removeClass('loading');
  (0, _jquery2.default)('.ivprog_textual_code').text(code);

  (0, _jquery2.default)('.visual_coding_button').removeClass('active');
  (0, _jquery2.default)('.textual_coding_button').addClass('active');
}

function toggleVisualCoding() {
  (0, _jquery2.default)('.ivprog_textual_panel').addClass('loading');
  (0, _jquery2.default)('.ivprog_textual_panel').css('display', 'none');
  (0, _jquery2.default)('.ivprog_visual_panel').css('display', 'block');

  (0, _jquery2.default)('.textual_coding_button').removeClass('active');
  (0, _jquery2.default)('.visual_coding_button').addClass('active');
}

function removeParameter(function_obj, parameter_obj, parameter_container) {
  var index = function_obj.parameters_list.indexOf(parameter_obj);
  if (index > -1) {
    window.insertContext = true;
    function_obj.parameters_list.splice(index, 1);
  }
  (0, _jquery2.default)(parameter_container).fadeOut();
}

function updateParameterType(parameter_obj, new_type) {
  var new_dimensions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;

  parameter_obj.type = new_type;
  parameter_obj.dimensions = new_dimensions;

  if (new_dimensions > 0) {
    parameter_obj.rows = new_dimensions;
    parameter_obj.columns = 2;
  }
}

function renderParameter(function_obj, parameter_obj, function_container) {
  var ret = "";

  ret += '<div class="ui label function_name_parameter pink"><i class="ui icon ellipsis vertical inverted"></i>';

  ret += '<div class="ui dropdown parameter_type">';

  if (parameter_obj.dimensions > 0) {
    ret += '<div class="text">' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(parameter_obj.type);
    if (parameter_obj.dimensions == 1) {
      ret += ' [ ] ';
    } else {
      ret += ' [ ] [ ] ';
    }
    ret += '</div>';
  } else {
    ret += '<div class="text">' + _localizedStringsService.LocalizedStrings.getUI(parameter_obj.type) + '</div>';
  }

  ret += '<div class="menu">';

  for (var tm in _types.Types) {
    if (tm == _types.Types.VOID.toUpperCase()) {
      continue;
    }
    ret += '<div class="item ' + (parameter_obj.type == tm.toLowerCase() ? ' selected ' : '') + '" data-type="' + tm + '" >' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + '</div>';
  }

  for (var tm in _types.Types) {
    if (tm == _types.Types.VOID.toUpperCase()) {
      continue;
    }
    ret += '<div class="item">' + '<i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + '<div class="menu">' + '<div class="item" data-text="' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + ' [ ] " data-type="' + tm + '" data-dimensions="1">[ ]</div>' + '<div class="item" data-text="' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + ' [ ] [ ] " data-type="' + tm + '" data-dimensions="2">[ ] [ ] </div>' + '</div>' + '</div>';
  }

  ret += '</div></div>';

  ret += '<div class="parameter_div_edit"><span class="span_name_parameter label_enable_name_parameter">' + parameter_obj.name + '</span></div> ';

  ret += ' <i class="yellow inverted icon times remove_parameter"></i></div>';

  ret = (0, _jquery2.default)(ret);

  function_container.find('.container_parameters_list').append(ret);

  ret.find('.remove_parameter').on('click', function (e) {
    removeParameter(function_obj, parameter_obj, ret);
  });

  ret.find('.ui.dropdown.parameter_type').dropdown({
    onChange: function onChange(value, text, $selectedItem) {
      if ($selectedItem.data('dimensions')) {
        updateParameterType(parameter_obj, _types.Types[$selectedItem.data('type')], $selectedItem.data('dimensions'));
      } else {
        updateParameterType(parameter_obj, _types.Types[$selectedItem.data('type')]);
      }
    },
    selectOnKeydown: false
  });

  ret.find('.label_enable_name_parameter').on('click', function (e) {
    enableNameParameterUpdate(parameter_obj, ret, function_obj);
  });

  return ret;
}

function updateParameterName(parameter_var, new_name, parameter_obj_dom, function_obj) {
  if (isValidIdentifier(new_name)) {
    if (variableNameAlreadyExists(new_name, function_obj)) {
      Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), _localizedStringsService.LocalizedStrings.getUI('inform_valid_variable_duplicated'));
    } else {
      parameter_var.name = new_name;
    }
  } else {
    Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), _localizedStringsService.LocalizedStrings.getUI('inform_valid_name'));
  }
}

function variableNameAlreadyExists(name_var, function_obj) {

  if (function_obj.parameters_list) {
    for (var i = 0; i < function_obj.parameters_list.length; i++) {
      if (function_obj.parameters_list[i].name == name_var) {
        return true;
      }
    }
  }

  if (function_obj.variables_list) {
    for (var i = 0; i < function_obj.variables_list.length; i++) {
      if (function_obj.variables_list[i].name == name_var) {
        return true;
      }
    }
  }

  return false;
}

function updateFunctionName(function_var, new_name, function_obj_dom) {
  if (isValidIdentifier(new_name)) {
    if (functionNameAlreadyExists(new_name)) {
      Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), _localizedStringsService.LocalizedStrings.getUI('inform_valid_name_duplicated'));
    } else {
      function_var.name = new_name;
    }
  } else {
    Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), _localizedStringsService.LocalizedStrings.getUI('inform_valid_name'));
  }
}

function functionNameAlreadyExists(function_name) {
  for (var i = 0; i < window.program_obj.functions.length; i++) {
    if (window.program_obj.functions[i].name == function_name) {
      return true;
    }
  }
  return false;
}

function isValidIdentifier(identifier_str) {
  return (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(identifier_str)
  );
}

var opened_name_parameter = false;
var opened_input_parameter = null;
function enableNameParameterUpdate(parameter_obj, parent_node, function_obj) {
  if (opened_name_parameter) {
    opened_input_parameter.focus();
    return;
  }
  opened_name_parameter = true;
  parent_node = (0, _jquery2.default)(parent_node);

  var input_field;

  parent_node.find('.span_name_parameter').text('');
  input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + parameter_obj.name + "' />");
  input_field.insertBefore(parent_node.find('.span_name_parameter'));

  input_field.on('input', function () {
    var inputWidth = input_field.textWidth() + 10;
    opened_input_parameter = input_field;
    input_field.focus();

    var tmpStr = input_field.val();
    input_field.val('');
    input_field.val(tmpStr);

    input_field.css({
      width: inputWidth
    });
  }).trigger('input');

  input_field.focusout(function () {
    /// update array:
    if (input_field.val().trim()) {
      updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
      parent_node.find('.span_name_parameter').text(parameter_obj.name);
    }
    input_field.off();
    input_field.remove();

    /// update elements:
    opened_name_parameter = false;
    opened_input_parameter = false;
  });

  input_field.on('keydown', function (e) {
    var code = e.keyCode || e.which;
    if (code == 13) {
      if (input_field.val().trim()) {
        updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
        parent_node.find('.span_name_parameter').text(parameter_obj.name);
      }
      input_field.off();
      input_field.remove();

      /// update elements:
      opened_name_parameter = false;
      opened_input_parameter = false;
    }
    if (code == 27) {
      parent_node.find('.span_name_parameter').text(parameter_obj.name);
      input_field.off();
      input_field.remove();

      /// update elements:
      opened_name_parameter = false;
      opened_input_parameter = false;
    }
  });
  input_field.select();
}

var opened_name_function = false;
var opened_input = null;
var previousPadding = null;
function enableNameFunctionUpdate(function_obj, parent_node) {
  if (opened_name_function) {
    opened_input.focus();
    return;
  }
  parent_node = (0, _jquery2.default)(parent_node);
  parent_node.find('.span_name_function').text('');
  var input_field;
  if (!previousPadding) {
    previousPadding = parent_node.find('.span_name_function').css('padding-left');
  }
  parent_node.find('.span_name_function').css('padding-left', '0');
  parent_node.find('.span_name_function').css('padding-right', '0');

  input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + function_obj.name + "' />");
  input_field.insertBefore(parent_node.find('.span_name_function'));

  input_field.on('input', function () {
    var inputWidth = input_field.textWidth() + 10;
    opened_input = input_field;
    input_field.focus();

    var tmpStr = input_field.val();
    input_field.val('');
    input_field.val(tmpStr);

    input_field.css({
      width: inputWidth
    });
  }).trigger('input');

  input_field.focusout(function () {
    /// update array:
    if (input_field.val().trim()) {
      updateFunctionName(function_obj, input_field.val().trim(), parent_node);
    }
    input_field.off();
    input_field.remove();
    parent_node.find('.span_name_function').css('padding-left', previousPadding);
    parent_node.find('.span_name_function').css('padding-right', previousPadding);
    parent_node.find('.span_name_function').text(function_obj.name);

    /// update elements:
    opened_name_function = false;
    opened_input = false;
  });

  input_field.on('keydown', function (e) {
    var code = e.keyCode || e.which;
    if (code == 13) {
      if (input_field.val().trim()) {
        updateFunctionName(function_obj, input_field.val().trim(), parent_node);
      }
      input_field.off();
      input_field.remove();
      parent_node.find('.span_name_function').css('padding-left', previousPadding);
      parent_node.find('.span_name_function').css('padding-right', previousPadding);
      parent_node.find('.span_name_function').text(function_obj.name);

      /// update elements:
      opened_name_function = false;
      opened_input = false;
    }
    if (code == 27) {

      input_field.off();
      input_field.remove();
      parent_node.find('.span_name_function').css('padding-left', previousPadding);
      parent_node.find('.span_name_function').css('padding-right', previousPadding);
      parent_node.find('.span_name_function').text(function_obj.name);

      /// update elements:
      opened_name_function = false;
      opened_input = false;
    }
  });
  input_field.select();
}

/***/ }),

/***/ "./js/visualUI/globals.js":
/*!********************************!*\
  !*** ./js/visualUI/globals.js ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.addGlobal = addGlobal;
exports.renderGlobal = renderGlobal;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ./types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ./ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ./../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _utils = __webpack_require__(/*! ./utils */ "./js/visualUI/utils.js");

var Utils = _interopRequireWildcard(_utils);

__webpack_require__(/*! ../semantic/semantic.min.js */ "./js/semantic/semantic.min.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

window.jQuery = _jquery2.default;

var counter_new_globals = 0;

function addGlobal(program) {
	var is_from_click = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;


	var new_global = new Models.Variable(_types.Types.INTEGER, _localizedStringsService.LocalizedStrings.getUI('new_global') + '_' + counter_new_globals, 1);
	counter_new_globals++;

	program.addGlobal(new_global);

	var newe = renderGlobal(new_global);

	if (is_from_click) {
		newe.css('display', 'none');
		newe.fadeIn();
	}
}

function toggleConstant(global_var) {
	global_var.is_constant = !global_var.is_constant;
}

function updateName(global_var, new_name, global_obj_dom) {
	if (isValidIdentifier(new_name)) {
		if (globalNameAlreadyExists(new_name)) {
			Utils.renderErrorMessage(global_obj_dom.find('.editing_name_var'), _localizedStringsService.LocalizedStrings.getUI('inform_valid_global_duplicated'));
		} else {
			global_var.name = new_name;
		}
	} else {
		Utils.renderErrorMessage(global_obj_dom.find('.editing_name_var'), _localizedStringsService.LocalizedStrings.getUI('inform_valid_name'));
	}
}

function globalNameAlreadyExists(global_name) {
	for (var i = 0; i < window.program_obj.globals.length; i++) {
		if (window.program_obj.globals[i].name == global_name) {
			return true;
		}
	}
	return false;
}

function isValidIdentifier(identifier_str) {
	return (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(identifier_str)
	);
}

function updateType(global_var, new_type) {
	var new_dimensions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;

	global_var.type = new_type;
	global_var.dimensions = new_dimensions;

	if (new_dimensions > 0) {
		global_var.rows = new_dimensions;
		global_var.columns = 2;
	}

	updateInitialValues(global_var);
}

function removeGlobal(global_var, global_container) {
	var index = window.program_obj.globals.indexOf(global_var);
	if (index > -1) {
		window.insertContext = true;
		window.program_obj.globals.splice(index, 1);
	}
	global_container.children().off();
	global_container.off();
	global_container.fadeOut();
}

function updateInitialValues(global_var) {
	if (global_var.type == _types.Types.INTEGER) {
		if (global_var.dimensions == 0) {
			global_var.value = 1;
		}
		if (global_var.dimensions == 1) {
			global_var.value = [1, 1];
		}
		if (global_var.dimensions == 2) {
			global_var.value = [[1, 1], [1, 1]];
		}
	}

	if (global_var.type == _types.Types.REAL) {
		if (global_var.dimensions == 0) {
			global_var.value = 1.0;
		}
		if (global_var.dimensions == 1) {
			global_var.value = [1.0, 1.0];
		}
		if (global_var.dimensions == 2) {
			global_var.value = [[1.0, 1.0], [1.0, 1.0]];
		}
	}

	if (global_var.type == _types.Types.TEXT) {
		if (global_var.dimensions == 0) {
			global_var.value = _localizedStringsService.LocalizedStrings.getUI('text_start');
		}
		if (global_var.dimensions == 1) {
			global_var.value = [_localizedStringsService.LocalizedStrings.getUI('text_start'), _localizedStringsService.LocalizedStrings.getUI('text_start')];
		}
		if (global_var.dimensions == 2) {
			global_var.value = [[_localizedStringsService.LocalizedStrings.getUI('text_start'), _localizedStringsService.LocalizedStrings.getUI('text_start')], [_localizedStringsService.LocalizedStrings.getUI('text_start'), _localizedStringsService.LocalizedStrings.getUI('text_start')]];
		}
	}

	if (global_var.type == _types.Types.BOOLEAN) {
		if (global_var.dimensions == 0) {
			global_var.value = true;
		}
		if (global_var.dimensions == 1) {
			global_var.value = [true, true];
		}
		if (global_var.dimensions == 2) {
			global_var.value = [[true, true], [true, true]];
		}
	}
}

function alternateBooleanGlobalValue(global_var, value_container) {
	global_var.value = !global_var.value;
	(0, _jquery2.default)(value_container).find('.span_value_variable').text(_localizedStringsService.LocalizedStrings.getUI(global_var.value));
}

function alternateBooleanGlobalVectorValue(global_var, index, value_container) {
	global_var.value[index] = !global_var.value[index];
	(0, _jquery2.default)(value_container).find('.span_value_variable').text(_localizedStringsService.LocalizedStrings.getUI(global_var.value[index]));
}

function removeGlobalColumnVector(global_var) {
	if (global_var.columns == 0) {
		return;
	}

	global_var.columns--;
	global_var.value.splice(global_var.value.length - 1, 1);
}

function addGlobalColumnVector(global_var) {
	global_var.columns++;

	if (global_var.type == _types.Types.INTEGER) {
		global_var.value.push(1);
	}
	if (global_var.type == _types.Types.REAL) {
		global_var.value.push(1.0);
	}
	if (global_var.type == _types.Types.TEXT) {
		global_var.value.push(_localizedStringsService.LocalizedStrings.getUI('text_start'));
	}
	if (global_var.type == _types.Types.BOOLEAN) {
		global_var.value.push(true);
	}
}

function removeColumnGlobalMatrix(global_var) {
	if (global_var.columns == 0) {
		return;
	}

	global_var.columns--;

	for (var i = 0; i < global_var.rows; i++) {
		global_var.value[i].splice(global_var.value[i].length - 1, 1);
	}
}

function addColumnGlobalMatrix(global_var) {
	global_var.columns++;

	if (global_var.type == _types.Types.INTEGER) {
		for (var i = 0; i < global_var.rows; i++) {
			global_var.value[i].push(1);
		}
	}
	if (global_var.type == _types.Types.REAL) {
		for (var i = 0; i < global_var.rows; i++) {
			global_var.value[i].push(1.0);
		}
	}
	if (global_var.type == _types.Types.TEXT) {
		for (var i = 0; i < global_var.rows; i++) {
			global_var.value[i].push(_localizedStringsService.LocalizedStrings.getUI('text_start'));
		}
	}
	if (global_var.type == _types.Types.BOOLEAN) {
		for (var i = 0; i < global_var.rows; i++) {
			global_var.value[i].push(true);
		}
	}
}

function removeLineGlobalMatrix(global_var) {
	if (global_var.rows == 0) {
		return;
	}

	global_var.rows--;
	global_var.value.splice(global_var.value.length - 1, 1);
}

function addLineGlobalMatrix(global_var) {
	global_var.rows++;

	if (global_var.type == _types.Types.INTEGER) {
		var n_l = [];
		for (var i = 0; i < global_var.columns; i++) {
			n_l.push(1);
		}
		global_var.value.push(n_l);
	}
	if (global_var.type == _types.Types.REAL) {
		var n_l = [];
		for (i = 0; i < global_var.columns; i++) {
			n_l.push(1.0);
		}
		global_var.value.push(n_l);
	}

	if (global_var.type == _types.Types.TEXT) {
		var n_l = [];
		for (i = 0; i < global_var.columns; i++) {
			n_l.push(_localizedStringsService.LocalizedStrings.getUI('text_start'));
		}
		global_var.value.push(n_l);
	}

	if (global_var.type == _types.Types.BOOLEAN) {
		var n_l = [];
		for (i = 0; i < global_var.columns; i++) {
			n_l.push(true);
		}
		global_var.value.push(n_l);
	}
}

function alternateBooleanGlobalMatrixValue(global_var, row, index, value_container) {
	global_var.value[row][index] = !global_var.value[row][index];
	(0, _jquery2.default)(value_container).find('.span_value_variable').text(_localizedStringsService.LocalizedStrings.getUI(global_var.value[row][index]));
}

function renderValues(global_var, global_container) {

	var ret = "";
	var j = 0;

	if (global_var.dimensions == 0) {
		if (global_var.type == _types.Types.REAL) {
			ret += '<div class="created_div_valor_var"><span class="span_value_variable simple_var">' + global_var.value.toFixed(1) + '</span>  </div> ';
		} else {
			if (global_var.type == _types.Types.BOOLEAN) {
				ret += '<div class="created_div_valor_var"><span class="span_value_variable boolean_simple_type">' + _localizedStringsService.LocalizedStrings.getUI(global_var.value) + '</span>  </div> ';
			} else {
				ret += '<div class="created_div_valor_var"><span class="span_value_variable simple_var">' + global_var.value + '</span>  </div> ';
			}
		}
	} else {
		ret += '<table class="tabela_var">';

		if (global_var.dimensions == 1) {
			ret += '<tr>';
			if (global_var.type == _types.Types.REAL) {
				for (var k = 0; k < global_var.columns; k++) {
					ret += '<td><span class="span_value_variable vector_var" data-index="' + k + '">' + global_var.value[k].toFixed(1) + '</span></td>';
				}
			} else {
				for (var k = 0; k < global_var.columns; k++) {
					if (global_var.type == _types.Types.BOOLEAN) {
						ret += '<td><span class="span_value_variable boolean_vector_var" data-index="' + k + '">' + _localizedStringsService.LocalizedStrings.getUI(global_var.value[k]) + '</span></td>';
					} else {
						ret += '<td><span class="span_value_variable vector_var" data-index="' + k + '">' + global_var.value[k] + '</span>' + '</td>';
					}
				}
			}

			ret += '</tr>';
			ret += '</table>';

			ret += '<div class="buttons_manage_columns"><i class="ui icon minus square outline remove_global_vector_column"></i>' + ' <i class="ui icon plus square outline add_global_vector_column"></i></div>';
		}

		if (global_var.dimensions == 2) {
			if (global_var.type == _types.Types.REAL) {
				for (var l = 0; l < global_var.rows; l++) {
					ret += '<tr>';
					for (var k = 0; k < global_var.columns; k++) {
						ret += '<td><span class="span_value_variable matrix_var" data-index="' + k + '" data-row="' + l + '">' + global_var.value[l][k].toFixed(1) + '</span>' + '</td>';
					}
					ret += '</tr>';
				}
			} else {
				for (var l = 0; l < global_var.rows; l++) {
					ret += '<tr>';
					for (var k = 0; k < global_var.columns; k++) {
						if (global_var.type == _types.Types.BOOLEAN) {
							ret += '<td><span class="span_value_variable boolean_matrix_var" data-index="' + k + '" data-row="' + l + '">' + _localizedStringsService.LocalizedStrings.getUI(global_var.value[l][k]) + '</span></td>';
						} else {
							ret += '<td><span class="span_value_variable matrix_var" data-index="' + k + '" data-row="' + l + '">' + global_var.value[l][k] + '</span></td>';
						}
					}
					ret += '</tr>';
				}
			}
			if (global_var.rows == 0) {
				ret += '<tr><td></td></tr>';
			}
			ret += '<tr><td colspan="' + global_var.columns + '" class="tr_manage_lines"><i class="ui icon minus square outline remove_global_matrix_line"></i>' + ' <i class="ui icon plus square outline add_global_matrix_line"></i></td></tr>';
			ret += '</table>';

			ret += '<div class="buttons_manage_columns"><i class="ui icon minus square outline remove_global_matrix_column"></i>' + ' <i class="ui icon plus square outline add_global_matrix_column"></i></div>';
		}
	}

	global_container.find(".div_valor_var").html('');

	ret = (0, _jquery2.default)(ret);

	ret.find('.span_value_variable').data('associatedOject', global_var);

	ret.find(".boolean_simple_type").on('click', function (e) {
		alternateBooleanGlobalValue(global_var, this.parentNode);
	});
	ret.find(".simple_var").on('click', function (e) {
		enableGlobalValueUpdate(global_var, this.parentNode);
	});

	ret.find(".boolean_vector_var").on('click', function (e) {
		alternateBooleanGlobalVectorValue(global_var, (0, _jquery2.default)(this).data('index'), this.parentNode);
	});
	ret.find(".vector_var").on('click', function (e) {
		enableGlobalVectorValueUpdate(global_var, (0, _jquery2.default)(this).data('index'), this.parentNode);
	});
	ret.find(".remove_global_vector_column").on('click', function (e) {
		removeGlobalColumnVector(global_var);
		global_container.find(".div_valor_var").html('');
		renderValues(global_var, global_container);
	});
	ret.find(".add_global_vector_column").on('click', function (e) {
		addGlobalColumnVector(global_var);
		global_container.find(".div_valor_var").html('');
		renderValues(global_var, global_container);
	});
	ret.find(".remove_global_matrix_column").on('click', function (e) {
		removeColumnGlobalMatrix(global_var);
		global_container.find(".div_valor_var").html('');
		renderValues(global_var, global_container);
	});
	ret.find(".add_global_matrix_column").on('click', function (e) {
		addColumnGlobalMatrix(global_var);
		global_container.find(".div_valor_var").html('');
		renderValues(global_var, global_container);
	});
	ret.find(".remove_global_matrix_line").on('click', function (e) {
		removeLineGlobalMatrix(global_var);
		global_container.find(".div_valor_var").html('');
		renderValues(global_var, global_container);
	});
	ret.find(".add_global_matrix_line").on('click', function (e) {
		addLineGlobalMatrix(global_var);
		global_container.find(".div_valor_var").html('');
		renderValues(global_var, global_container);
	});
	ret.find(".boolean_matrix_var").on('click', function (e) {
		alternateBooleanGlobalMatrixValue(global_var, (0, _jquery2.default)(this).data('row'), (0, _jquery2.default)(this).data('index'), this.parentNode);
	});
	ret.find(".matrix_var").on('click', function (e) {
		enableGlobalMatrixValueUpdate(global_var, (0, _jquery2.default)(this).data('row'), (0, _jquery2.default)(this).data('index'), this.parentNode);
	});
	global_container.find(".div_valor_var").append(ret);

	updateColumnsAndRowsText(global_container, global_var);
}

function addHandlers(global_container) {
	var global_var = global_container.data('associatedOject');
	// Manage constant option:
	global_container.find(".alternate_constant").on('click', function (e) {
		toggleConstant(global_var);

		(0, _jquery2.default)(this).removeClass("on off");
		if (global_var.is_constant) {
			(0, _jquery2.default)(this).addClass("on");
		} else {
			(0, _jquery2.default)(this).addClass("off");
		}
	});

	// Manage global name: 
	global_container.find(".enable_edit_name_parameter").on('click', function (e) {
		enableNameUpdate(global_container);
	});

	// Menu to change type:
	global_container.find('.ui.dropdown.global_type').dropdown({
		onChange: function onChange(value, text, $selectedItem) {
			if ($selectedItem.data('dimensions')) {
				updateType(global_var, _types.Types[$selectedItem.data('type')], $selectedItem.data('dimensions'));
			} else {
				updateType(global_var, _types.Types[$selectedItem.data('type')]);
			}

			renderValues(global_var, global_container);
		},
		selectOnKeydown: false
	});

	// Remove global: 
	global_container.find(".remove_global").on('click', function (e) {
		removeGlobal(global_var, global_container);
	});
}

function updateColumnsAndRowsText(global_container, global_var) {
	var prev = global_container.find('.text').text().split('[');
	if (prev.length == 2) {
		var ff = prev[0] + '[ ' + global_var.columns + ' ] ';
		global_container.find('.text').empty();
		global_container.find('.text').text(ff);
	}
	if (prev.length == 3) {
		var ff = prev[0] + '[ ' + global_var.columns + ' ] [ ' + global_var.rows + ' ] ';
		global_container.find('.text').empty();
		global_container.find('.text').text(ff);
	}
}

function renderGlobal(global_var) {

	var element = '<div class="ui label global_container pink"><i class="ui icon ellipsis vertical inverted"></i><div class="global_const">const: ';

	element += '<i class="ui icon toggle ' + (global_var.is_constant ? "on" : "off") + ' alternate_constant"></i></div>';

	element += '<div class="ui dropdown global_type">';

	if (global_var.dimensions > 0) {
		element += '<div class="text">' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(global_var.type);
		for (var i = 0; i < global_var.dimensions; i++) {
			element += ' [ <span class="dimensions_' + i + '"></span> ] ';
		}
		element += '</div>';
	} else {
		element += '<div class="text">' + _localizedStringsService.LocalizedStrings.getUI(global_var.type.toLowerCase()) + '</div>';
	}
	element += '<div class="menu">';

	for (var tm in _types.Types) {
		if (tm == _types.Types.VOID.toUpperCase()) {
			continue;
		}
		element += '<div class="item ' + (global_var.type == tm.toLowerCase() ? ' selected ' : '') + '" data-type="' + tm + '" >' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + '</div>';
	}

	for (var tm in _types.Types) {
		if (tm == _types.Types.VOID.toUpperCase()) {
			continue;
		}
		element += '<div class="item">' + '<i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + '<div class="menu">' + '<div class="item" data-text="' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + ' [ ] " data-type="' + tm + '" data-dimensions="1">[ ]</div>' + '<div class="item" data-text="' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + ' [ ] [ ] " data-type="' + tm + '" data-dimensions="2">[ ] [ ] </div>' + '</div>' + '</div>';
	}

	element += '</div></div> <div class="editing_name_var"> <span class="span_name_variable enable_edit_name_parameter">' + global_var.name + '</span> </div> <span class="character_equals"> = </span> ';

	element += '<div class="ui div_valor_var">' + global_var.value + '</div>';

	element += ' <i class="yellow inverted icon times remove_global"></i></div>';

	var complete_element = (0, _jquery2.default)(element);

	complete_element.data('associatedOject', global_var);

	(0, _jquery2.default)('.list_globals').append(complete_element);

	addHandlers(complete_element);

	renderValues(global_var, complete_element);

	if (global_var.dimensions == 1) {
		complete_element.find('.dimensions_0').text(global_var.columns);
	}
	if (global_var.dimensions == 2) {
		complete_element.find('.dimensions_0').text(global_var.columns);
		complete_element.find('.dimensions_1').text(global_var.rows);
	}

	return complete_element;
}

var opened_name_value_matrix_global_v = false;
var opened_input_value_matrix_global_v = null;
function enableGlobalMatrixValueUpdate(global_var, row, index, parent_node) {
	if (opened_name_value_matrix_global_v) {
		opened_input_value_matrix_global_v.focus();
		return;
	}
	parent_node = (0, _jquery2.default)(parent_node);
	opened_name_value_matrix_global_v = true;

	parent_node.find('.span_value_variable').text('');

	var input_field;

	if (global_var.type == _types.Types.REAL) {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + global_var.value[row][index].toFixed(1) + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	} else {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + global_var.value[row][index] + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	}

	input_field.on('input', function () {
		var inputWidth = input_field.textWidth() + 10;
		opened_input_value_matrix_global_v = input_field;
		input_field.focus();

		var tmpStr = input_field.val();
		input_field.val('');
		input_field.val(tmpStr);

		input_field.css({
			width: inputWidth
		});
	}).trigger('input');

	input_field.focusout(function () {
		/// update array:
		if (input_field.val().trim()) {
			if (global_var.type == _types.Types.REAL) {
				global_var.value[row][index] = parseFloat(input_field.val().trim());

				parent_node.find('.span_value_variable').text(global_var.value[row][index].toFixed(1));
			} else {
				if (global_var.type == _types.Types.INTEGER) {
					global_var.value[row][index] = parseInt(input_field.val().trim());
				} else {
					global_var.value[row][index] = input_field.val().trim();
				}
				parent_node.find('.span_value_variable').text(global_var.value[row][index]);
			}
		} else {
			if (global_var.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(global_var.value[row][index].toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(global_var.value[row][index]);
			}
		}
		if (global_var.type == _types.Types.TEXT) {
			global_var.value[row][index] = input_field.val();
			parent_node.find('.span_value_variable').text(global_var.value[row][index]);
		}
		input_field.off();
		input_field.remove();

		/// update elements:
		opened_name_value_matrix_global_v = false;
		opened_input_value_matrix_global_v = false;
	});

	input_field.on('keydown', function (e) {
		var code = e.keyCode || e.which;
		if (code == 13) {
			if (input_field.val().trim()) {
				if (global_var.type == _types.Types.REAL) {
					global_var.value[row][index] = parseFloat(input_field.val().trim());

					parent_node.find('.span_value_variable').text(global_var.value[row][index].toFixed(1));
				} else {
					if (global_var.type == _types.Types.INTEGER) {
						global_var.value[row][index] = parseInt(input_field.val().trim());
					} else {
						global_var.value[row][index] = input_field.val().trim();
					}
					parent_node.find('.span_value_variable').text(global_var.value[row][index]);
				}
			} else {
				if (global_var.type == _types.Types.REAL) {
					parent_node.find('.span_value_variable').text(global_var.value[row][index].toFixed(1));
				} else {
					parent_node.find('.span_value_variable').text(global_var.value[row][index]);
				}
			}
			if (global_var.type == _types.Types.TEXT) {
				global_var.value[row][index] = input_field.val();
				parent_node.find('.span_value_variable').text(global_var.value[row][index]);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_matrix_global_v = false;
			opened_input_value_matrix_global_v = false;
		}
		if (code == 27) {
			if (global_var.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(global_var.value[row][index].toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(global_var.value[row][index]);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_matrix_global_v = false;
			opened_input_value_matrix_global_v = false;
		}
	});
	input_field.select();
}

var opened_name_value_global_var = false;
var opened_input_value_global_ar = null;
function enableGlobalValueUpdate(global_var, parent_node) {
	if (opened_name_value_global_var) {
		opened_input_value_global_ar.focus();
		return;
	}
	parent_node = (0, _jquery2.default)(parent_node);
	opened_name_value_global_var = true;

	parent_node.find('.span_value_variable').text('');

	var input_field;

	if (global_var.type == _types.Types.REAL) {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + global_var.value.toFixed(1) + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	} else {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + global_var.value + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	}

	input_field.on('input', function () {
		var inputWidth = input_field.textWidth() + 10;
		opened_input_value_global_ar = input_field;
		input_field.focus();

		var tmpStr = input_field.val();
		input_field.val('');
		input_field.val(tmpStr);

		input_field.css({
			width: inputWidth
		});
	}).trigger('input');

	input_field.focusout(function () {
		/// update array:
		if (input_field.val().trim()) {
			if (global_var.type == _types.Types.REAL) {
				global_var.value = parseFloat(input_field.val().trim());
				parent_node.find('.span_value_variable').text(global_var.value.toFixed(1));
			} else {
				if (global_var.type == _types.Types.INTEGER) {
					global_var.value = parseInt(input_field.val().trim());
				} else {
					global_var.value = input_field.val().trim();
				}
				parent_node.find('.span_value_variable').text(global_var.value);
			}
		} else {
			if (global_var.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(global_var.value.toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(global_var.value);
			}
		}
		if (global_var.type == _types.Types.TEXT) {
			global_var.value = input_field.val();
			parent_node.find('.span_value_variable').text(global_var.value);
		}
		input_field.off();
		input_field.remove();

		/// update elements:
		opened_name_value_global_var = false;
		opened_input_value_global_ar = false;
	});

	input_field.on('keydown', function (e) {
		var code = e.keyCode || e.which;
		if (code == 13) {
			if (input_field.val().trim()) {
				if (global_var.type == _types.Types.REAL) {
					global_var.value = parseFloat(input_field.val().trim());
					parent_node.find('.span_value_variable').text(global_var.value.toFixed(1));
				} else {
					if (global_var.type == _types.Types.INTEGER) {
						global_var.value = parseInt(input_field.val().trim());
					} else {
						global_var.value = input_field.val().trim();
					}
					parent_node.find('.span_value_variable').text(global_var.value);
				}
			} else {
				if (global_var.type == _types.Types.REAL) {
					parent_node.find('.span_value_variable').text(global_var.value.toFixed(1));
				} else {
					parent_node.find('.span_value_variable').text(global_var.value);
				}
			}
			if (global_var.type == _types.Types.TEXT) {
				global_var.value = input_field.val();
				parent_node.find('.span_value_variable').text(global_var.value);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_global_var = false;
			opened_input_value_global_ar = false;
		}
		if (code == 27) {
			if (global_var.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(global_var.value.toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(global_var.value);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_global_var = false;
			opened_input_value_global_ar = false;
		}
	});

	input_field.select();
}

var opened_name_global = false;
var opened_input_global = null;
function enableNameUpdate(global_container) {

	var global_var = global_container.data('associatedOject');

	if (opened_name_global) {
		opened_input_global.focus();
		return;
	}
	opened_name_global = true;

	global_container.find('.span_name_variable').text('');
	var input_name = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + global_var.name + "' />");
	input_name.insertBefore(global_container.find('.span_name_variable'));

	input_name.on('input', function () {
		var inputWidth = input_name.textWidth() + 10;
		opened_input_global = input_name;
		opened_input_global.focus();

		opened_input_global.css({
			width: inputWidth
		});
	}).trigger('input');

	input_name.focusout(function () {
		/// update array:
		if (input_name.val().trim().length > 0) {
			updateName(global_var, input_name.val().trim(), global_container);
			global_container.find('.span_name_variable').text(global_var.name);
		} else {
			global_container.find('.span_name_variable').text(global_var.name);
		}
		input_name.off();
		input_name.remove();

		/// update elements:
		opened_name_global = false;
		opened_input_global = false;
	});

	input_name.on('keydown', function (e) {
		var code = e.keyCode || e.which;
		if (code == 13) {
			if (input_name.val().trim()) {
				updateName(global_var, input_name.val().trim(), global_container);
				global_container.find('.span_name_variable').text(global_var.name);
			} else {
				global_container.find('.span_name_variable').text(global_var.name);
			}
			input_name.off();
			input_name.remove();

			/// update elements:
			opened_name_global = false;
			opened_input_global = false;
		}
		if (code == 27) {

			global_container.find('.span_name_variable').text(global_var.name);
			input_name.off();
			input_name.remove();

			/// update elements:
			opened_name_global = false;
			opened_input_global = false;
		}
	});

	input_name.select();
}

var opened_name_value_vector_global_ = false;
var opened_input_value_vector_global_ = null;
function enableGlobalVectorValueUpdate(global_var, index, parent_node) {
	if (opened_name_value_vector_global_) {
		opened_input_value_vector_global_.focus();
		return;
	}
	parent_node = (0, _jquery2.default)(parent_node);
	opened_name_value_vector_global_ = true;

	parent_node.find('.span_value_variable').text('');

	var input_field;

	if (global_var.type == _types.Types.REAL) {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + global_var.value[index].toFixed(1) + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	} else {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + global_var.value[index] + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	}

	input_field.on('input', function () {
		var inputWidth = input_field.textWidth() + 10;
		opened_input_value_vector_global_ = input_field;
		input_field.focus();

		var tmpStr = input_field.val();
		input_field.val('');
		input_field.val(tmpStr);

		input_field.css({
			width: inputWidth
		});
	}).trigger('input');

	input_field.focusout(function () {
		/// update array:
		if (input_field.val().trim()) {
			if (global_var.type == _types.Types.REAL) {
				global_var.value[index] = parseFloat(input_field.val().trim());

				parent_node.find('.span_value_variable').text(global_var.value[index].toFixed(1));
			} else {

				if (global_var.type == _types.Types.INTEGER) {
					global_var.value[index] = parseInt(input_field.val().trim());
				} else {
					global_var.value[index] = input_field.val().trim();
				}

				parent_node.find('.span_value_variable').text(global_var.value[index]);
			}
		} else {
			if (global_var.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(global_var.value[index].toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(global_var.value[index]);
			}
		}
		if (global_var.type == _types.Types.TEXT) {
			global_var.value[index] = input_field.val();
			parent_node.find('.span_value_variable').text(global_var.value[index]);
		}
		input_field.off();
		input_field.remove();

		/// update elements:
		opened_name_value_vector_global_ = false;
		opened_input_value_vector_global_ = false;
	});

	input_field.on('keydown', function (e) {
		var code = e.keyCode || e.which;
		if (code == 13) {
			if (input_field.val().trim()) {
				if (global_var.type == _types.Types.REAL) {
					global_var.value[index] = parseFloat(input_field.val().trim());

					parent_node.find('.span_value_variable').text(global_var.value[index].toFixed(1));
				} else {

					if (global_var.type == _types.Types.INTEGER) {
						global_var.value[index] = parseInt(input_field.val().trim());
					} else {
						global_var.value[index] = input_field.val().trim();
					}

					parent_node.find('.span_value_variable').text(global_var.value[index]);
				}
			} else {
				if (global_var.type == _types.Types.REAL) {
					parent_node.find('.span_value_variable').text(global_var.value[index].toFixed(1));
				} else {
					parent_node.find('.span_value_variable').text(global_var.value[index]);
				}
			}
			if (global_var.type == _types.Types.TEXT) {
				global_var.value[index] = input_field.val();
				parent_node.find('.span_value_variable').text(global_var.value[index]);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_vector_global_ = false;
			opened_input_value_vector_global_ = false;
		}
		if (code == 27) {
			if (global_var.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(global_var.value[index].toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(global_var.value[index]);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_vector_global_ = false;
			opened_input_value_vector_global_ = false;
		}
	});

	input_field.select();
}

_jquery2.default.fn.textWidth = function (text, font) {

	if (!_jquery2.default.fn.textWidth.fakeEl) _jquery2.default.fn.textWidth.fakeEl = (0, _jquery2.default)('<span>').hide().appendTo(document.body);

	_jquery2.default.fn.textWidth.fakeEl.text(text || this.val() || this.text() || this.attr('placeholder')).css('font', font || this.css('font'));

	return _jquery2.default.fn.textWidth.fakeEl.width();
};

/***/ }),

/***/ "./js/visualUI/ivprog_elements.js":
/*!****************************************!*\
  !*** ./js/visualUI/ivprog_elements.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Program = exports.FunctionCallMenu = exports.VariableValueMenu = exports.FunctionCall = exports.SwitchCase = exports.Return = exports.Switch = exports.DoWhileTrue = exports.WhileTrue = exports.RepeatNTimes = exports.IfTrue = exports.ArithmeticExpression = exports.LogicExpression = exports.ConditionalExpression = exports.ExpressionElement = exports.Attribution = exports.Writer = exports.Reader = exports.Break = exports.Comment = exports.SystemFunction = exports.Function = exports.Variable = exports.SYSTEM_FUNCTIONS_CATEGORIES = exports.LOGIC_COMPARISON = exports.ARITHMETIC_COMPARISON = exports.EXPRESSION_TYPES = exports.EXPRESSION_ELEMENTS = exports.ARITHMETIC_TYPES = exports.COMMAND_TYPES = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _variable_value_menu = __webpack_require__(/*! ./commands/variable_value_menu */ "./js/visualUI/commands/variable_value_menu.js");

var VariableValueMenuManagement = _interopRequireWildcard(_variable_value_menu);

var _types = __webpack_require__(/*! ./types */ "./js/visualUI/types.js");

var _melankeWatchjs = __webpack_require__(/*! melanke-watchjs */ "./node_modules/melanke-watchjs/src/watch.js");

var _melankeWatchjs2 = _interopRequireDefault(_melankeWatchjs);

var _algorithm = __webpack_require__(/*! ./algorithm */ "./js/visualUI/algorithm.js");

var AlgorithmManagement = _interopRequireWildcard(_algorithm);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var COMMAND_TYPES = exports.COMMAND_TYPES = Object.freeze({ function: "function", comment: "comment", reader: "reader", writer: "writer", attribution: "attribution", iftrue: "iftrue",
  repeatNtimes: "repeatNtimes", whiletrue: "whiletrue", dowhiletrue: "dowhiletrue", switch: "switch", switchcase: "switchcase", functioncall: "functioncall", break: "break",
  return: "return" });

var ARITHMETIC_TYPES = exports.ARITHMETIC_TYPES = Object.freeze({ plus: "plus", minus: "minus", multiplication: "multiplication", division: "division", module: "module", none: "none" });

var EXPRESSION_ELEMENTS = exports.EXPRESSION_ELEMENTS = Object.freeze({ exp_op_exp: "exp_op_exp", op_exp: "op_exp", par_exp_par: "par_exp_par", start_point: "start_point" });

var EXPRESSION_TYPES = exports.EXPRESSION_TYPES = Object.freeze({ exp_conditional: "exp_conditional", exp_logic: "exp_logic", exp_arithmetic: "exp_arithmetic" });

var ARITHMETIC_COMPARISON = exports.ARITHMETIC_COMPARISON = Object.freeze({ greater_than: "greater_than", less_than: "less_than", equals_to: "equals_to", not_equals_to: "not_equals_to", greater_than_or_equals_to: "greater_than_or_equals_to", less_than_or_equals_to: "less_than_or_equals_to" });

var LOGIC_COMPARISON = exports.LOGIC_COMPARISON = Object.freeze({ equals_to: "equals_to", not_equals_to: "not_equals_to", and: "and", or: "or" });

var SYSTEM_FUNCTIONS_CATEGORIES = exports.SYSTEM_FUNCTIONS_CATEGORIES = Object.freeze({ math: "math", text: "text_t", arrangement: "arrangement", conversion: "conversion" });

var Variable = exports.Variable = function Variable(type, name, value) {
  var dimensions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  var is_constant = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  var rows = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
  var columns = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;

  _classCallCheck(this, Variable);

  this.type = type;
  this.name = name;
  this.value = value;
  this.dimensions = dimensions;
  this.is_constant = is_constant;
  this.rows = rows;
  this.columns = columns;
};

var Function = exports.Function = function Function(name) {
  var return_type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _types.Types.VOID;
  var return_dimensions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  var parameters_list = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  var is_main = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  var is_hidden = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
  var variables_list = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : [];
  var function_comment = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null;
  var commands = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : [];

  _classCallCheck(this, Function);

  this.type = COMMAND_TYPES.function;
  this.name = name;
  this.return_type = return_type;
  this.return_dimensions = return_dimensions;
  this.parameters_list = parameters_list;
  this.is_main = is_main;
  this.is_hidden = is_hidden;
  this.variables_list = variables_list;
  this.function_comment = function_comment;
  this.commands = commands;
};

var SystemFunction = exports.SystemFunction = function SystemFunction(identifier, return_type, return_dimensions, parameters_list) {
  var function_comment = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
  var category = arguments[5];

  _classCallCheck(this, SystemFunction);

  this.type = COMMAND_TYPES.function;
  this.identifier = identifier;
  this.return_type = return_type;
  this.return_dimensions = return_dimensions;
  this.parameters_list = parameters_list;
  this.function_comment = function_comment;
  this.category = category;
};

var Comment = exports.Comment = function Comment(comment_text) {
  _classCallCheck(this, Comment);

  this.type = COMMAND_TYPES.comment;
  this.comment_text = comment_text;
};

var Break = exports.Break = function Break() {
  _classCallCheck(this, Break);

  this.type = COMMAND_TYPES.break;
};

var Reader = exports.Reader = function Reader() {
  var variable_value_menu = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new VariableValueMenu();

  _classCallCheck(this, Reader);

  this.type = COMMAND_TYPES.reader;
  this.variable_value_menu = variable_value_menu;
};

var Writer = exports.Writer = function Writer(content) {
  _classCallCheck(this, Writer);

  this.type = COMMAND_TYPES.writer;
  this.content = content;
};

var Attribution = exports.Attribution = function Attribution(variable) {
  var expression = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  _classCallCheck(this, Attribution);

  this.type = COMMAND_TYPES.attribution;
  this.variable = variable;
  this.expression = expression;
};

var ExpressionElement = exports.ExpressionElement = function ExpressionElement(type_exp) {
  var itens = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  _classCallCheck(this, ExpressionElement);

  this.type_exp = type_exp;
  this.itens = itens;
};

var ConditionalExpression = exports.ConditionalExpression = function ConditionalExpression(expression) {
  _classCallCheck(this, ConditionalExpression);

  this.type = EXPRESSION_TYPES.exp_conditional;
  this.expression = expression;
};

var LogicExpression = exports.LogicExpression = function LogicExpression(has_neg, first_operand, second_operand, operator) {
  _classCallCheck(this, LogicExpression);

  this.type = EXPRESSION_TYPES.exp_logic;
  this.has_neg = has_neg;
  this.first_operand = first_operand;
  this.second_operand = second_operand;
  this.operator = operator;
};

var ArithmeticExpression = exports.ArithmeticExpression = function ArithmeticExpression(first_operand, second_operand, operator) {
  _classCallCheck(this, ArithmeticExpression);

  this.type = EXPRESSION_TYPES.exp_arithmetic;
  this.first_operand = first_operand;
  this.second_operand = second_operand;
  this.operator = operator;
};

var IfTrue = exports.IfTrue = function IfTrue(expression, commands_block, commands_else) {
  _classCallCheck(this, IfTrue);

  this.type = COMMAND_TYPES.iftrue;
  this.expression = expression;
  this.commands_block = commands_block;
  this.commands_else = commands_else;
};

var RepeatNTimes = exports.RepeatNTimes = function RepeatNTimes(var_attribution, var_incrementation, expression1, expression2, expression3, commands_block) {
  _classCallCheck(this, RepeatNTimes);

  this.type = COMMAND_TYPES.repeatNtimes;
  this.var_attribution = var_attribution;
  this.var_incrementation = var_incrementation;
  this.expression1 = expression1;
  this.expression2 = expression2;
  this.expression3 = expression3;
  this.commands_block = commands_block;
};

var WhileTrue = exports.WhileTrue = function WhileTrue(expression, commands_block) {
  _classCallCheck(this, WhileTrue);

  this.type = COMMAND_TYPES.whiletrue;
  this.expression = expression;
  this.commands_block = commands_block;
};

var DoWhileTrue = exports.DoWhileTrue = function DoWhileTrue(expression, commands_block) {
  _classCallCheck(this, DoWhileTrue);

  this.type = COMMAND_TYPES.dowhiletrue;
  this.expression = expression;
  this.commands_block = commands_block;
};

var Switch = exports.Switch = function Switch(variable) {
  var cases = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  _classCallCheck(this, Switch);

  this.type = COMMAND_TYPES.switch;
  this.variable = variable;
  this.cases = cases;
};

var Return = exports.Return = function Return(variable_value_menu) {
  _classCallCheck(this, Return);

  this.type = COMMAND_TYPES.return;
  this.variable_value_menu = variable_value_menu;
};

var SwitchCase = exports.SwitchCase = function SwitchCase(variable_value_menu) {
  var commands_block = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  _classCallCheck(this, SwitchCase);

  this.type = COMMAND_TYPES.switchcase;
  this.variable_value_menu = variable_value_menu;
  this.commands_block = commands_block;
};

var FunctionCall = exports.FunctionCall = function FunctionCall(function_called, parameters_list) {
  _classCallCheck(this, FunctionCall);

  this.type = COMMAND_TYPES.functioncall;
  this.function_called = function_called;
  this.parameters_list = parameters_list;
};

var VariableValueMenu = exports.VariableValueMenu = function VariableValueMenu() {
  var variable_and_value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 7;
  var content = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  var row = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  var column = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  var include_constant = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  var dimensions = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;

  _classCallCheck(this, VariableValueMenu);

  this.type = "var_value";
  this.variable_and_value = variable_and_value;
  this.content = content;
  this.row = row;
  this.column = column;
  this.include_constant = include_constant;
  this.dimensions = dimensions;
};

var FunctionCallMenu = exports.FunctionCallMenu = function FunctionCallMenu() {
  var function_called = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
  var parameters_list = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  _classCallCheck(this, FunctionCallMenu);

  this.type = "function_call";
  this.function_called = function_called;
  this.parameters_list = parameters_list;
};

var Program = exports.Program = function () {
  function Program() {
    _classCallCheck(this, Program);

    this.functions = [];
    this.globals = [];
  }

  _createClass(Program, [{
    key: 'addFunction',
    value: function addFunction(function_to_add) {

      _melankeWatchjs2.default.watch(function_to_add.parameters_list, function () {
        if (window.insertContext) {
          setTimeout(function () {
            AlgorithmManagement.renderAlgorithm();
          }, 300);
          window.insertContext = false;
        } else {
          AlgorithmManagement.renderAlgorithm();
        }
      }, 1);

      _melankeWatchjs2.default.watch(function_to_add.variables_list, function () {
        if (window.insertContext) {
          setTimeout(function () {
            AlgorithmManagement.renderAlgorithm();
          }, 300);
          window.insertContext = false;
        } else {
          AlgorithmManagement.renderAlgorithm();
        }
      }, 1);

      this.functions.push(function_to_add);
    }
  }, {
    key: 'addVariable',
    value: function addVariable(function_to_receive, variable) {
      if (this.functions[function_to_receive].variable === null) {
        this.functions[function_to_receive].variables_list = [];
      }
      this.functions[function_to_receive].variables_list.push(variable);
    }
  }, {
    key: 'addGlobal',
    value: function addGlobal(variable) {
      this.globals.push(variable);
    }
  }]);

  return Program;
}();

/***/ }),

/***/ "./js/visualUI/types.js":
/*!******************************!*\
  !*** ./js/visualUI/types.js ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var Types = exports.Types = Object.freeze({
  INTEGER: "integer",
  REAL: "real",
  TEXT: "text",
  BOOLEAN: "boolean",
  VOID: "void"
});

/***/ }),

/***/ "./js/visualUI/utils.js":
/*!******************************!*\
  !*** ./js/visualUI/utils.js ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.renderErrorMessage = renderErrorMessage;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function renderErrorMessage(dom_obj_target, message_text) {

	dom_obj_target.popup({
		html: '<i class="ui icon inverted exclamation triangle yellow"></i>' + message_text,
		transition: "fade up",
		on: 'click',
		closable: true,
		movePopup: true,
		boundary: window,
		preserve: false,
		target: false,
		className: {
			popup: 'ui popup invalid-identifier'
		},
		onHidden: function onHidden($module) {
			dom_obj_target.popup('destroy');
		}

	}).popup('toggle');
}

/***/ }),

/***/ "./js/visualUI/variables.js":
/*!**********************************!*\
  !*** ./js/visualUI/variables.js ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.addVariable = addVariable;
exports.renderVariable = renderVariable;

var _jquery = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js");

var _jquery2 = _interopRequireDefault(_jquery);

var _types = __webpack_require__(/*! ./types */ "./js/visualUI/types.js");

var _ivprog_elements = __webpack_require__(/*! ./ivprog_elements */ "./js/visualUI/ivprog_elements.js");

var Models = _interopRequireWildcard(_ivprog_elements);

var _localizedStringsService = __webpack_require__(/*! ./../services/localizedStringsService */ "./js/services/localizedStringsService.js");

var _utils = __webpack_require__(/*! ./utils */ "./js/visualUI/utils.js");

var Utils = _interopRequireWildcard(_utils);

__webpack_require__(/*! ../semantic/semantic.min.js */ "./js/semantic/semantic.min.js");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

window.jQuery = _jquery2.default;

var counter_new_variables = 0;

function addVariable(function_obj, function_container) {
	var is_in_click = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

	var new_var = new Models.Variable(_types.Types.INTEGER, _localizedStringsService.LocalizedStrings.getUI('new_variable') + '_' + counter_new_variables, 1);
	if (function_obj.variables_list == null) {
		function_obj.variables_list = [];
	}
	function_obj.variables_list.push(new_var);

	counter_new_variables++;

	var newe = renderVariable(function_container, new_var, function_obj);

	if (is_in_click) {
		newe.css('display', 'none');
		newe.fadeIn();
	}
}

function updateName(variable_obj, new_name, variable_obj_dom, function_obj) {

	if (isValidIdentifier(new_name)) {
		if (variableNameAlreadyExists(new_name, function_obj)) {
			Utils.renderErrorMessage(variable_obj_dom.find('.editing_name_var'), _localizedStringsService.LocalizedStrings.getUI('inform_valid_variable_duplicated'));
		} else {
			variable_obj.name = new_name;
		}
	} else {
		Utils.renderErrorMessage(variable_obj_dom.find('.editing_name_var'), _localizedStringsService.LocalizedStrings.getUI('inform_valid_name'));
	}
}

function variableNameAlreadyExists(name_var, function_obj) {

	if (function_obj.parameters_list) {
		for (var i = 0; i < function_obj.parameters_list.length; i++) {
			if (function_obj.parameters_list[i].name == name_var) {
				return true;
			}
		}
	}

	if (function_obj.variables_list) {
		for (var i = 0; i < function_obj.variables_list.length; i++) {
			if (function_obj.variables_list[i].name == name_var) {
				return true;
			}
		}
	}

	return false;
}

function isValidIdentifier(identifier_str) {
	return (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(identifier_str)
	);
}

function removeVariable(variable_obj, variable_container) {
	var function_associated = variable_container.data('associatedFunction');

	var index = function_associated.variables_list.indexOf(variable_obj);
	if (index > -1) {
		window.insertContext = true;
		delete function_associated.variables_list[index];
		function_associated.variables_list.splice(index, 1);
	}
	variable_container.children().off();
	variable_container.off();
	variable_container.fadeOut();
}

function updateType(variable_obj, new_type) {
	var new_dimensions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;

	variable_obj.type = new_type;
	variable_obj.dimensions = new_dimensions;

	if (new_dimensions > 0) {
		variable_obj.rows = new_dimensions;
		variable_obj.columns = 2;
	}

	updateInitialValues(variable_obj);
}

function addHandlers(variable_obj, variable_container, function_obj) {

	// Manage variable name: 
	variable_container.find(".enable_edit_name_variable").on('click', function (e) {
		enableNameUpdate(variable_obj, variable_container, function_obj);
	});

	// Menu to change type:
	variable_container.find('.ui.dropdown.variable_type').dropdown({
		onChange: function onChange(value, text, $selectedItem) {
			if ($selectedItem.data('dimensions')) {
				updateType(variable_obj, _types.Types[$selectedItem.data('type')], $selectedItem.data('dimensions'));
			} else {
				updateType(variable_obj, _types.Types[$selectedItem.data('type')]);
			}

			renderValues(variable_obj, variable_container);
		},
		selectOnKeydown: false
	});

	// Remove variable: 
	variable_container.find(".remove_variable").on('click', function (e) {
		removeVariable(variable_obj, variable_container);
	});
}

function renderVariable(function_container, new_var, function_obj) {

	var element = '<div class="ui label variable_container pink"><i class="ui icon ellipsis vertical inverted"></i>';

	element += '<div class="ui dropdown variable_type">';

	if (new_var.dimensions > 0) {
		element += '<div class="text">' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(new_var.type.toLowerCase());
		for (var i = 0; i < new_var.dimensions; i++) {
			element += ' [ ] ';
		}
		element += '</div>';
	} else {
		element += '<div class="text">' + _localizedStringsService.LocalizedStrings.getUI(new_var.type.toLowerCase()) + '</div>';
	}
	element += '<div class="menu">';

	for (var tm in _types.Types) {
		if (tm == _types.Types.VOID.toUpperCase()) {
			continue;
		}
		element += '<div class="item ' + (new_var.type == tm.toLowerCase() ? ' selected ' : '') + '" data-type="' + tm + '" >' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + '</div>';
	}

	for (var tm in _types.Types) {
		if (tm == _types.Types.VOID.toUpperCase()) {
			continue;
		}
		element += '<div class="item">' + '<i class="dropdown icon"></i>' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + '<div class="menu">' + '<div class="item" data-text="' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + ' [ ] " data-type="' + tm + '" data-dimensions="1">[ ]</div>' + '<div class="item" data-text="' + _localizedStringsService.LocalizedStrings.getUI('vector') + ':' + _localizedStringsService.LocalizedStrings.getUI(tm.toLowerCase()) + ' [ ] [ ] " data-type="' + tm + '" data-dimensions="2">[ ] [ ] </div>' + '</div>' + '</div>';
	}

	element += '</div></div> ';

	element += '<div class="editing_name_var"><span class="span_name_variable enable_edit_name_variable">' + new_var.name + '</span> </div>';

	element += ' <span class="character_equals"> = </span> <div class="ui div_valor_var">' + new_var.value + '</div>';

	element += ' <i class="yellow inverted icon times remove_variable"></i></div>';

	element = (0, _jquery2.default)(element);

	element.data('associatedFunction', function_obj);

	function_container.find('.variables_list_div').append(element);

	addHandlers(new_var, element, function_obj);

	renderValues(new_var, element);

	return element;
}

function updateColumnsAndRowsText(variable_container, variable_var) {
	var prev = variable_container.find('.text').text().split('[');
	if (prev.length == 2) {
		var ff = prev[0] + '[ ' + variable_var.columns + ' ] ';
		variable_container.find('.text').empty();
		variable_container.find('.text').text(ff);
	}
	if (prev.length == 3) {
		var ff = prev[0] + '[ ' + variable_var.columns + ' ] [ ' + variable_var.rows + ' ] ';
		variable_container.find('.text').empty();
		variable_container.find('.text').text(ff);
	}
}

function renderValues(new_var, variable_container) {

	var ret = "";
	var j = 0;

	if (new_var.dimensions == 0) {
		if (new_var.type == _types.Types.REAL) {
			ret += '<div class="created_div_valor_var"><span class="span_value_variable simple_var">' + new_var.value.toFixed(1) + '</span> </div> ';
		} else {
			if (new_var.type == _types.Types.BOOLEAN) {
				ret += '<div class="created_div_valor_var"><span class="span_value_variable boolean_simple_type">' + _localizedStringsService.LocalizedStrings.getUI(new_var.value) + '</span> </div> ';
			} else {
				ret += '<div class="created_div_valor_var"><span class="span_value_variable simple_var">' + new_var.value + '</span> </div> ';
			}
		}
	} else {
		ret += '<table class="tabela_var">';

		if (new_var.dimensions == 1) {
			ret += '<tr>';
			if (new_var.type == _types.Types.REAL) {
				for (var k = 0; k < new_var.columns; k++) {
					ret += '<td><span class="span_value_variable vector_var" data-index="' + k + '">' + new_var.value[k].toFixed(1) + '</span></td>';
				}
			} else {
				for (var k = 0; k < new_var.columns; k++) {
					if (new_var.type == _types.Types.BOOLEAN) {
						ret += '<td><span class="span_value_variable boolean_vector_var" data-index="' + k + '">' + _localizedStringsService.LocalizedStrings.getUI(new_var.value[k]) + '</span></td>';
					} else {
						ret += '<td><span class="span_value_variable vector_var" data-index="' + k + '">' + new_var.value[k] + '</span>' + '</td>';
					}
				}
			}

			ret += '</tr>';
			ret += '</table>';

			ret += '<div class="buttons_manage_columns"><i class="ui icon minus square outline remove_global_vector_column"></i>' + ' <i class="ui icon plus square outline add_global_vector_column"></i></div>';
		}

		if (new_var.dimensions == 2) {
			if (new_var.type == _types.Types.REAL) {
				for (var l = 0; l < new_var.rows; l++) {
					ret += '<tr>';
					for (var k = 0; k < new_var.columns; k++) {
						ret += '<td><span class="span_value_variable matrix_var" data-index="' + k + '" data-row="' + l + '">' + new_var.value[l][k].toFixed(1) + '</span>' + '</td>';
					}
					ret += '</tr>';
				}
			} else {
				for (var l = 0; l < new_var.rows; l++) {
					ret += '<tr>';
					for (var k = 0; k < new_var.columns; k++) {
						if (new_var.type == _types.Types.BOOLEAN) {
							ret += '<td><span class="span_value_variable boolean_matrix_var" data-index="' + k + '" data-row="' + l + '">' + _localizedStringsService.LocalizedStrings.getUI(new_var.value[l][k]) + '</span></td>';
						} else {
							ret += '<td><span class="span_value_variable matrix_var" data-index="' + k + '" data-row="' + l + '">' + new_var.value[l][k] + '</span></td>';
						}
					}
					ret += '</tr>';
				}
			}
			if (new_var.rows == 0) {
				ret += '<tr><td></td></tr>';
			}
			ret += '<tr><td colspan="' + new_var.columns + '" class="tr_manage_lines"><i class="ui icon minus square outline remove_global_matrix_line"></i>' + ' <i class="ui icon plus square outline add_global_matrix_line"></i></td></tr>';
			ret += '</table>';

			ret += '<div class="buttons_manage_columns"><i class="ui icon minus square outline remove_global_matrix_column"></i>' + ' <i class="ui icon plus square outline add_global_matrix_column"></i></div>';
		}
	}

	(0, _jquery2.default)(variable_container).find(".div_valor_var").html('');

	ret = (0, _jquery2.default)(ret);

	(0, _jquery2.default)(ret).find('.span_value_variable').data('associatedOject', new_var);

	(0, _jquery2.default)(ret).find(".boolean_simple_type").on('click', function (e) {
		alternateBooleanValue(new_var, this.parentNode);
	});
	(0, _jquery2.default)(ret).find(".simple_var").on('click', function (e) {
		enableValueUpdate(new_var, this.parentNode);
	});

	(0, _jquery2.default)(ret).find(".boolean_vector_var").on('click', function (e) {
		alternateBooleanVectorValue(new_var, (0, _jquery2.default)(this).data('index'), this.parentNode);
	});
	(0, _jquery2.default)(ret).find(".vector_var").on('click', function (e) {
		enableVectorValueUpdate(new_var, (0, _jquery2.default)(this).data('index'), this.parentNode);
	});
	(0, _jquery2.default)(ret).find(".remove_global_vector_column").on('click', function (e) {
		removeColumnVector(new_var);
		(0, _jquery2.default)(variable_container).find(".div_valor_var").html('');
		renderValues(new_var, variable_container);
	});
	(0, _jquery2.default)(ret).find(".add_global_vector_column").on('click', function (e) {
		addColumnVector(new_var);
		(0, _jquery2.default)(variable_container).find(".div_valor_var").html('');
		renderValues(new_var, variable_container);
	});
	(0, _jquery2.default)(ret).find(".remove_global_matrix_column").on('click', function (e) {
		removeColumnMatrix(new_var);
		(0, _jquery2.default)(variable_container).find(".div_valor_var").html('');
		renderValues(new_var, variable_container);
	});
	(0, _jquery2.default)(ret).find(".add_global_matrix_column").on('click', function (e) {
		addColumnMatrix(new_var);
		(0, _jquery2.default)(variable_container).find(".div_valor_var").html('');
		renderValues(new_var, variable_container);
	});
	(0, _jquery2.default)(ret).find(".remove_global_matrix_line").on('click', function (e) {
		removeLineMatrix(new_var);
		(0, _jquery2.default)(variable_container).find(".div_valor_var").html('');
		renderValues(new_var, variable_container);
	});
	(0, _jquery2.default)(ret).find(".add_global_matrix_line").on('click', function (e) {
		addLineMatrix(new_var);
		(0, _jquery2.default)(variable_container).find(".div_valor_var").html('');
		renderValues(new_var, variable_container);
	});
	(0, _jquery2.default)(ret).find(".boolean_matrix_var").on('click', function (e) {
		alternateBooleanMatrixValue(new_var, (0, _jquery2.default)(this).data('row'), (0, _jquery2.default)(this).data('index'), this.parentNode);
	});
	(0, _jquery2.default)(ret).find(".matrix_var").on('click', function (e) {
		enableMatrixValueUpdate(new_var, (0, _jquery2.default)(this).data('row'), (0, _jquery2.default)(this).data('index'), this.parentNode);
	});
	(0, _jquery2.default)(variable_container).find(".div_valor_var").append(ret);

	updateColumnsAndRowsText(variable_container, new_var);
}

function alternateBooleanMatrixValue(var_obj, row, index, value_container) {
	var_obj.value[row][index] = !var_obj.value[row][index];
	(0, _jquery2.default)(value_container).find('.span_value_variable').text(_localizedStringsService.LocalizedStrings.getUI(var_obj.value[row][index]));
}

function addLineMatrix(var_obj) {
	var_obj.rows++;

	if (var_obj.type == _types.Types.INTEGER) {
		var n_l = [];
		for (var i = 0; i < var_obj.columns; i++) {
			n_l.push(1);
		}
		var_obj.value.push(n_l);
	}
	if (var_obj.type == _types.Types.REAL) {
		var n_l = [];
		for (i = 0; i < var_obj.columns; i++) {
			n_l.push(1.0);
		}
		var_obj.value.push(n_l);
	}

	if (var_obj.type == _types.Types.TEXT) {
		var n_l = [];
		for (i = 0; i < var_obj.columns; i++) {
			n_l.push(_localizedStringsService.LocalizedStrings.getUI('text_start'));
		}
		var_obj.value.push(n_l);
	}

	if (var_obj.type == _types.Types.BOOLEAN) {
		var n_l = [];
		for (i = 0; i < var_obj.columns; i++) {
			n_l.push(true);
		}
		var_obj.value.push(n_l);
	}
}

function removeLineMatrix(var_obj) {
	if (var_obj.rows == 0) {
		return;
	}

	var_obj.rows--;
	var_obj.value.splice(var_obj.value.length - 1, 1);
}

function addColumnMatrix(var_obj) {
	var_obj.columns++;

	if (var_obj.type == _types.Types.INTEGER) {
		for (var i = 0; i < var_obj.rows; i++) {
			var_obj.value[i].push(1);
		}
	}
	if (var_obj.type == _types.Types.REAL) {
		for (var i = 0; i < var_obj.rows; i++) {
			var_obj.value[i].push(1.0);
		}
	}
	if (var_obj.type == _types.Types.TEXT) {
		for (var i = 0; i < var_obj.rows; i++) {
			var_obj.value[i].push(_localizedStringsService.LocalizedStrings.getUI('text_start'));
		}
	}
	if (var_obj.type == _types.Types.BOOLEAN) {
		for (var i = 0; i < var_obj.rows; i++) {
			var_obj.value[i].push(true);
		}
	}
}

function removeColumnMatrix(var_obj) {
	if (var_obj.columns == 0) {
		return;
	}

	var_obj.columns--;

	for (var i = 0; i < var_obj.rows; i++) {
		var_obj.value[i].splice(var_obj.value[i].length - 1, 1);
	}
}

function addColumnVector(var_obj) {
	var_obj.columns++;

	if (var_obj.type == _types.Types.INTEGER) {
		var_obj.value.push(1);
	}
	if (var_obj.type == _types.Types.REAL) {
		var_obj.value.push(1.0);
	}
	if (var_obj.type == _types.Types.TEXT) {
		var_obj.value.push(_localizedStringsService.LocalizedStrings.getUI('text_start'));
	}
	if (var_obj.type == _types.Types.BOOLEAN) {
		var_obj.value.push(true);
	}
}

function removeColumnVector(var_obj) {
	if (var_obj.columns == 0) {
		return;
	}

	var_obj.columns--;
	var_obj.value.splice(var_obj.value.length - 1, 1);
}

function alternateBooleanValue(var_obj, value_container) {
	var_obj.value = !var_obj.value;
	(0, _jquery2.default)(value_container).find('.span_value_variable').text(_localizedStringsService.LocalizedStrings.getUI(var_obj.value));
}

function alternateBooleanVectorValue(var_obj, index, value_container) {
	var_obj.value[index] = !var_obj.value[index];
	(0, _jquery2.default)(value_container).find('.span_value_variable').text(_localizedStringsService.LocalizedStrings.getUI(var_obj.value[index]));
}

function updateInitialValues(variable_obj) {
	if (variable_obj.type == _types.Types.INTEGER) {
		if (variable_obj.dimensions == 0) {
			variable_obj.value = 1;
		}
		if (variable_obj.dimensions == 1) {
			variable_obj.value = [1, 1];
		}
		if (variable_obj.dimensions == 2) {
			variable_obj.value = [[1, 1], [1, 1]];
		}
	}

	if (variable_obj.type == _types.Types.REAL) {
		if (variable_obj.dimensions == 0) {
			variable_obj.value = 1.0;
		}
		if (variable_obj.dimensions == 1) {
			variable_obj.value = [1.0, 1.0];
		}
		if (variable_obj.dimensions == 2) {
			variable_obj.value = [[1.0, 1.0], [1.0, 1.0]];
		}
	}

	if (variable_obj.type == _types.Types.TEXT) {
		if (variable_obj.dimensions == 0) {
			variable_obj.value = _localizedStringsService.LocalizedStrings.getUI('text_start');
		}
		if (variable_obj.dimensions == 1) {
			variable_obj.value = [_localizedStringsService.LocalizedStrings.getUI('text_start'), _localizedStringsService.LocalizedStrings.getUI('text_start')];
		}
		if (variable_obj.dimensions == 2) {
			variable_obj.value = [[_localizedStringsService.LocalizedStrings.getUI('text_start'), _localizedStringsService.LocalizedStrings.getUI('text_start')], [_localizedStringsService.LocalizedStrings.getUI('text_start'), _localizedStringsService.LocalizedStrings.getUI('text_start')]];
		}
	}

	if (variable_obj.type == _types.Types.BOOLEAN) {
		if (variable_obj.dimensions == 0) {
			variable_obj.value = true;
		}
		if (variable_obj.dimensions == 1) {
			variable_obj.value = [true, true];
		}
		if (variable_obj.dimensions == 2) {
			variable_obj.value = [[true, true], [true, true]];
		}
	}
}

var opened_name_value_vector_global_ = false;
var opened_input_value_vector_global_ = null;
function enableVectorValueUpdate(var_obj, index, parent_node) {
	if (opened_name_value_vector_global_) {
		opened_input_value_vector_global_.focus();
		return;
	}
	parent_node = (0, _jquery2.default)(parent_node);
	opened_name_value_vector_global_ = true;

	parent_node.find('.span_value_variable').text('');

	var input_field;

	if (var_obj.type == _types.Types.REAL) {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + var_obj.value[index].toFixed(1) + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	} else {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + var_obj.value[index] + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	}

	input_field.on('input', function () {
		var inputWidth = input_field.textWidth() + 10;
		opened_input_value_vector_global_ = input_field;
		input_field.focus();

		var tmpStr = input_field.val();
		input_field.val('');
		input_field.val(tmpStr);

		input_field.css({
			width: inputWidth
		});
	}).trigger('input');

	input_field.focusout(function () {
		/// update array:
		if (input_field.val().trim()) {
			if (var_obj.type == _types.Types.REAL) {
				var_obj.value[index] = parseFloat(input_field.val().trim());

				parent_node.find('.span_value_variable').text(var_obj.value[index].toFixed(1));
			} else {

				if (var_obj.type == _types.Types.INTEGER) {
					var_obj.value[index] = parseInt(input_field.val().trim());
				} else {
					var_obj.value[index] = input_field.val().trim();
				}

				parent_node.find('.span_value_variable').text(var_obj.value[index]);
			}
		} else {
			if (var_obj.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(var_obj.value[index].toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(var_obj.value[index]);
			}
		}
		if (var_obj.type == _types.Types.TEXT) {
			var_obj.value[index] = input_field.val();
			parent_node.find('.span_value_variable').text(var_obj.value[index]);
		}
		input_field.off();
		input_field.remove();

		/// update elements:
		opened_name_value_vector_global_ = false;
		opened_input_value_vector_global_ = false;
	});

	input_field.on('keydown', function (e) {
		var code = e.keyCode || e.which;
		if (code == 13) {
			if (input_field.val().trim()) {
				if (var_obj.type == _types.Types.REAL) {
					var_obj.value[index] = parseFloat(input_field.val().trim());

					parent_node.find('.span_value_variable').text(var_obj.value[index].toFixed(1));
				} else {

					if (var_obj.type == _types.Types.INTEGER) {
						var_obj.value[index] = parseInt(input_field.val().trim());
					} else {
						var_obj.value[index] = input_field.val().trim();
					}

					parent_node.find('.span_value_variable').text(var_obj.value[index]);
				}
			} else {
				if (var_obj.type == _types.Types.REAL) {
					parent_node.find('.span_value_variable').text(var_obj.value[index].toFixed(1));
				} else {
					parent_node.find('.span_value_variable').text(var_obj.value[index]);
				}
			}
			if (var_obj.type == _types.Types.TEXT) {
				var_obj.value[index] = input_field.val();
				parent_node.find('.span_value_variable').text(var_obj.value[index]);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_vector_global_ = false;
			opened_input_value_vector_global_ = false;
		}
		if (code == 27) {
			if (var_obj.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(var_obj.value[index].toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(var_obj.value[index]);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_vector_global_ = false;
			opened_input_value_vector_global_ = false;
		}
	});

	input_field.select();
}

var opened_name_value_global_var = false;
var opened_input_value_global_ar = null;
function enableValueUpdate(var_obj, parent_node) {
	if (opened_name_value_global_var) {
		opened_input_value_global_ar.focus();
		return;
	}
	parent_node = (0, _jquery2.default)(parent_node);
	opened_name_value_global_var = true;

	var input_field;

	parent_node.find('.span_value_variable').text('');
	if (var_obj.type == _types.Types.REAL) {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + var_obj.value.toFixed(1) + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	} else {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + var_obj.value + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	}

	input_field.on('input', function () {
		var inputWidth = input_field.textWidth() + 10;
		opened_input_value_global_ar = input_field;
		input_field.focus();

		var tmpStr = input_field.val();
		input_field.val('');
		input_field.val(tmpStr);

		input_field.css({
			width: inputWidth
		});
	}).trigger('input');

	input_field.focusout(function () {
		/// update array:
		if (input_field.val().trim()) {
			if (var_obj.type == _types.Types.REAL) {
				var_obj.value = parseFloat(input_field.val().trim());
				parent_node.find('.span_value_variable').text(var_obj.value.toFixed(1));
			} else {
				if (var_obj.type == _types.Types.INTEGER) {
					var_obj.value = parseInt(input_field.val().trim());
				} else {
					var_obj.value = input_field.val().trim();
				}
				parent_node.find('.span_value_variable').text(var_obj.value);
			}
		} else {
			if (var_obj.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(var_obj.value.toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(var_obj.value);
			}
		}
		if (var_obj.type == _types.Types.TEXT) {
			var_obj.value = input_field.val();
			parent_node.find('.span_value_variable').text(var_obj.value);
		}
		input_field.off();
		input_field.remove();

		/// update elements:
		opened_name_value_global_var = false;
		opened_input_value_global_ar = false;
	});

	input_field.on('keydown', function (e) {
		var code = e.keyCode || e.which;
		if (code == 13) {
			if (input_field.val().trim()) {
				if (var_obj.type == _types.Types.REAL) {
					var_obj.value = parseFloat(input_field.val().trim());
					parent_node.find('.span_value_variable').text(var_obj.value.toFixed(1));
				} else {
					if (var_obj.type == _types.Types.INTEGER) {
						var_obj.value = parseInt(input_field.val().trim());
					} else {
						var_obj.value = input_field.val().trim();
					}
					parent_node.find('.span_value_variable').text(var_obj.value);
				}
			} else {
				if (var_obj.type == _types.Types.REAL) {
					parent_node.find('.span_value_variable').text(var_obj.value.toFixed(1));
				} else {
					parent_node.find('.span_value_variable').text(var_obj.value);
				}
			}
			if (var_obj.type == _types.Types.TEXT) {
				var_obj.value = input_field.val();
				parent_node.find('.span_value_variable').text(var_obj.value);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_global_var = false;
			opened_input_value_global_ar = false;
		}
		if (code == 27) {
			if (var_obj.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(var_obj.value.toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(var_obj.value);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_global_var = false;
			opened_input_value_global_ar = false;
		}
	});

	input_field.select();
}

var opened_name_global = false;
var opened_input_global = null;
function enableNameUpdate(variable_obj, variable_container, function_obj) {

	if (opened_name_global) {
		opened_input_global.focus();
		return;
	}
	opened_name_global = true;

	variable_container.find('.span_name_variable').text('');

	var input_name;

	input_name = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + variable_obj.name + "' />");
	input_name.insertBefore(variable_container.find('.span_name_variable'));

	input_name.on('input', function () {
		var inputWidth = input_name.textWidth() + 10;
		opened_input_global = input_name;
		input_name.focus();

		var tmpStr = input_name.val();
		input_name.val('');
		input_name.val(tmpStr);

		input_name.css({
			width: inputWidth
		});
	}).trigger('input');

	input_name.focusout(function () {
		/// update array:
		if (input_name.val().trim().length > 0) {
			updateName(variable_obj, input_name.val().trim(), variable_container, function_obj);
			variable_container.find('.span_name_variable').text(variable_obj.name);
		} else {
			variable_container.find('.span_name_variable').text(variable_obj.name);
		}
		input_name.off();
		input_name.remove();

		/// update elements:
		opened_name_global = false;
		opened_input_global = false;
	});

	input_name.on('keydown', function (e) {
		var code = e.keyCode || e.which;
		if (code == 13) {
			if (input_name.val().trim().length > 0) {
				updateName(variable_obj, input_name.val().trim(), variable_container, function_obj);
				variable_container.find('.span_name_variable').text(variable_obj.name);
			} else {
				variable_container.find('.span_name_variable').text(variable_obj.name);
			}
			input_name.off();
			input_name.remove();

			/// update elements:
			opened_name_global = false;
			opened_input_global = false;
		}
		if (code == 27) {

			variable_container.find('.span_name_variable').text(variable_obj.name);
			input_name.off();
			input_name.remove();

			/// update elements:
			opened_name_global = false;
			opened_input_global = false;
		}
	});

	input_name.select();
}

var opened_name_value_matrix_global_v = false;
var opened_input_value_matrix_global_v = null;
function enableMatrixValueUpdate(var_obj, row, index, parent_node) {
	if (opened_name_value_matrix_global_v) {
		opened_input_value_matrix_global_v.focus();
		return;
	}
	parent_node = (0, _jquery2.default)(parent_node);
	opened_name_value_matrix_global_v = true;

	parent_node.find('.span_value_variable').text('');

	var input_field;

	if (var_obj.type == _types.Types.REAL) {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + var_obj.value[row][index].toFixed(1) + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	} else {
		input_field = (0, _jquery2.default)("<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='" + var_obj.value[row][index] + "' />");
		input_field.insertBefore(parent_node.find('.span_value_variable'));
	}

	input_field.on('input', function () {
		var inputWidth = input_field.textWidth() + 10;
		opened_input_value_matrix_global_v = input_field;
		input_field.focus();

		var tmpStr = input_field.val();
		input_field.val('');
		input_field.val(tmpStr);

		input_field.css({
			width: inputWidth
		});
	}).trigger('input');

	input_field.focusout(function () {
		/// update array:
		if (input_field.val().trim()) {
			if (var_obj.type == _types.Types.REAL) {
				var_obj.value[row][index] = parseFloat(input_field.val().trim());

				parent_node.find('.span_value_variable').text(var_obj.value[row][index].toFixed(1));
			} else {
				if (var_obj.type == _types.Types.INTEGER) {
					var_obj.value[row][index] = parseInt(input_field.val().trim());
				} else {
					var_obj.value[row][index] = input_field.val().trim();
				}
				parent_node.find('.span_value_variable').text(var_obj.value[row][index]);
			}
		} else {
			if (var_obj.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(var_obj.value[row][index].toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(var_obj.value[row][index]);
			}
		}
		if (var_obj.type == _types.Types.TEXT) {
			var_obj.value[row][index] = input_field.val();
			parent_node.find('.span_value_variable').text(var_obj.value[row][index]);
		}
		input_field.off();
		input_field.remove();

		/// update elements:
		opened_name_value_matrix_global_v = false;
		opened_input_value_matrix_global_v = false;
	});

	input_field.on('keydown', function (e) {
		var code = e.keyCode || e.which;
		if (code == 13) {
			if (input_field.val().trim()) {
				if (var_obj.type == _types.Types.REAL) {
					var_obj.value[row][index] = parseFloat(input_field.val().trim());

					parent_node.find('.span_value_variable').text(var_obj.value[row][index].toFixed(1));
				} else {
					if (var_obj.type == _types.Types.INTEGER) {
						var_obj.value[row][index] = parseInt(input_field.val().trim());
					} else {
						var_obj.value[row][index] = input_field.val().trim();
					}
					parent_node.find('.span_value_variable').text(var_obj.value[row][index]);
				}
			} else {
				if (var_obj.type == _types.Types.REAL) {
					parent_node.find('.span_value_variable').text(var_obj.value[row][index].toFixed(1));
				} else {
					parent_node.find('.span_value_variable').text(var_obj.value[row][index]);
				}
			}
			if (var_obj.type == _types.Types.TEXT) {
				var_obj.value[row][index] = input_field.val();
				parent_node.find('.span_value_variable').text(var_obj.value[row][index]);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_matrix_global_v = false;
			opened_input_value_matrix_global_v = false;
		}
		if (code == 27) {
			if (var_obj.type == _types.Types.REAL) {
				parent_node.find('.span_value_variable').text(var_obj.value[row][index].toFixed(1));
			} else {
				parent_node.find('.span_value_variable').text(var_obj.value[row][index]);
			}
			input_field.off();
			input_field.remove();

			/// update elements:
			opened_name_value_matrix_global_v = false;
			opened_input_value_matrix_global_v = false;
		}
	});

	input_field.select();
}

/***/ }),

/***/ "./node_modules/antlr4/BufferedTokenStream.js":
/*!****************************************************!*\
  !*** ./node_modules/antlr4/BufferedTokenStream.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

// This implementation of {@link TokenStream} loads tokens from a
// {@link TokenSource} on-demand, and places the tokens in a buffer to provide
// access to any previous token by index.
//
// <p>
// This token stream ignores the value of {@link Token//getChannel}. If your
// parser requires the token stream filter tokens to only those on a particular
// channel, such as {@link Token//DEFAULT_CHANNEL} or
// {@link Token//HIDDEN_CHANNEL}, use a filtering token stream such a
// {@link CommonTokenStream}.</p>

var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
var Lexer = __webpack_require__(/*! ./Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
var Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;

// this is just to keep meaningful parameter types to Parser
function TokenStream() {
	return this;
}

function BufferedTokenStream(tokenSource) {

	TokenStream.call(this);
	// The {@link TokenSource} from which tokens for this stream are fetched.
	this.tokenSource = tokenSource;

	// A collection of all tokens fetched from the token source. The list is
	// considered a complete view of the input once {@link //fetchedEOF} is set
	// to {@code true}.
	this.tokens = [];

	// The index into {@link //tokens} of the current token (next token to
	// {@link //consume}). {@link //tokens}{@code [}{@link //p}{@code ]} should
	// be
	// {@link //LT LT(1)}.
	//
	// <p>This field is set to -1 when the stream is first constructed or when
	// {@link //setTokenSource} is called, indicating that the first token has
	// not yet been fetched from the token source. For additional information,
	// see the documentation of {@link IntStream} for a description of
	// Initializing Methods.</p>
	this.index = -1;

	// Indicates whether the {@link Token//EOF} token has been fetched from
	// {@link //tokenSource} and added to {@link //tokens}. This field improves
	// performance for the following cases:
	//
	// <ul>
	// <li>{@link //consume}: The lookahead check in {@link //consume} to
	// prevent
	// consuming the EOF symbol is optimized by checking the values of
	// {@link //fetchedEOF} and {@link //p} instead of calling {@link
	// //LA}.</li>
	// <li>{@link //fetch}: The check to prevent adding multiple EOF symbols
	// into
	// {@link //tokens} is trivial with this field.</li>
	// <ul>
	this.fetchedEOF = false;
	return this;
}

BufferedTokenStream.prototype = Object.create(TokenStream.prototype);
BufferedTokenStream.prototype.constructor = BufferedTokenStream;

BufferedTokenStream.prototype.mark = function () {
	return 0;
};

BufferedTokenStream.prototype.release = function (marker) {
	// no resources to release
};

BufferedTokenStream.prototype.reset = function () {
	this.seek(0);
};

BufferedTokenStream.prototype.seek = function (index) {
	this.lazyInit();
	this.index = this.adjustSeekIndex(index);
};

BufferedTokenStream.prototype.get = function (index) {
	this.lazyInit();
	return this.tokens[index];
};

BufferedTokenStream.prototype.consume = function () {
	var skipEofCheck = false;
	if (this.index >= 0) {
		if (this.fetchedEOF) {
			// the last token in tokens is EOF. skip check if p indexes any
			// fetched token except the last.
			skipEofCheck = this.index < this.tokens.length - 1;
		} else {
			// no EOF token in tokens. skip check if p indexes a fetched token.
			skipEofCheck = this.index < this.tokens.length;
		}
	} else {
		// not yet initialized
		skipEofCheck = false;
	}
	if (!skipEofCheck && this.LA(1) === Token.EOF) {
		throw "cannot consume EOF";
	}
	if (this.sync(this.index + 1)) {
		this.index = this.adjustSeekIndex(this.index + 1);
	}
};

// Make sure index {@code i} in tokens has a token.
//
// @return {@code true} if a token is located at index {@code i}, otherwise
// {@code false}.
// @see //get(int i)
// /
BufferedTokenStream.prototype.sync = function (i) {
	var n = i - this.tokens.length + 1; // how many more elements we need?
	if (n > 0) {
		var fetched = this.fetch(n);
		return fetched >= n;
	}
	return true;
};

// Add {@code n} elements to buffer.
//
// @return The actual number of elements added to the buffer.
// /
BufferedTokenStream.prototype.fetch = function (n) {
	if (this.fetchedEOF) {
		return 0;
	}
	for (var i = 0; i < n; i++) {
		var t = this.tokenSource.nextToken();
		t.tokenIndex = this.tokens.length;
		this.tokens.push(t);
		if (t.type === Token.EOF) {
			this.fetchedEOF = true;
			return i + 1;
		}
	}
	return n;
};

// Get all tokens from start..stop inclusively///
BufferedTokenStream.prototype.getTokens = function (start, stop, types) {
	if (types === undefined) {
		types = null;
	}
	if (start < 0 || stop < 0) {
		return null;
	}
	this.lazyInit();
	var subset = [];
	if (stop >= this.tokens.length) {
		stop = this.tokens.length - 1;
	}
	for (var i = start; i < stop; i++) {
		var t = this.tokens[i];
		if (t.type === Token.EOF) {
			break;
		}
		if (types === null || types.contains(t.type)) {
			subset.push(t);
		}
	}
	return subset;
};

BufferedTokenStream.prototype.LA = function (i) {
	return this.LT(i).type;
};

BufferedTokenStream.prototype.LB = function (k) {
	if (this.index - k < 0) {
		return null;
	}
	return this.tokens[this.index - k];
};

BufferedTokenStream.prototype.LT = function (k) {
	this.lazyInit();
	if (k === 0) {
		return null;
	}
	if (k < 0) {
		return this.LB(-k);
	}
	var i = this.index + k - 1;
	this.sync(i);
	if (i >= this.tokens.length) {
		// return EOF token
		// EOF must be last token
		return this.tokens[this.tokens.length - 1];
	}
	return this.tokens[i];
};

// Allowed derived classes to modify the behavior of operations which change
// the current stream position by adjusting the target token index of a seek
// operation. The default implementation simply returns {@code i}. If an
// exception is thrown in this method, the current stream index should not be
// changed.
//
// <p>For example, {@link CommonTokenStream} overrides this method to ensure
// that
// the seek target is always an on-channel token.</p>
//
// @param i The target token index.
// @return The adjusted target token index.

BufferedTokenStream.prototype.adjustSeekIndex = function (i) {
	return i;
};

BufferedTokenStream.prototype.lazyInit = function () {
	if (this.index === -1) {
		this.setup();
	}
};

BufferedTokenStream.prototype.setup = function () {
	this.sync(0);
	this.index = this.adjustSeekIndex(0);
};

// Reset this token stream by setting its token source.///
BufferedTokenStream.prototype.setTokenSource = function (tokenSource) {
	this.tokenSource = tokenSource;
	this.tokens = [];
	this.index = -1;
	this.fetchedEOF = false;
};

// Given a starting index, return the index of the next token on channel.
// Return i if tokens[i] is on channel. Return -1 if there are no tokens
// on channel between i and EOF.
// /
BufferedTokenStream.prototype.nextTokenOnChannel = function (i, channel) {
	this.sync(i);
	if (i >= this.tokens.length) {
		return -1;
	}
	var token = this.tokens[i];
	while (token.channel !== this.channel) {
		if (token.type === Token.EOF) {
			return -1;
		}
		i += 1;
		this.sync(i);
		token = this.tokens[i];
	}
	return i;
};

// Given a starting index, return the index of the previous token on channel.
// Return i if tokens[i] is on channel. Return -1 if there are no tokens
// on channel between i and 0.
BufferedTokenStream.prototype.previousTokenOnChannel = function (i, channel) {
	while (i >= 0 && this.tokens[i].channel !== channel) {
		i -= 1;
	}
	return i;
};

// Collect all tokens on specified channel to the right of
// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or
// EOF. If channel is -1, find any non default channel token.
BufferedTokenStream.prototype.getHiddenTokensToRight = function (tokenIndex, channel) {
	if (channel === undefined) {
		channel = -1;
	}
	this.lazyInit();
	if (tokenIndex < 0 || tokenIndex >= this.tokens.length) {
		throw "" + tokenIndex + " not in 0.." + this.tokens.length - 1;
	}
	var nextOnChannel = this.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL);
	var from_ = tokenIndex + 1;
	// if none onchannel to right, nextOnChannel=-1 so set to = last token
	var to = nextOnChannel === -1 ? this.tokens.length - 1 : nextOnChannel;
	return this.filterForChannel(from_, to, channel);
};

// Collect all tokens on specified channel to the left of
// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.
// If channel is -1, find any non default channel token.
BufferedTokenStream.prototype.getHiddenTokensToLeft = function (tokenIndex, channel) {
	if (channel === undefined) {
		channel = -1;
	}
	this.lazyInit();
	if (tokenIndex < 0 || tokenIndex >= this.tokens.length) {
		throw "" + tokenIndex + " not in 0.." + this.tokens.length - 1;
	}
	var prevOnChannel = this.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL);
	if (prevOnChannel === tokenIndex - 1) {
		return null;
	}
	// if none on channel to left, prevOnChannel=-1 then from=0
	var from_ = prevOnChannel + 1;
	var to = tokenIndex - 1;
	return this.filterForChannel(from_, to, channel);
};

BufferedTokenStream.prototype.filterForChannel = function (left, right, channel) {
	var hidden = [];
	for (var i = left; i < right + 1; i++) {
		var t = this.tokens[i];
		if (channel === -1) {
			if (t.channel !== Lexer.DEFAULT_TOKEN_CHANNEL) {
				hidden.push(t);
			}
		} else if (t.channel === channel) {
			hidden.push(t);
		}
	}
	if (hidden.length === 0) {
		return null;
	}
	return hidden;
};

BufferedTokenStream.prototype.getSourceName = function () {
	return this.tokenSource.getSourceName();
};

// Get the text of all tokens in this buffer.///
BufferedTokenStream.prototype.getText = function (interval) {
	this.lazyInit();
	this.fill();
	if (interval === undefined || interval === null) {
		interval = new Interval(0, this.tokens.length - 1);
	}
	var start = interval.start;
	if (start instanceof Token) {
		start = start.tokenIndex;
	}
	var stop = interval.stop;
	if (stop instanceof Token) {
		stop = stop.tokenIndex;
	}
	if (start === null || stop === null || start < 0 || stop < 0) {
		return "";
	}
	if (stop >= this.tokens.length) {
		stop = this.tokens.length - 1;
	}
	var s = "";
	for (var i = start; i < stop + 1; i++) {
		var t = this.tokens[i];
		if (t.type === Token.EOF) {
			break;
		}
		s = s + t.text;
	}
	return s;
};

// Get all tokens from lexer until EOF///
BufferedTokenStream.prototype.fill = function () {
	this.lazyInit();
	while (this.fetch(1000) === 1000) {
		continue;
	}
};

exports.BufferedTokenStream = BufferedTokenStream;

/***/ }),

/***/ "./node_modules/antlr4/CharStreams.js":
/*!********************************************!*\
  !*** ./node_modules/antlr4/CharStreams.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

var InputStream = __webpack_require__(/*! ./InputStream */ "./node_modules/antlr4/InputStream.js").InputStream;

var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined';
var fs = isNodeJs ? __webpack_require__(/*! fs */ "./node_modules/node-libs-browser/mock/empty.js") : null;

// Utility functions to create InputStreams from various sources.
//
// All returned InputStreams support the full range of Unicode
// up to U+10FFFF (the default behavior of InputStream only supports
// code points up to U+FFFF).
var CharStreams = {
  // Creates an InputStream from a string.
  fromString: function fromString(str) {
    return new InputStream(str, true);
  },

  // Asynchronously creates an InputStream from a blob given the
  // encoding of the bytes in that blob (defaults to 'utf8' if
  // encoding is null).
  //
  // Invokes onLoad(result) on success, onError(error) on
  // failure.
  fromBlob: function fromBlob(blob, encoding, onLoad, onError) {
    var reader = FileReader();
    reader.onload = function (e) {
      var is = new InputStream(e.target.result, true);
      onLoad(is);
    };
    reader.onerror = onError;
    reader.readAsText(blob, encoding);
  },

  // Creates an InputStream from a Buffer given the
  // encoding of the bytes in that buffer (defaults to 'utf8' if
  // encoding is null).
  fromBuffer: function fromBuffer(buffer, encoding) {
    return new InputStream(buffer.toString(encoding), true);
  },

  // Asynchronously creates an InputStream from a file on disk given
  // the encoding of the bytes in that file (defaults to 'utf8' if
  // encoding is null).
  //
  // Invokes callback(error, result) on completion.
  fromPath: function fromPath(path, encoding, callback) {
    fs.readFile(path, encoding, function (err, data) {
      var is = null;
      if (data !== null) {
        is = new InputStream(data, true);
      }
      callback(err, is);
    });
  },

  // Synchronously creates an InputStream given a path to a file
  // on disk and the encoding of the bytes in that file (defaults to
  // 'utf8' if encoding is null).
  fromPathSync: function fromPathSync(path, encoding) {
    var data = fs.readFileSync(path, encoding);
    return new InputStream(data, true);
  }
};

exports.CharStreams = CharStreams;

/***/ }),

/***/ "./node_modules/antlr4/CommonTokenFactory.js":
/*!***************************************************!*\
  !*** ./node_modules/antlr4/CommonTokenFactory.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

//
// This default implementation of {@link TokenFactory} creates
// {@link CommonToken} objects.
//

var CommonToken = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").CommonToken;

function TokenFactory() {
    return this;
}

function CommonTokenFactory(copyText) {
    TokenFactory.call(this);
    // Indicates whether {@link CommonToken//setText} should be called after
    // constructing tokens to explicitly set the text. This is useful for cases
    // where the input stream might not be able to provide arbitrary substrings
    // of text from the input after the lexer creates a token (e.g. the
    // implementation of {@link CharStream//getText} in
    // {@link UnbufferedCharStream} throws an
    // {@link UnsupportedOperationException}). Explicitly setting the token text
    // allows {@link Token//getText} to be called at any time regardless of the
    // input stream implementation.
    //
    // <p>
    // The default value is {@code false} to avoid the performance and memory
    // overhead of copying text for every token unless explicitly requested.</p>
    //
    this.copyText = copyText === undefined ? false : copyText;
    return this;
}

CommonTokenFactory.prototype = Object.create(TokenFactory.prototype);
CommonTokenFactory.prototype.constructor = CommonTokenFactory;

//
// The default {@link CommonTokenFactory} instance.
//
// <p>
// This token factory does not explicitly copy token text when constructing
// tokens.</p>
//
CommonTokenFactory.DEFAULT = new CommonTokenFactory();

CommonTokenFactory.prototype.create = function (source, type, text, channel, start, stop, line, column) {
    var t = new CommonToken(source, type, channel, start, stop);
    t.line = line;
    t.column = column;
    if (text !== null) {
        t.text = text;
    } else if (this.copyText && source[1] !== null) {
        t.text = source[1].getText(start, stop);
    }
    return t;
};

CommonTokenFactory.prototype.createThin = function (type, text) {
    var t = new CommonToken(null, type);
    t.text = text;
    return t;
};

exports.CommonTokenFactory = CommonTokenFactory;

/***/ }),

/***/ "./node_modules/antlr4/CommonTokenStream.js":
/*!**************************************************!*\
  !*** ./node_modules/antlr4/CommonTokenStream.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

//
// This class extends {@link BufferedTokenStream} with functionality to filter
// token streams to tokens on a particular channel (tokens where
// {@link Token//getChannel} returns a particular value).
//
// <p>
// This token stream provides access to all tokens by index or when calling
// methods like {@link //getText}. The channel filtering is only used for code
// accessing tokens via the lookahead methods {@link //LA}, {@link //LT}, and
// {@link //LB}.</p>
//
// <p>
// By default, tokens are placed on the default channel
// ({@link Token//DEFAULT_CHANNEL}), but may be reassigned by using the
// {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to
// call {@link Lexer//setChannel}.
// </p>
//
// <p>
// Note: lexer rules which use the {@code ->skip} lexer command or call
// {@link Lexer//skip} do not produce tokens at all, so input text matched by
// such a rule will not be available as part of the token stream, regardless of
// channel.</p>
///

var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
var BufferedTokenStream = __webpack_require__(/*! ./BufferedTokenStream */ "./node_modules/antlr4/BufferedTokenStream.js").BufferedTokenStream;

function CommonTokenStream(lexer, channel) {
    BufferedTokenStream.call(this, lexer);
    this.channel = channel === undefined ? Token.DEFAULT_CHANNEL : channel;
    return this;
}

CommonTokenStream.prototype = Object.create(BufferedTokenStream.prototype);
CommonTokenStream.prototype.constructor = CommonTokenStream;

CommonTokenStream.prototype.adjustSeekIndex = function (i) {
    return this.nextTokenOnChannel(i, this.channel);
};

CommonTokenStream.prototype.LB = function (k) {
    if (k === 0 || this.index - k < 0) {
        return null;
    }
    var i = this.index;
    var n = 1;
    // find k good tokens looking backwards
    while (n <= k) {
        // skip off-channel tokens
        i = this.previousTokenOnChannel(i - 1, this.channel);
        n += 1;
    }
    if (i < 0) {
        return null;
    }
    return this.tokens[i];
};

CommonTokenStream.prototype.LT = function (k) {
    this.lazyInit();
    if (k === 0) {
        return null;
    }
    if (k < 0) {
        return this.LB(-k);
    }
    var i = this.index;
    var n = 1; // we know tokens[pos] is a good one
    // find k good tokens
    while (n < k) {
        // skip off-channel tokens, but make sure to not look past EOF
        if (this.sync(i + 1)) {
            i = this.nextTokenOnChannel(i + 1, this.channel);
        }
        n += 1;
    }
    return this.tokens[i];
};

// Count EOF just once.///
CommonTokenStream.prototype.getNumberOfOnChannelTokens = function () {
    var n = 0;
    this.fill();
    for (var i = 0; i < this.tokens.length; i++) {
        var t = this.tokens[i];
        if (t.channel === this.channel) {
            n += 1;
        }
        if (t.type === Token.EOF) {
            break;
        }
    }
    return n;
};

exports.CommonTokenStream = CommonTokenStream;

/***/ }),

/***/ "./node_modules/antlr4/FileStream.js":
/*!*******************************************!*\
  !*** ./node_modules/antlr4/FileStream.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

//
//  This is an InputStream that is loaded from a file all at once
//  when you construct the object.
//
var InputStream = __webpack_require__(/*! ./InputStream */ "./node_modules/antlr4/InputStream.js").InputStream;
var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined';
var fs = isNodeJs ? __webpack_require__(/*! fs */ "./node_modules/node-libs-browser/mock/empty.js") : null;

function FileStream(fileName, decodeToUnicodeCodePoints) {
	var data = fs.readFileSync(fileName, "utf8");
	InputStream.call(this, data, decodeToUnicodeCodePoints);
	this.fileName = fileName;
	return this;
}

FileStream.prototype = Object.create(InputStream.prototype);
FileStream.prototype.constructor = FileStream;

exports.FileStream = FileStream;

/***/ }),

/***/ "./node_modules/antlr4/InputStream.js":
/*!********************************************!*\
  !*** ./node_modules/antlr4/InputStream.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
__webpack_require__(/*! ./polyfills/codepointat */ "./node_modules/antlr4/polyfills/codepointat.js");
__webpack_require__(/*! ./polyfills/fromcodepoint */ "./node_modules/antlr4/polyfills/fromcodepoint.js");

// Vacuum all input from a string and then treat it like a buffer.

function _loadString(stream, decodeToUnicodeCodePoints) {
	stream._index = 0;
	stream.data = [];
	if (stream.decodeToUnicodeCodePoints) {
		for (var i = 0; i < stream.strdata.length;) {
			var codePoint = stream.strdata.codePointAt(i);
			stream.data.push(codePoint);
			i += codePoint <= 0xFFFF ? 1 : 2;
		}
	} else {
		for (var i = 0; i < stream.strdata.length; i++) {
			var codeUnit = stream.strdata.charCodeAt(i);
			stream.data.push(codeUnit);
		}
	}
	stream._size = stream.data.length;
}

// If decodeToUnicodeCodePoints is true, the input is treated
// as a series of Unicode code points.
//
// Otherwise, the input is treated as a series of 16-bit UTF-16 code
// units.
function InputStream(data, decodeToUnicodeCodePoints) {
	this.name = "<empty>";
	this.strdata = data;
	this.decodeToUnicodeCodePoints = decodeToUnicodeCodePoints || false;
	_loadString(this);
	return this;
}

Object.defineProperty(InputStream.prototype, "index", {
	get: function get() {
		return this._index;
	}
});

Object.defineProperty(InputStream.prototype, "size", {
	get: function get() {
		return this._size;
	}
});

// Reset the stream so that it's in the same state it was
// when the object was created *except* the data array is not
// touched.
//
InputStream.prototype.reset = function () {
	this._index = 0;
};

InputStream.prototype.consume = function () {
	if (this._index >= this._size) {
		// assert this.LA(1) == Token.EOF
		throw "cannot consume EOF";
	}
	this._index += 1;
};

InputStream.prototype.LA = function (offset) {
	if (offset === 0) {
		return 0; // undefined
	}
	if (offset < 0) {
		offset += 1; // e.g., translate LA(-1) to use offset=0
	}
	var pos = this._index + offset - 1;
	if (pos < 0 || pos >= this._size) {
		// invalid
		return Token.EOF;
	}
	return this.data[pos];
};

InputStream.prototype.LT = function (offset) {
	return this.LA(offset);
};

// mark/release do nothing; we have entire buffer
InputStream.prototype.mark = function () {
	return -1;
};

InputStream.prototype.release = function (marker) {};

// consume() ahead until p==_index; can't just set p=_index as we must
// update line and column. If we seek backwards, just set p
//
InputStream.prototype.seek = function (_index) {
	if (_index <= this._index) {
		this._index = _index; // just jump; don't update stream state (line,
		// ...)
		return;
	}
	// seek forward
	this._index = Math.min(_index, this._size);
};

InputStream.prototype.getText = function (start, stop) {
	if (stop >= this._size) {
		stop = this._size - 1;
	}
	if (start >= this._size) {
		return "";
	} else {
		if (this.decodeToUnicodeCodePoints) {
			var result = "";
			for (var i = start; i <= stop; i++) {
				result += String.fromCodePoint(this.data[i]);
			}
			return result;
		} else {
			return this.strdata.slice(start, stop + 1);
		}
	}
};

InputStream.prototype.toString = function () {
	return this.strdata;
};

exports.InputStream = InputStream;

/***/ }),

/***/ "./node_modules/antlr4/IntervalSet.js":
/*!********************************************!*\
  !*** ./node_modules/antlr4/IntervalSet.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

/*jslint smarttabs:true */

var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;

/* stop is not included! */
function Interval(start, stop) {
	this.start = start;
	this.stop = stop;
	return this;
}

Interval.prototype.contains = function (item) {
	return item >= this.start && item < this.stop;
};

Interval.prototype.toString = function () {
	if (this.start === this.stop - 1) {
		return this.start.toString();
	} else {
		return this.start.toString() + ".." + (this.stop - 1).toString();
	}
};

Object.defineProperty(Interval.prototype, "length", {
	get: function get() {
		return this.stop - this.start;
	}
});

function IntervalSet() {
	this.intervals = null;
	this.readOnly = false;
}

IntervalSet.prototype.first = function (v) {
	if (this.intervals === null || this.intervals.length === 0) {
		return Token.INVALID_TYPE;
	} else {
		return this.intervals[0].start;
	}
};

IntervalSet.prototype.addOne = function (v) {
	this.addInterval(new Interval(v, v + 1));
};

IntervalSet.prototype.addRange = function (l, h) {
	this.addInterval(new Interval(l, h + 1));
};

IntervalSet.prototype.addInterval = function (v) {
	if (this.intervals === null) {
		this.intervals = [];
		this.intervals.push(v);
	} else {
		// find insert pos
		for (var k = 0; k < this.intervals.length; k++) {
			var i = this.intervals[k];
			// distinct range -> insert
			if (v.stop < i.start) {
				this.intervals.splice(k, 0, v);
				return;
			}
			// contiguous range -> adjust
			else if (v.stop === i.start) {
					this.intervals[k].start = v.start;
					return;
				}
				// overlapping range -> adjust and reduce
				else if (v.start <= i.stop) {
						this.intervals[k] = new Interval(Math.min(i.start, v.start), Math.max(i.stop, v.stop));
						this.reduce(k);
						return;
					}
		}
		// greater than any existing
		this.intervals.push(v);
	}
};

IntervalSet.prototype.addSet = function (other) {
	if (other.intervals !== null) {
		for (var k = 0; k < other.intervals.length; k++) {
			var i = other.intervals[k];
			this.addInterval(new Interval(i.start, i.stop));
		}
	}
	return this;
};

IntervalSet.prototype.reduce = function (k) {
	// only need to reduce if k is not the last
	if (k < this.intervalslength - 1) {
		var l = this.intervals[k];
		var r = this.intervals[k + 1];
		// if r contained in l
		if (l.stop >= r.stop) {
			this.intervals.pop(k + 1);
			this.reduce(k);
		} else if (l.stop >= r.start) {
			this.intervals[k] = new Interval(l.start, r.stop);
			this.intervals.pop(k + 1);
		}
	}
};

IntervalSet.prototype.complement = function (start, stop) {
	var result = new IntervalSet();
	result.addInterval(new Interval(start, stop + 1));
	for (var i = 0; i < this.intervals.length; i++) {
		result.removeRange(this.intervals[i]);
	}
	return result;
};

IntervalSet.prototype.contains = function (item) {
	if (this.intervals === null) {
		return false;
	} else {
		for (var k = 0; k < this.intervals.length; k++) {
			if (this.intervals[k].contains(item)) {
				return true;
			}
		}
		return false;
	}
};

Object.defineProperty(IntervalSet.prototype, "length", {
	get: function get() {
		var len = 0;
		this.intervals.map(function (i) {
			len += i.length;
		});
		return len;
	}
});

IntervalSet.prototype.removeRange = function (v) {
	if (v.start === v.stop - 1) {
		this.removeOne(v.start);
	} else if (this.intervals !== null) {
		var k = 0;
		for (var n = 0; n < this.intervals.length; n++) {
			var i = this.intervals[k];
			// intervals are ordered
			if (v.stop <= i.start) {
				return;
			}
			// check for including range, split it
			else if (v.start > i.start && v.stop < i.stop) {
					this.intervals[k] = new Interval(i.start, v.start);
					var x = new Interval(v.stop, i.stop);
					this.intervals.splice(k, 0, x);
					return;
				}
				// check for included range, remove it
				else if (v.start <= i.start && v.stop >= i.stop) {
						this.intervals.splice(k, 1);
						k = k - 1; // need another pass
					}
					// check for lower boundary
					else if (v.start < i.stop) {
							this.intervals[k] = new Interval(i.start, v.start);
						}
						// check for upper boundary
						else if (v.stop < i.stop) {
								this.intervals[k] = new Interval(v.stop, i.stop);
							}
			k += 1;
		}
	}
};

IntervalSet.prototype.removeOne = function (v) {
	if (this.intervals !== null) {
		for (var k = 0; k < this.intervals.length; k++) {
			var i = this.intervals[k];
			// intervals is ordered
			if (v < i.start) {
				return;
			}
			// check for single value range
			else if (v === i.start && v === i.stop - 1) {
					this.intervals.splice(k, 1);
					return;
				}
				// check for lower boundary
				else if (v === i.start) {
						this.intervals[k] = new Interval(i.start + 1, i.stop);
						return;
					}
					// check for upper boundary
					else if (v === i.stop - 1) {
							this.intervals[k] = new Interval(i.start, i.stop - 1);
							return;
						}
						// split existing range
						else if (v < i.stop - 1) {
								var x = new Interval(i.start, v);
								i.start = v + 1;
								this.intervals.splice(k, 0, x);
								return;
							}
		}
	}
};

IntervalSet.prototype.toString = function (literalNames, symbolicNames, elemsAreChar) {
	literalNames = literalNames || null;
	symbolicNames = symbolicNames || null;
	elemsAreChar = elemsAreChar || false;
	if (this.intervals === null) {
		return "{}";
	} else if (literalNames !== null || symbolicNames !== null) {
		return this.toTokenString(literalNames, symbolicNames);
	} else if (elemsAreChar) {
		return this.toCharString();
	} else {
		return this.toIndexString();
	}
};

IntervalSet.prototype.toCharString = function () {
	var names = [];
	for (var i = 0; i < this.intervals.length; i++) {
		var v = this.intervals[i];
		if (v.stop === v.start + 1) {
			if (v.start === Token.EOF) {
				names.push("<EOF>");
			} else {
				names.push("'" + String.fromCharCode(v.start) + "'");
			}
		} else {
			names.push("'" + String.fromCharCode(v.start) + "'..'" + String.fromCharCode(v.stop - 1) + "'");
		}
	}
	if (names.length > 1) {
		return "{" + names.join(", ") + "}";
	} else {
		return names[0];
	}
};

IntervalSet.prototype.toIndexString = function () {
	var names = [];
	for (var i = 0; i < this.intervals.length; i++) {
		var v = this.intervals[i];
		if (v.stop === v.start + 1) {
			if (v.start === Token.EOF) {
				names.push("<EOF>");
			} else {
				names.push(v.start.toString());
			}
		} else {
			names.push(v.start.toString() + ".." + (v.stop - 1).toString());
		}
	}
	if (names.length > 1) {
		return "{" + names.join(", ") + "}";
	} else {
		return names[0];
	}
};

IntervalSet.prototype.toTokenString = function (literalNames, symbolicNames) {
	var names = [];
	for (var i = 0; i < this.intervals.length; i++) {
		var v = this.intervals[i];
		for (var j = v.start; j < v.stop; j++) {
			names.push(this.elementName(literalNames, symbolicNames, j));
		}
	}
	if (names.length > 1) {
		return "{" + names.join(", ") + "}";
	} else {
		return names[0];
	}
};

IntervalSet.prototype.elementName = function (literalNames, symbolicNames, a) {
	if (a === Token.EOF) {
		return "<EOF>";
	} else if (a === Token.EPSILON) {
		return "<EPSILON>";
	} else {
		return literalNames[a] || symbolicNames[a];
	}
};

exports.Interval = Interval;
exports.IntervalSet = IntervalSet;

/***/ }),

/***/ "./node_modules/antlr4/LL1Analyzer.js":
/*!********************************************!*\
  !*** ./node_modules/antlr4/LL1Analyzer.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

var Set = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js").Set;
var BitSet = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js").BitSet;
var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
var ATNConfig = __webpack_require__(/*! ./atn/ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").ATNConfig;
var Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
var IntervalSet = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
var RuleStopState = __webpack_require__(/*! ./atn/ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
var RuleTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").RuleTransition;
var NotSetTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").NotSetTransition;
var WildcardTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").WildcardTransition;
var AbstractPredicateTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").AbstractPredicateTransition;

var pc = __webpack_require__(/*! ./PredictionContext */ "./node_modules/antlr4/PredictionContext.js");
var predictionContextFromRuleContext = pc.predictionContextFromRuleContext;
var PredictionContext = pc.PredictionContext;
var SingletonPredictionContext = pc.SingletonPredictionContext;

function LL1Analyzer(atn) {
    this.atn = atn;
}

//* Special value added to the lookahead sets to indicate that we hit
//  a predicate during analysis if {@code seeThruPreds==false}.
///
LL1Analyzer.HIT_PRED = Token.INVALID_TYPE;

//*
// Calculates the SLL(1) expected lookahead set for each outgoing transition
// of an {@link ATNState}. The returned array has one element for each
// outgoing transition in {@code s}. If the closure from transition
// <em>i</em> leads to a semantic predicate before matching a symbol, the
// element at index <em>i</em> of the result will be {@code null}.
//
// @param s the ATN state
// @return the expected symbols for each outgoing transition of {@code s}.
///
LL1Analyzer.prototype.getDecisionLookahead = function (s) {
    if (s === null) {
        return null;
    }
    var count = s.transitions.length;
    var look = [];
    for (var alt = 0; alt < count; alt++) {
        look[alt] = new IntervalSet();
        var lookBusy = new Set();
        var seeThruPreds = false; // fail to get lookahead upon pred
        this._LOOK(s.transition(alt).target, null, PredictionContext.EMPTY, look[alt], lookBusy, new BitSet(), seeThruPreds, false);
        // Wipe out lookahead for this alternative if we found nothing
        // or we had a predicate when we !seeThruPreds
        if (look[alt].length === 0 || look[alt].contains(LL1Analyzer.HIT_PRED)) {
            look[alt] = null;
        }
    }
    return look;
};

//*
// Compute set of tokens that can follow {@code s} in the ATN in the
// specified {@code ctx}.
//
// <p>If {@code ctx} is {@code null} and the end of the rule containing
// {@code s} is reached, {@link Token//EPSILON} is added to the result set.
// If {@code ctx} is not {@code null} and the end of the outermost rule is
// reached, {@link Token//EOF} is added to the result set.</p>
//
// @param s the ATN state
// @param stopState the ATN state to stop at. This can be a
// {@link BlockEndState} to detect epsilon paths through a closure.
// @param ctx the complete parser context, or {@code null} if the context
// should be ignored
//
// @return The set of tokens that can follow {@code s} in the ATN in the
// specified {@code ctx}.
///
LL1Analyzer.prototype.LOOK = function (s, stopState, ctx) {
    var r = new IntervalSet();
    var seeThruPreds = true; // ignore preds; get all lookahead
    ctx = ctx || null;
    var lookContext = ctx !== null ? predictionContextFromRuleContext(s.atn, ctx) : null;
    this._LOOK(s, stopState, lookContext, r, new Set(), new BitSet(), seeThruPreds, true);
    return r;
};

//*
// Compute set of tokens that can follow {@code s} in the ATN in the
// specified {@code ctx}.
//
// <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the
// rule containing {@code s} is reached, {@link Token//EPSILON} is added to
// the result set. If {@code ctx} is not {@code null} and {@code addEOF} is
// {@code true} and {@code stopState} or the end of the outermost rule is
// reached, {@link Token//EOF} is added to the result set.</p>
//
// @param s the ATN state.
// @param stopState the ATN state to stop at. This can be a
// {@link BlockEndState} to detect epsilon paths through a closure.
// @param ctx The outer context, or {@code null} if the outer context should
// not be used.
// @param look The result lookahead set.
// @param lookBusy A set used for preventing epsilon closures in the ATN
// from causing a stack overflow. Outside code should pass
// {@code new Set<ATNConfig>} for this argument.
// @param calledRuleStack A set used for preventing left recursion in the
// ATN from causing a stack overflow. Outside code should pass
// {@code new BitSet()} for this argument.
// @param seeThruPreds {@code true} to true semantic predicates as
// implicitly {@code true} and "see through them", otherwise {@code false}
// to treat semantic predicates as opaque and add {@link //HIT_PRED} to the
// result if one is encountered.
// @param addEOF Add {@link Token//EOF} to the result if the end of the
// outermost context is reached. This parameter has no effect if {@code ctx}
// is {@code null}.
///
LL1Analyzer.prototype._LOOK = function (s, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) {
    var c = new ATNConfig({ state: s, alt: 0, context: ctx }, null);
    if (lookBusy.contains(c)) {
        return;
    }
    lookBusy.add(c);
    if (s === stopState) {
        if (ctx === null) {
            look.addOne(Token.EPSILON);
            return;
        } else if (ctx.isEmpty() && addEOF) {
            look.addOne(Token.EOF);
            return;
        }
    }
    if (s instanceof RuleStopState) {
        if (ctx === null) {
            look.addOne(Token.EPSILON);
            return;
        } else if (ctx.isEmpty() && addEOF) {
            look.addOne(Token.EOF);
            return;
        }
        if (ctx !== PredictionContext.EMPTY) {
            // run thru all possible stack tops in ctx
            for (var i = 0; i < ctx.length; i++) {
                var returnState = this.atn.states[ctx.getReturnState(i)];
                var removed = calledRuleStack.contains(returnState.ruleIndex);
                try {
                    calledRuleStack.remove(returnState.ruleIndex);
                    this._LOOK(returnState, stopState, ctx.getParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
                } finally {
                    if (removed) {
                        calledRuleStack.add(returnState.ruleIndex);
                    }
                }
            }
            return;
        }
    }
    for (var j = 0; j < s.transitions.length; j++) {
        var t = s.transitions[j];
        if (t.constructor === RuleTransition) {
            if (calledRuleStack.contains(t.target.ruleIndex)) {
                continue;
            }
            var newContext = SingletonPredictionContext.create(ctx, t.followState.stateNumber);
            try {
                calledRuleStack.add(t.target.ruleIndex);
                this._LOOK(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
            } finally {
                calledRuleStack.remove(t.target.ruleIndex);
            }
        } else if (t instanceof AbstractPredicateTransition) {
            if (seeThruPreds) {
                this._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
            } else {
                look.addOne(LL1Analyzer.HIT_PRED);
            }
        } else if (t.isEpsilon) {
            this._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
        } else if (t.constructor === WildcardTransition) {
            look.addRange(Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType);
        } else {
            var set = t.label;
            if (set !== null) {
                if (t instanceof NotSetTransition) {
                    set = set.complement(Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType);
                }
                look.addSet(set);
            }
        }
    }
};

exports.LL1Analyzer = LL1Analyzer;

/***/ }),

/***/ "./node_modules/antlr4/Lexer.js":
/*!**************************************!*\
  !*** ./node_modules/antlr4/Lexer.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

// A lexer is recognizer that draws input symbols from a character stream.
//  lexer grammars result in a subclass of this object. A Lexer object
//  uses simplified match() and error recovery mechanisms in the interest of speed.

var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
var Recognizer = __webpack_require__(/*! ./Recognizer */ "./node_modules/antlr4/Recognizer.js").Recognizer;
var CommonTokenFactory = __webpack_require__(/*! ./CommonTokenFactory */ "./node_modules/antlr4/CommonTokenFactory.js").CommonTokenFactory;
var RecognitionException = __webpack_require__(/*! ./error/Errors */ "./node_modules/antlr4/error/Errors.js").RecognitionException;
var LexerNoViableAltException = __webpack_require__(/*! ./error/Errors */ "./node_modules/antlr4/error/Errors.js").LexerNoViableAltException;

function TokenSource() {
	return this;
}

function Lexer(input) {
	Recognizer.call(this);
	this._input = input;
	this._factory = CommonTokenFactory.DEFAULT;
	this._tokenFactorySourcePair = [this, input];

	this._interp = null; // child classes must populate this

	// The goal of all lexer rules/methods is to create a token object.
	// this is an instance variable as multiple rules may collaborate to
	// create a single token. nextToken will return this object after
	// matching lexer rule(s). If you subclass to allow multiple token
	// emissions, then set this to the last token to be matched or
	// something nonnull so that the auto token emit mechanism will not
	// emit another token.
	this._token = null;

	// What character index in the stream did the current token start at?
	// Needed, for example, to get the text for current token. Set at
	// the start of nextToken.
	this._tokenStartCharIndex = -1;

	// The line on which the first character of the token resides///
	this._tokenStartLine = -1;

	// The character position of first character within the line///
	this._tokenStartColumn = -1;

	// Once we see EOF on char stream, next token will be EOF.
	// If you have DONE : EOF ; then you see DONE EOF.
	this._hitEOF = false;

	// The channel number for the current token///
	this._channel = Token.DEFAULT_CHANNEL;

	// The token type for the current token///
	this._type = Token.INVALID_TYPE;

	this._modeStack = [];
	this._mode = Lexer.DEFAULT_MODE;

	// You can set the text for the current token to override what is in
	// the input char buffer. Use setText() or can set this instance var.
	// /
	this._text = null;

	return this;
}

Lexer.prototype = Object.create(Recognizer.prototype);
Lexer.prototype.constructor = Lexer;

Lexer.DEFAULT_MODE = 0;
Lexer.MORE = -2;
Lexer.SKIP = -3;

Lexer.DEFAULT_TOKEN_CHANNEL = Token.DEFAULT_CHANNEL;
Lexer.HIDDEN = Token.HIDDEN_CHANNEL;
Lexer.MIN_CHAR_VALUE = 0x0000;
Lexer.MAX_CHAR_VALUE = 0x10FFFF;

Lexer.prototype.reset = function () {
	// wack Lexer state variables
	if (this._input !== null) {
		this._input.seek(0); // rewind the input
	}
	this._token = null;
	this._type = Token.INVALID_TYPE;
	this._channel = Token.DEFAULT_CHANNEL;
	this._tokenStartCharIndex = -1;
	this._tokenStartColumn = -1;
	this._tokenStartLine = -1;
	this._text = null;

	this._hitEOF = false;
	this._mode = Lexer.DEFAULT_MODE;
	this._modeStack = [];

	this._interp.reset();
};

// Return a token from this source; i.e., match a token on the char stream.
Lexer.prototype.nextToken = function () {
	if (this._input === null) {
		throw "nextToken requires a non-null input stream.";
	}

	// Mark start location in char stream so unbuffered streams are
	// guaranteed at least have text of current token
	var tokenStartMarker = this._input.mark();
	try {
		while (true) {
			if (this._hitEOF) {
				this.emitEOF();
				return this._token;
			}
			this._token = null;
			this._channel = Token.DEFAULT_CHANNEL;
			this._tokenStartCharIndex = this._input.index;
			this._tokenStartColumn = this._interp.column;
			this._tokenStartLine = this._interp.line;
			this._text = null;
			var continueOuter = false;
			while (true) {
				this._type = Token.INVALID_TYPE;
				var ttype = Lexer.SKIP;
				try {
					ttype = this._interp.match(this._input, this._mode);
				} catch (e) {
					if (e instanceof RecognitionException) {
						this.notifyListeners(e); // report error
						this.recover(e);
					} else {
						console.log(e.stack);
						throw e;
					}
				}
				if (this._input.LA(1) === Token.EOF) {
					this._hitEOF = true;
				}
				if (this._type === Token.INVALID_TYPE) {
					this._type = ttype;
				}
				if (this._type === Lexer.SKIP) {
					continueOuter = true;
					break;
				}
				if (this._type !== Lexer.MORE) {
					break;
				}
			}
			if (continueOuter) {
				continue;
			}
			if (this._token === null) {
				this.emit();
			}
			return this._token;
		}
	} finally {
		// make sure we release marker after match or
		// unbuffered char stream will keep buffering
		this._input.release(tokenStartMarker);
	}
};

// Instruct the lexer to skip creating a token for current lexer rule
// and look for another token. nextToken() knows to keep looking when
// a lexer rule finishes with token set to SKIP_TOKEN. Recall that
// if token==null at end of any token rule, it creates one for you
// and emits it.
// /
Lexer.prototype.skip = function () {
	this._type = Lexer.SKIP;
};

Lexer.prototype.more = function () {
	this._type = Lexer.MORE;
};

Lexer.prototype.mode = function (m) {
	this._mode = m;
};

Lexer.prototype.pushMode = function (m) {
	if (this._interp.debug) {
		console.log("pushMode " + m);
	}
	this._modeStack.push(this._mode);
	this.mode(m);
};

Lexer.prototype.popMode = function () {
	if (this._modeStack.length === 0) {
		throw "Empty Stack";
	}
	if (this._interp.debug) {
		console.log("popMode back to " + this._modeStack.slice(0, -1));
	}
	this.mode(this._modeStack.pop());
	return this._mode;
};

// Set the char stream and reset the lexer
Object.defineProperty(Lexer.prototype, "inputStream", {
	get: function get() {
		return this._input;
	},
	set: function set(input) {
		this._input = null;
		this._tokenFactorySourcePair = [this, this._input];
		this.reset();
		this._input = input;
		this._tokenFactorySourcePair = [this, this._input];
	}
});

Object.defineProperty(Lexer.prototype, "sourceName", {
	get: function sourceName() {
		return this._input.sourceName;
	}
});

// By default does not support multiple emits per nextToken invocation
// for efficiency reasons. Subclass and override this method, nextToken,
// and getToken (to push tokens into a list and pull from that list
// rather than a single variable as this implementation does).
// /
Lexer.prototype.emitToken = function (token) {
	this._token = token;
};

// The standard method called to automatically emit a token at the
// outermost lexical rule. The token object should point into the
// char buffer start..stop. If there is a text override in 'text',
// use that to set the token's text. Override this method to emit
// custom Token objects or provide a new factory.
// /
Lexer.prototype.emit = function () {
	var t = this._factory.create(this._tokenFactorySourcePair, this._type, this._text, this._channel, this._tokenStartCharIndex, this.getCharIndex() - 1, this._tokenStartLine, this._tokenStartColumn);
	this.emitToken(t);
	return t;
};

Lexer.prototype.emitEOF = function () {
	var cpos = this.column;
	var lpos = this.line;
	var eof = this._factory.create(this._tokenFactorySourcePair, Token.EOF, null, Token.DEFAULT_CHANNEL, this._input.index, this._input.index - 1, lpos, cpos);
	this.emitToken(eof);
	return eof;
};

Object.defineProperty(Lexer.prototype, "type", {
	get: function get() {
		return this.type;
	},
	set: function set(type) {
		this._type = type;
	}
});

Object.defineProperty(Lexer.prototype, "line", {
	get: function get() {
		return this._interp.line;
	},
	set: function set(line) {
		this._interp.line = line;
	}
});

Object.defineProperty(Lexer.prototype, "column", {
	get: function get() {
		return this._interp.column;
	},
	set: function set(column) {
		this._interp.column = column;
	}
});

// What is the index of the current character of lookahead?///
Lexer.prototype.getCharIndex = function () {
	return this._input.index;
};

// Return the text matched so far for the current token or any text override.
//Set the complete text of this token; it wipes any previous changes to the text.
Object.defineProperty(Lexer.prototype, "text", {
	get: function get() {
		if (this._text !== null) {
			return this._text;
		} else {
			return this._interp.getText(this._input);
		}
	},
	set: function set(text) {
		this._text = text;
	}
});
// Return a list of all Token objects in input char stream.
// Forces load of all tokens. Does not include EOF token.
// /
Lexer.prototype.getAllTokens = function () {
	var tokens = [];
	var t = this.nextToken();
	while (t.type !== Token.EOF) {
		tokens.push(t);
		t = this.nextToken();
	}
	return tokens;
};

Lexer.prototype.notifyListeners = function (e) {
	var start = this._tokenStartCharIndex;
	var stop = this._input.index;
	var text = this._input.getText(start, stop);
	var msg = "token recognition error at: '" + this.getErrorDisplay(text) + "'";
	var listener = this.getErrorListenerDispatch();
	listener.syntaxError(this, null, this._tokenStartLine, this._tokenStartColumn, msg, e);
};

Lexer.prototype.getErrorDisplay = function (s) {
	var d = [];
	for (var i = 0; i < s.length; i++) {
		d.push(s[i]);
	}
	return d.join('');
};

Lexer.prototype.getErrorDisplayForChar = function (c) {
	if (c.charCodeAt(0) === Token.EOF) {
		return "<EOF>";
	} else if (c === '\n') {
		return "\\n";
	} else if (c === '\t') {
		return "\\t";
	} else if (c === '\r') {
		return "\\r";
	} else {
		return c;
	}
};

Lexer.prototype.getCharErrorDisplay = function (c) {
	return "'" + this.getErrorDisplayForChar(c) + "'";
};

// Lexers can normally match any char in it's vocabulary after matching
// a token, so do the easy thing and just kill a character and hope
// it all works out. You can instead use the rule invocation stack
// to do sophisticated error recovery if you are in a fragment rule.
// /
Lexer.prototype.recover = function (re) {
	if (this._input.LA(1) !== Token.EOF) {
		if (re instanceof LexerNoViableAltException) {
			// skip a char and try again
			this._interp.consume(this._input);
		} else {
			// TODO: Do we lose character or line position information?
			this._input.consume();
		}
	}
};

exports.Lexer = Lexer;

/***/ }),

/***/ "./node_modules/antlr4/Parser.js":
/*!***************************************!*\
  !*** ./node_modules/antlr4/Parser.js ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
var ParseTreeListener = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").ParseTreeListener;
var Recognizer = __webpack_require__(/*! ./Recognizer */ "./node_modules/antlr4/Recognizer.js").Recognizer;
var DefaultErrorStrategy = __webpack_require__(/*! ./error/ErrorStrategy */ "./node_modules/antlr4/error/ErrorStrategy.js").DefaultErrorStrategy;
var ATNDeserializer = __webpack_require__(/*! ./atn/ATNDeserializer */ "./node_modules/antlr4/atn/ATNDeserializer.js").ATNDeserializer;
var ATNDeserializationOptions = __webpack_require__(/*! ./atn/ATNDeserializationOptions */ "./node_modules/antlr4/atn/ATNDeserializationOptions.js").ATNDeserializationOptions;
var TerminalNode = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").TerminalNode;
var ErrorNode = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").ErrorNode;

function TraceListener(parser) {
	ParseTreeListener.call(this);
	this.parser = parser;
	return this;
}

TraceListener.prototype = Object.create(ParseTreeListener.prototype);
TraceListener.prototype.constructor = TraceListener;

TraceListener.prototype.enterEveryRule = function (ctx) {
	console.log("enter   " + this.parser.ruleNames[ctx.ruleIndex] + ", LT(1)=" + this.parser._input.LT(1).text);
};

TraceListener.prototype.visitTerminal = function (node) {
	console.log("consume " + node.symbol + " rule " + this.parser.ruleNames[this.parser._ctx.ruleIndex]);
};

TraceListener.prototype.exitEveryRule = function (ctx) {
	console.log("exit    " + this.parser.ruleNames[ctx.ruleIndex] + ", LT(1)=" + this.parser._input.LT(1).text);
};

// this is all the parsing support code essentially; most of it is error
// recovery stuff.//
function Parser(input) {
	Recognizer.call(this);
	// The input stream.
	this._input = null;
	// The error handling strategy for the parser. The default value is a new
	// instance of {@link DefaultErrorStrategy}.
	this._errHandler = new DefaultErrorStrategy();
	this._precedenceStack = [];
	this._precedenceStack.push(0);
	// The {@link ParserRuleContext} object for the currently executing rule.
	// this is always non-null during the parsing process.
	this._ctx = null;
	// Specifies whether or not the parser should construct a parse tree during
	// the parsing process. The default value is {@code true}.
	this.buildParseTrees = true;
	// When {@link //setTrace}{@code (true)} is called, a reference to the
	// {@link TraceListener} is stored here so it can be easily removed in a
	// later call to {@link //setTrace}{@code (false)}. The listener itself is
	// implemented as a parser listener so this field is not directly used by
	// other parser methods.
	this._tracer = null;
	// The list of {@link ParseTreeListener} listeners registered to receive
	// events during the parse.
	this._parseListeners = null;
	// The number of syntax errors reported during parsing. this value is
	// incremented each time {@link //notifyErrorListeners} is called.
	this._syntaxErrors = 0;
	this.setInputStream(input);
	return this;
}

Parser.prototype = Object.create(Recognizer.prototype);
Parser.prototype.contructor = Parser;

// this field maps from the serialized ATN string to the deserialized {@link
// ATN} with
// bypass alternatives.
//
// @see ATNDeserializationOptions//isGenerateRuleBypassTransitions()
//
Parser.bypassAltsAtnCache = {};

// reset the parser's state//
Parser.prototype.reset = function () {
	if (this._input !== null) {
		this._input.seek(0);
	}
	this._errHandler.reset(this);
	this._ctx = null;
	this._syntaxErrors = 0;
	this.setTrace(false);
	this._precedenceStack = [];
	this._precedenceStack.push(0);
	if (this._interp !== null) {
		this._interp.reset();
	}
};

// Match current input symbol against {@code ttype}. If the symbol type
// matches, {@link ANTLRErrorStrategy//reportMatch} and {@link //consume} are
// called to complete the match process.
//
// <p>If the symbol type does not match,
// {@link ANTLRErrorStrategy//recoverInline} is called on the current error
// strategy to attempt recovery. If {@link //getBuildParseTree} is
// {@code true} and the token index of the symbol returned by
// {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to
// the parse tree by calling {@link ParserRuleContext//addErrorNode}.</p>
//
// @param ttype the token type to match
// @return the matched symbol
// @throws RecognitionException if the current input symbol did not match
// {@code ttype} and the error strategy could not recover from the
// mismatched symbol

Parser.prototype.match = function (ttype) {
	var t = this.getCurrentToken();
	if (t.type === ttype) {
		this._errHandler.reportMatch(this);
		this.consume();
	} else {
		t = this._errHandler.recoverInline(this);
		if (this.buildParseTrees && t.tokenIndex === -1) {
			// we must have conjured up a new token during single token
			// insertion
			// if it's not the current symbol
			this._ctx.addErrorNode(t);
		}
	}
	return t;
};
// Match current input symbol as a wildcard. If the symbol type matches
// (i.e. has a value greater than 0), {@link ANTLRErrorStrategy//reportMatch}
// and {@link //consume} are called to complete the match process.
//
// <p>If the symbol type does not match,
// {@link ANTLRErrorStrategy//recoverInline} is called on the current error
// strategy to attempt recovery. If {@link //getBuildParseTree} is
// {@code true} and the token index of the symbol returned by
// {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to
// the parse tree by calling {@link ParserRuleContext//addErrorNode}.</p>
//
// @return the matched symbol
// @throws RecognitionException if the current input symbol did not match
// a wildcard and the error strategy could not recover from the mismatched
// symbol

Parser.prototype.matchWildcard = function () {
	var t = this.getCurrentToken();
	if (t.type > 0) {
		this._errHandler.reportMatch(this);
		this.consume();
	} else {
		t = this._errHandler.recoverInline(this);
		if (this._buildParseTrees && t.tokenIndex === -1) {
			// we must have conjured up a new token during single token
			// insertion
			// if it's not the current symbol
			this._ctx.addErrorNode(t);
		}
	}
	return t;
};

Parser.prototype.getParseListeners = function () {
	return this._parseListeners || [];
};

// Registers {@code listener} to receive events during the parsing process.
//
// <p>To support output-preserving grammar transformations (including but not
// limited to left-recursion removal, automated left-factoring, and
// optimized code generation), calls to listener methods during the parse
// may differ substantially from calls made by
// {@link ParseTreeWalker//DEFAULT} used after the parse is complete. In
// particular, rule entry and exit events may occur in a different order
// during the parse than after the parser. In addition, calls to certain
// rule entry methods may be omitted.</p>
//
// <p>With the following specific exceptions, calls to listener events are
// <em>deterministic</em>, i.e. for identical input the calls to listener
// methods will be the same.</p>
//
// <ul>
// <li>Alterations to the grammar used to generate code may change the
// behavior of the listener calls.</li>
// <li>Alterations to the command line options passed to ANTLR 4 when
// generating the parser may change the behavior of the listener calls.</li>
// <li>Changing the version of the ANTLR Tool used to generate the parser
// may change the behavior of the listener calls.</li>
// </ul>
//
// @param listener the listener to add
//
// @throws NullPointerException if {@code} listener is {@code null}
//
Parser.prototype.addParseListener = function (listener) {
	if (listener === null) {
		throw "listener";
	}
	if (this._parseListeners === null) {
		this._parseListeners = [];
	}
	this._parseListeners.push(listener);
};

//
// Remove {@code listener} from the list of parse listeners.
//
// <p>If {@code listener} is {@code null} or has not been added as a parse
// listener, this method does nothing.</p>
// @param listener the listener to remove
//
Parser.prototype.removeParseListener = function (listener) {
	if (this._parseListeners !== null) {
		var idx = this._parseListeners.indexOf(listener);
		if (idx >= 0) {
			this._parseListeners.splice(idx, 1);
		}
		if (this._parseListeners.length === 0) {
			this._parseListeners = null;
		}
	}
};

// Remove all parse listeners.
Parser.prototype.removeParseListeners = function () {
	this._parseListeners = null;
};

// Notify any parse listeners of an enter rule event.
Parser.prototype.triggerEnterRuleEvent = function () {
	if (this._parseListeners !== null) {
		var ctx = this._ctx;
		this._parseListeners.map(function (listener) {
			listener.enterEveryRule(ctx);
			ctx.enterRule(listener);
		});
	}
};

//
// Notify any parse listeners of an exit rule event.
//
// @see //addParseListener
//
Parser.prototype.triggerExitRuleEvent = function () {
	if (this._parseListeners !== null) {
		// reverse order walk of listeners
		var ctx = this._ctx;
		this._parseListeners.slice(0).reverse().map(function (listener) {
			ctx.exitRule(listener);
			listener.exitEveryRule(ctx);
		});
	}
};

Parser.prototype.getTokenFactory = function () {
	return this._input.tokenSource._factory;
};

// Tell our token source and error strategy about a new way to create tokens.//
Parser.prototype.setTokenFactory = function (factory) {
	this._input.tokenSource._factory = factory;
};

// The ATN with bypass alternatives is expensive to create so we create it
// lazily.
//
// @throws UnsupportedOperationException if the current parser does not
// implement the {@link //getSerializedATN()} method.
//
Parser.prototype.getATNWithBypassAlts = function () {
	var serializedAtn = this.getSerializedATN();
	if (serializedAtn === null) {
		throw "The current parser does not support an ATN with bypass alternatives.";
	}
	var result = this.bypassAltsAtnCache[serializedAtn];
	if (result === null) {
		var deserializationOptions = new ATNDeserializationOptions();
		deserializationOptions.generateRuleBypassTransitions = true;
		result = new ATNDeserializer(deserializationOptions).deserialize(serializedAtn);
		this.bypassAltsAtnCache[serializedAtn] = result;
	}
	return result;
};

// The preferred method of getting a tree pattern. For example, here's a
// sample use:
//
// <pre>
// ParseTree t = parser.expr();
// ParseTreePattern p = parser.compileParseTreePattern("&lt;ID&gt;+0",
// MyParser.RULE_expr);
// ParseTreeMatch m = p.match(t);
// String id = m.get("ID");
// </pre>

var Lexer = __webpack_require__(/*! ./Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;

Parser.prototype.compileParseTreePattern = function (pattern, patternRuleIndex, lexer) {
	lexer = lexer || null;
	if (lexer === null) {
		if (this.getTokenStream() !== null) {
			var tokenSource = this.getTokenStream().tokenSource;
			if (tokenSource instanceof Lexer) {
				lexer = tokenSource;
			}
		}
	}
	if (lexer === null) {
		throw "Parser can't discover a lexer to use";
	}
	var m = new ParseTreePatternMatcher(lexer, this);
	return m.compile(pattern, patternRuleIndex);
};

Parser.prototype.getInputStream = function () {
	return this.getTokenStream();
};

Parser.prototype.setInputStream = function (input) {
	this.setTokenStream(input);
};

Parser.prototype.getTokenStream = function () {
	return this._input;
};

// Set the token stream and reset the parser.//
Parser.prototype.setTokenStream = function (input) {
	this._input = null;
	this.reset();
	this._input = input;
};

// Match needs to return the current input symbol, which gets put
// into the label for the associated token ref; e.g., x=ID.
//
Parser.prototype.getCurrentToken = function () {
	return this._input.LT(1);
};

Parser.prototype.notifyErrorListeners = function (msg, offendingToken, err) {
	offendingToken = offendingToken || null;
	err = err || null;
	if (offendingToken === null) {
		offendingToken = this.getCurrentToken();
	}
	this._syntaxErrors += 1;
	var line = offendingToken.line;
	var column = offendingToken.column;
	var listener = this.getErrorListenerDispatch();
	listener.syntaxError(this, offendingToken, line, column, msg, err);
};

//
// Consume and return the {@linkplain //getCurrentToken current symbol}.
//
// <p>E.g., given the following input with {@code A} being the current
// lookahead symbol, this function moves the cursor to {@code B} and returns
// {@code A}.</p>
//
// <pre>
// A B
// ^
// </pre>
//
// If the parser is not in error recovery mode, the consumed symbol is added
// to the parse tree using {@link ParserRuleContext//addChild(Token)}, and
// {@link ParseTreeListener//visitTerminal} is called on any parse listeners.
// If the parser <em>is</em> in error recovery mode, the consumed symbol is
// added to the parse tree using
// {@link ParserRuleContext//addErrorNode(Token)}, and
// {@link ParseTreeListener//visitErrorNode} is called on any parse
// listeners.
//
Parser.prototype.consume = function () {
	var o = this.getCurrentToken();
	if (o.type !== Token.EOF) {
		this.getInputStream().consume();
	}
	var hasListener = this._parseListeners !== null && this._parseListeners.length > 0;
	if (this.buildParseTrees || hasListener) {
		var node;
		if (this._errHandler.inErrorRecoveryMode(this)) {
			node = this._ctx.addErrorNode(o);
		} else {
			node = this._ctx.addTokenNode(o);
		}
		node.invokingState = this.state;
		if (hasListener) {
			this._parseListeners.map(function (listener) {
				if (node instanceof ErrorNode || node.isErrorNode !== undefined && node.isErrorNode()) {
					listener.visitErrorNode(node);
				} else if (node instanceof TerminalNode) {
					listener.visitTerminal(node);
				}
			});
		}
	}
	return o;
};

Parser.prototype.addContextToParseTree = function () {
	// add current context to parent if we have a parent
	if (this._ctx.parentCtx !== null) {
		this._ctx.parentCtx.addChild(this._ctx);
	}
};

// Always called by generated parsers upon entry to a rule. Access field
// {@link //_ctx} get the current context.

Parser.prototype.enterRule = function (localctx, state, ruleIndex) {
	this.state = state;
	this._ctx = localctx;
	this._ctx.start = this._input.LT(1);
	if (this.buildParseTrees) {
		this.addContextToParseTree();
	}
	if (this._parseListeners !== null) {
		this.triggerEnterRuleEvent();
	}
};

Parser.prototype.exitRule = function () {
	this._ctx.stop = this._input.LT(-1);
	// trigger event on _ctx, before it reverts to parent
	if (this._parseListeners !== null) {
		this.triggerExitRuleEvent();
	}
	this.state = this._ctx.invokingState;
	this._ctx = this._ctx.parentCtx;
};

Parser.prototype.enterOuterAlt = function (localctx, altNum) {
	localctx.setAltNumber(altNum);
	// if we have new localctx, make sure we replace existing ctx
	// that is previous child of parse tree
	if (this.buildParseTrees && this._ctx !== localctx) {
		if (this._ctx.parentCtx !== null) {
			this._ctx.parentCtx.removeLastChild();
			this._ctx.parentCtx.addChild(localctx);
		}
	}
	this._ctx = localctx;
};

// Get the precedence level for the top-most precedence rule.
//
// @return The precedence level for the top-most precedence rule, or -1 if
// the parser context is not nested within a precedence rule.

Parser.prototype.getPrecedence = function () {
	if (this._precedenceStack.length === 0) {
		return -1;
	} else {
		return this._precedenceStack[this._precedenceStack.length - 1];
	}
};

Parser.prototype.enterRecursionRule = function (localctx, state, ruleIndex, precedence) {
	this.state = state;
	this._precedenceStack.push(precedence);
	this._ctx = localctx;
	this._ctx.start = this._input.LT(1);
	if (this._parseListeners !== null) {
		this.triggerEnterRuleEvent(); // simulates rule entry for
		// left-recursive rules
	}
};

//
// Like {@link //enterRule} but for recursive rules.

Parser.prototype.pushNewRecursionContext = function (localctx, state, ruleIndex) {
	var previous = this._ctx;
	previous.parentCtx = localctx;
	previous.invokingState = state;
	previous.stop = this._input.LT(-1);

	this._ctx = localctx;
	this._ctx.start = previous.start;
	if (this.buildParseTrees) {
		this._ctx.addChild(previous);
	}
	if (this._parseListeners !== null) {
		this.triggerEnterRuleEvent(); // simulates rule entry for
		// left-recursive rules
	}
};

Parser.prototype.unrollRecursionContexts = function (parentCtx) {
	this._precedenceStack.pop();
	this._ctx.stop = this._input.LT(-1);
	var retCtx = this._ctx; // save current ctx (return value)
	// unroll so _ctx is as it was before call to recursive method
	if (this._parseListeners !== null) {
		while (this._ctx !== parentCtx) {
			this.triggerExitRuleEvent();
			this._ctx = this._ctx.parentCtx;
		}
	} else {
		this._ctx = parentCtx;
	}
	// hook into tree
	retCtx.parentCtx = parentCtx;
	if (this.buildParseTrees && parentCtx !== null) {
		// add return ctx into invoking rule's tree
		parentCtx.addChild(retCtx);
	}
};

Parser.prototype.getInvokingContext = function (ruleIndex) {
	var ctx = this._ctx;
	while (ctx !== null) {
		if (ctx.ruleIndex === ruleIndex) {
			return ctx;
		}
		ctx = ctx.parentCtx;
	}
	return null;
};

Parser.prototype.precpred = function (localctx, precedence) {
	return precedence >= this._precedenceStack[this._precedenceStack.length - 1];
};

Parser.prototype.inContext = function (context) {
	// TODO: useful in parser?
	return false;
};

//
// Checks whether or not {@code symbol} can follow the current state in the
// ATN. The behavior of this method is equivalent to the following, but is
// implemented such that the complete context-sensitive follow set does not
// need to be explicitly constructed.
//
// <pre>
// return getExpectedTokens().contains(symbol);
// </pre>
//
// @param symbol the symbol type to check
// @return {@code true} if {@code symbol} can follow the current state in
// the ATN, otherwise {@code false}.

Parser.prototype.isExpectedToken = function (symbol) {
	var atn = this._interp.atn;
	var ctx = this._ctx;
	var s = atn.states[this.state];
	var following = atn.nextTokens(s);
	if (following.contains(symbol)) {
		return true;
	}
	if (!following.contains(Token.EPSILON)) {
		return false;
	}
	while (ctx !== null && ctx.invokingState >= 0 && following.contains(Token.EPSILON)) {
		var invokingState = atn.states[ctx.invokingState];
		var rt = invokingState.transitions[0];
		following = atn.nextTokens(rt.followState);
		if (following.contains(symbol)) {
			return true;
		}
		ctx = ctx.parentCtx;
	}
	if (following.contains(Token.EPSILON) && symbol === Token.EOF) {
		return true;
	} else {
		return false;
	}
};

// Computes the set of input symbols which could follow the current parser
// state and context, as given by {@link //getState} and {@link //getContext},
// respectively.
//
// @see ATN//getExpectedTokens(int, RuleContext)
//
Parser.prototype.getExpectedTokens = function () {
	return this._interp.atn.getExpectedTokens(this.state, this._ctx);
};

Parser.prototype.getExpectedTokensWithinCurrentRule = function () {
	var atn = this._interp.atn;
	var s = atn.states[this.state];
	return atn.nextTokens(s);
};

// Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found.//
Parser.prototype.getRuleIndex = function (ruleName) {
	var ruleIndex = this.getRuleIndexMap()[ruleName];
	if (ruleIndex !== null) {
		return ruleIndex;
	} else {
		return -1;
	}
};

// Return List&lt;String&gt; of the rule names in your parser instance
// leading up to a call to the current rule. You could override if
// you want more details such as the file/line info of where
// in the ATN a rule is invoked.
//
// this is very useful for error messages.
//
Parser.prototype.getRuleInvocationStack = function (p) {
	p = p || null;
	if (p === null) {
		p = this._ctx;
	}
	var stack = [];
	while (p !== null) {
		// compute what follows who invoked us
		var ruleIndex = p.ruleIndex;
		if (ruleIndex < 0) {
			stack.push("n/a");
		} else {
			stack.push(this.ruleNames[ruleIndex]);
		}
		p = p.parentCtx;
	}
	return stack;
};

// For debugging and other purposes.//
Parser.prototype.getDFAStrings = function () {
	return this._interp.decisionToDFA.toString();
};
// For debugging and other purposes.//
Parser.prototype.dumpDFA = function () {
	var seenOne = false;
	for (var i = 0; i < this._interp.decisionToDFA.length; i++) {
		var dfa = this._interp.decisionToDFA[i];
		if (dfa.states.length > 0) {
			if (seenOne) {
				console.log();
			}
			this.printer.println("Decision " + dfa.decision + ":");
			this.printer.print(dfa.toString(this.literalNames, this.symbolicNames));
			seenOne = true;
		}
	}
};

/*
"			printer = function() {\r\n" +
"				this.println = function(s) { document.getElementById('output') += s + '\\n'; }\r\n" +
"				this.print = function(s) { document.getElementById('output') += s; }\r\n" +
"			};\r\n" +
*/

Parser.prototype.getSourceName = function () {
	return this._input.sourceName;
};

// During a parse is sometimes useful to listen in on the rule entry and exit
// events as well as token matches. this is for quick and dirty debugging.
//
Parser.prototype.setTrace = function (trace) {
	if (!trace) {
		this.removeParseListener(this._tracer);
		this._tracer = null;
	} else {
		if (this._tracer !== null) {
			this.removeParseListener(this._tracer);
		}
		this._tracer = new TraceListener(this);
		this.addParseListener(this._tracer);
	}
};

exports.Parser = Parser;

/***/ }),

/***/ "./node_modules/antlr4/ParserRuleContext.js":
/*!**************************************************!*\
  !*** ./node_modules/antlr4/ParserRuleContext.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

//* A rule invocation record for parsing.
//
//  Contains all of the information about the current rule not stored in the
//  RuleContext. It handles parse tree children list, Any ATN state
//  tracing, and the default values available for rule indications:
//  start, stop, rule index, current alt number, current
//  ATN state.
//
//  Subclasses made for each rule and grammar track the parameters,
//  return values, locals, and labels specific to that rule. These
//  are the objects that are returned from rules.
//
//  Note text is not an actual field of a rule return value; it is computed
//  from start and stop using the input stream's toString() method.  I
//  could add a ctor to this so that we can pass in and store the input
//  stream, but I'm not sure we want to do that.  It would seem to be undefined
//  to get the .text property anyway if the rule matches tokens from multiple
//  input streams.
//
//  I do not use getters for fields of objects that are used simply to
//  group values such as this aggregate.  The getters/setters are there to
//  satisfy the superclass interface.

var RuleContext = __webpack_require__(/*! ./RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
var Tree = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js");
var INVALID_INTERVAL = Tree.INVALID_INTERVAL;
var TerminalNode = Tree.TerminalNode;
var TerminalNodeImpl = Tree.TerminalNodeImpl;
var ErrorNodeImpl = Tree.ErrorNodeImpl;
var Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;

function ParserRuleContext(parent, invokingStateNumber) {
  parent = parent || null;
  invokingStateNumber = invokingStateNumber || null;
  RuleContext.call(this, parent, invokingStateNumber);
  this.ruleIndex = -1;
  // * If we are debugging or building a parse tree for a visitor,
  // we need to track all of the tokens and rule invocations associated
  // with this rule's context. This is empty for parsing w/o tree constr.
  // operation because we don't the need to track the details about
  // how we parse this rule.
  // /
  this.children = null;
  this.start = null;
  this.stop = null;
  // The exception that forced this rule to return. If the rule successfully
  // completed, this is {@code null}.
  this.exception = null;
}

ParserRuleContext.prototype = Object.create(RuleContext.prototype);
ParserRuleContext.prototype.constructor = ParserRuleContext;

// * COPY a ctx (I'm deliberately not using copy constructor)///
ParserRuleContext.prototype.copyFrom = function (ctx) {
  // from RuleContext
  this.parentCtx = ctx.parentCtx;
  this.invokingState = ctx.invokingState;
  this.children = null;
  this.start = ctx.start;
  this.stop = ctx.stop;
  // copy any error nodes to alt label node
  if (ctx.children) {
    this.children = [];
    // reset parent pointer for any error nodes
    ctx.children.map(function (child) {
      if (child instanceof ErrorNodeImpl) {
        this.children.push(child);
        child.parentCtx = this;
      }
    }, this);
  }
};

// Double dispatch methods for listeners
ParserRuleContext.prototype.enterRule = function (listener) {};

ParserRuleContext.prototype.exitRule = function (listener) {};

// * Does not set parent link; other add methods do that///
ParserRuleContext.prototype.addChild = function (child) {
  if (this.children === null) {
    this.children = [];
  }
  this.children.push(child);
  return child;
};

// * Used by enterOuterAlt to toss out a RuleContext previously added as
// we entered a rule. If we have // label, we will need to remove
// generic ruleContext object.
// /
ParserRuleContext.prototype.removeLastChild = function () {
  if (this.children !== null) {
    this.children.pop();
  }
};

ParserRuleContext.prototype.addTokenNode = function (token) {
  var node = new TerminalNodeImpl(token);
  this.addChild(node);
  node.parentCtx = this;
  return node;
};

ParserRuleContext.prototype.addErrorNode = function (badToken) {
  var node = new ErrorNodeImpl(badToken);
  this.addChild(node);
  node.parentCtx = this;
  return node;
};

ParserRuleContext.prototype.getChild = function (i, type) {
  type = type || null;
  if (this.children === null || i < 0 || i >= this.children.length) {
    return null;
  }
  if (type === null) {
    return this.children[i];
  } else {
    for (var j = 0; j < this.children.length; j++) {
      var child = this.children[j];
      if (child instanceof type) {
        if (i === 0) {
          return child;
        } else {
          i -= 1;
        }
      }
    }
    return null;
  }
};

ParserRuleContext.prototype.getToken = function (ttype, i) {
  if (this.children === null || i < 0 || i >= this.children.length) {
    return null;
  }
  for (var j = 0; j < this.children.length; j++) {
    var child = this.children[j];
    if (child instanceof TerminalNode) {
      if (child.symbol.type === ttype) {
        if (i === 0) {
          return child;
        } else {
          i -= 1;
        }
      }
    }
  }
  return null;
};

ParserRuleContext.prototype.getTokens = function (ttype) {
  if (this.children === null) {
    return [];
  } else {
    var tokens = [];
    for (var j = 0; j < this.children.length; j++) {
      var child = this.children[j];
      if (child instanceof TerminalNode) {
        if (child.symbol.type === ttype) {
          tokens.push(child);
        }
      }
    }
    return tokens;
  }
};

ParserRuleContext.prototype.getTypedRuleContext = function (ctxType, i) {
  return this.getChild(i, ctxType);
};

ParserRuleContext.prototype.getTypedRuleContexts = function (ctxType) {
  if (this.children === null) {
    return [];
  } else {
    var contexts = [];
    for (var j = 0; j < this.children.length; j++) {
      var child = this.children[j];
      if (child instanceof ctxType) {
        contexts.push(child);
      }
    }
    return contexts;
  }
};

ParserRuleContext.prototype.getChildCount = function () {
  if (this.children === null) {
    return 0;
  } else {
    return this.children.length;
  }
};

ParserRuleContext.prototype.getSourceInterval = function () {
  if (this.start === null || this.stop === null) {
    return INVALID_INTERVAL;
  } else {
    return new Interval(this.start.tokenIndex, this.stop.tokenIndex);
  }
};

RuleContext.EMPTY = new ParserRuleContext();

function InterpreterRuleContext(parent, invokingStateNumber, ruleIndex) {
  ParserRuleContext.call(parent, invokingStateNumber);
  this.ruleIndex = ruleIndex;
  return this;
}

InterpreterRuleContext.prototype = Object.create(ParserRuleContext.prototype);
InterpreterRuleContext.prototype.constructor = InterpreterRuleContext;

exports.ParserRuleContext = ParserRuleContext;

/***/ }),

/***/ "./node_modules/antlr4/PredictionContext.js":
/*!**************************************************!*\
  !*** ./node_modules/antlr4/PredictionContext.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

var RuleContext = __webpack_require__(/*! ./RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
var Hash = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js").Hash;

function PredictionContext(cachedHashCode) {
	this.cachedHashCode = cachedHashCode;
}

// Represents {@code $} in local context prediction, which means wildcard.
// {@code//+x =//}.
// /
PredictionContext.EMPTY = null;

// Represents {@code $} in an array in full context mode, when {@code $}
// doesn't mean wildcard: {@code $ + x = [$,x]}. Here,
// {@code $} = {@link //EMPTY_RETURN_STATE}.
// /
PredictionContext.EMPTY_RETURN_STATE = 0x7FFFFFFF;

PredictionContext.globalNodeCount = 1;
PredictionContext.id = PredictionContext.globalNodeCount;

// Stores the computed hash code of this {@link PredictionContext}. The hash
// code is computed in parts to match the following reference algorithm.
//
// <pre>
// private int referenceHashCode() {
// int hash = {@link MurmurHash//initialize MurmurHash.initialize}({@link
// //INITIAL_HASH});
//
// for (int i = 0; i &lt; {@link //size()}; i++) {
// hash = {@link MurmurHash//update MurmurHash.update}(hash, {@link //getParent
// getParent}(i));
// }
//
// for (int i = 0; i &lt; {@link //size()}; i++) {
// hash = {@link MurmurHash//update MurmurHash.update}(hash, {@link
// //getReturnState getReturnState}(i));
// }
//
// hash = {@link MurmurHash//finish MurmurHash.finish}(hash, 2// {@link
// //size()});
// return hash;
// }
// </pre>
// /

// This means only the {@link //EMPTY} context is in set.
PredictionContext.prototype.isEmpty = function () {
	return this === PredictionContext.EMPTY;
};

PredictionContext.prototype.hasEmptyPath = function () {
	return this.getReturnState(this.length - 1) === PredictionContext.EMPTY_RETURN_STATE;
};

PredictionContext.prototype.hashCode = function () {
	return this.cachedHashCode;
};

PredictionContext.prototype.updateHashCode = function (hash) {
	hash.update(this.cachedHashCode);
};
/*
function calculateHashString(parent, returnState) {
	return "" + parent + returnState;
}
*/

// Used to cache {@link PredictionContext} objects. Its used for the shared
// context cash associated with contexts in DFA states. This cache
// can be used for both lexers and parsers.

function PredictionContextCache() {
	this.cache = {};
	return this;
}

// Add a context to the cache and return it. If the context already exists,
// return that one instead and do not add a new context to the cache.
// Protect shared cache from unsafe thread access.
//
PredictionContextCache.prototype.add = function (ctx) {
	if (ctx === PredictionContext.EMPTY) {
		return PredictionContext.EMPTY;
	}
	var existing = this.cache[ctx] || null;
	if (existing !== null) {
		return existing;
	}
	this.cache[ctx] = ctx;
	return ctx;
};

PredictionContextCache.prototype.get = function (ctx) {
	return this.cache[ctx] || null;
};

Object.defineProperty(PredictionContextCache.prototype, "length", {
	get: function get() {
		return this.cache.length;
	}
});

function SingletonPredictionContext(parent, returnState) {
	var hashCode = 0;
	if (parent !== null) {
		var hash = new Hash();
		hash.update(parent, returnState);
		hashCode = hash.finish();
	}
	PredictionContext.call(this, hashCode);
	this.parentCtx = parent;
	this.returnState = returnState;
}

SingletonPredictionContext.prototype = Object.create(PredictionContext.prototype);
SingletonPredictionContext.prototype.contructor = SingletonPredictionContext;

SingletonPredictionContext.create = function (parent, returnState) {
	if (returnState === PredictionContext.EMPTY_RETURN_STATE && parent === null) {
		// someone can pass in the bits of an array ctx that mean $
		return PredictionContext.EMPTY;
	} else {
		return new SingletonPredictionContext(parent, returnState);
	}
};

Object.defineProperty(SingletonPredictionContext.prototype, "length", {
	get: function get() {
		return 1;
	}
});

SingletonPredictionContext.prototype.getParent = function (index) {
	return this.parentCtx;
};

SingletonPredictionContext.prototype.getReturnState = function (index) {
	return this.returnState;
};

SingletonPredictionContext.prototype.equals = function (other) {
	if (this === other) {
		return true;
	} else if (!(other instanceof SingletonPredictionContext)) {
		return false;
	} else if (this.hashCode() !== other.hashCode()) {
		return false; // can't be same if hash is different
	} else {
		if (this.returnState !== other.returnState) return false;else if (this.parentCtx == null) return other.parentCtx == null;else return this.parentCtx.equals(other.parentCtx);
	}
};

SingletonPredictionContext.prototype.toString = function () {
	var up = this.parentCtx === null ? "" : this.parentCtx.toString();
	if (up.length === 0) {
		if (this.returnState === PredictionContext.EMPTY_RETURN_STATE) {
			return "$";
		} else {
			return "" + this.returnState;
		}
	} else {
		return "" + this.returnState + " " + up;
	}
};

function EmptyPredictionContext() {
	SingletonPredictionContext.call(this, null, PredictionContext.EMPTY_RETURN_STATE);
	return this;
}

EmptyPredictionContext.prototype = Object.create(SingletonPredictionContext.prototype);
EmptyPredictionContext.prototype.constructor = EmptyPredictionContext;

EmptyPredictionContext.prototype.isEmpty = function () {
	return true;
};

EmptyPredictionContext.prototype.getParent = function (index) {
	return null;
};

EmptyPredictionContext.prototype.getReturnState = function (index) {
	return this.returnState;
};

EmptyPredictionContext.prototype.equals = function (other) {
	return this === other;
};

EmptyPredictionContext.prototype.toString = function () {
	return "$";
};

PredictionContext.EMPTY = new EmptyPredictionContext();

function ArrayPredictionContext(parents, returnStates) {
	// Parent can be null only if full ctx mode and we make an array
	// from {@link //EMPTY} and non-empty. We merge {@link //EMPTY} by using
	// null parent and
	// returnState == {@link //EMPTY_RETURN_STATE}.
	var h = new Hash();
	h.update(parents, returnStates);
	var hashCode = h.finish();
	PredictionContext.call(this, hashCode);
	this.parents = parents;
	this.returnStates = returnStates;
	return this;
}

ArrayPredictionContext.prototype = Object.create(PredictionContext.prototype);
ArrayPredictionContext.prototype.constructor = ArrayPredictionContext;

ArrayPredictionContext.prototype.isEmpty = function () {
	// since EMPTY_RETURN_STATE can only appear in the last position, we
	// don't need to verify that size==1
	return this.returnStates[0] === PredictionContext.EMPTY_RETURN_STATE;
};

Object.defineProperty(ArrayPredictionContext.prototype, "length", {
	get: function get() {
		return this.returnStates.length;
	}
});

ArrayPredictionContext.prototype.getParent = function (index) {
	return this.parents[index];
};

ArrayPredictionContext.prototype.getReturnState = function (index) {
	return this.returnStates[index];
};

ArrayPredictionContext.prototype.equals = function (other) {
	if (this === other) {
		return true;
	} else if (!(other instanceof ArrayPredictionContext)) {
		return false;
	} else if (this.hashCode() !== other.hashCode()) {
		return false; // can't be same if hash is different
	} else {
		return this.returnStates === other.returnStates && this.parents === other.parents;
	}
};

ArrayPredictionContext.prototype.toString = function () {
	if (this.isEmpty()) {
		return "[]";
	} else {
		var s = "[";
		for (var i = 0; i < this.returnStates.length; i++) {
			if (i > 0) {
				s = s + ", ";
			}
			if (this.returnStates[i] === PredictionContext.EMPTY_RETURN_STATE) {
				s = s + "$";
				continue;
			}
			s = s + this.returnStates[i];
			if (this.parents[i] !== null) {
				s = s + " " + this.parents[i];
			} else {
				s = s + "null";
			}
		}
		return s + "]";
	}
};

// Convert a {@link RuleContext} tree to a {@link PredictionContext} graph.
// Return {@link //EMPTY} if {@code outerContext} is empty or null.
// /
function predictionContextFromRuleContext(atn, outerContext) {
	if (outerContext === undefined || outerContext === null) {
		outerContext = RuleContext.EMPTY;
	}
	// if we are in RuleContext of start rule, s, then PredictionContext
	// is EMPTY. Nobody called us. (if we are empty, return empty)
	if (outerContext.parentCtx === null || outerContext === RuleContext.EMPTY) {
		return PredictionContext.EMPTY;
	}
	// If we have a parent, convert it to a PredictionContext graph
	var parent = predictionContextFromRuleContext(atn, outerContext.parentCtx);
	var state = atn.states[outerContext.invokingState];
	var transition = state.transitions[0];
	return SingletonPredictionContext.create(parent, transition.followState.stateNumber);
}
/*
function calculateListsHashString(parents, returnStates) {
	var s = "";
	parents.map(function(p) {
		s = s + p;
	});
	returnStates.map(function(r) {
		s = s + r;
	});
	return s;
}
*/
function merge(a, b, rootIsWildcard, mergeCache) {
	// share same graph if both same
	if (a === b) {
		return a;
	}
	if (a instanceof SingletonPredictionContext && b instanceof SingletonPredictionContext) {
		return mergeSingletons(a, b, rootIsWildcard, mergeCache);
	}
	// At least one of a or b is array
	// If one is $ and rootIsWildcard, return $ as// wildcard
	if (rootIsWildcard) {
		if (a instanceof EmptyPredictionContext) {
			return a;
		}
		if (b instanceof EmptyPredictionContext) {
			return b;
		}
	}
	// convert singleton so both are arrays to normalize
	if (a instanceof SingletonPredictionContext) {
		a = new ArrayPredictionContext([a.getParent()], [a.returnState]);
	}
	if (b instanceof SingletonPredictionContext) {
		b = new ArrayPredictionContext([b.getParent()], [b.returnState]);
	}
	return mergeArrays(a, b, rootIsWildcard, mergeCache);
}

//
// Merge two {@link SingletonPredictionContext} instances.
//
// <p>Stack tops equal, parents merge is same; return left graph.<br>
// <embed src="images/SingletonMerge_SameRootSamePar.svg"
// type="image/svg+xml"/></p>
//
// <p>Same stack top, parents differ; merge parents giving array node, then
// remainders of those graphs. A new root node is created to point to the
// merged parents.<br>
// <embed src="images/SingletonMerge_SameRootDiffPar.svg"
// type="image/svg+xml"/></p>
//
// <p>Different stack tops pointing to same parent. Make array node for the
// root where both element in the root point to the same (original)
// parent.<br>
// <embed src="images/SingletonMerge_DiffRootSamePar.svg"
// type="image/svg+xml"/></p>
//
// <p>Different stack tops pointing to different parents. Make array node for
// the root where each element points to the corresponding original
// parent.<br>
// <embed src="images/SingletonMerge_DiffRootDiffPar.svg"
// type="image/svg+xml"/></p>
//
// @param a the first {@link SingletonPredictionContext}
// @param b the second {@link SingletonPredictionContext}
// @param rootIsWildcard {@code true} if this is a local-context merge,
// otherwise false to indicate a full-context merge
// @param mergeCache
// /
function mergeSingletons(a, b, rootIsWildcard, mergeCache) {
	if (mergeCache !== null) {
		var previous = mergeCache.get(a, b);
		if (previous !== null) {
			return previous;
		}
		previous = mergeCache.get(b, a);
		if (previous !== null) {
			return previous;
		}
	}

	var rootMerge = mergeRoot(a, b, rootIsWildcard);
	if (rootMerge !== null) {
		if (mergeCache !== null) {
			mergeCache.set(a, b, rootMerge);
		}
		return rootMerge;
	}
	if (a.returnState === b.returnState) {
		var parent = merge(a.parentCtx, b.parentCtx, rootIsWildcard, mergeCache);
		// if parent is same as existing a or b parent or reduced to a parent,
		// return it
		if (parent === a.parentCtx) {
			return a; // ax + bx = ax, if a=b
		}
		if (parent === b.parentCtx) {
			return b; // ax + bx = bx, if a=b
		}
		// else: ax + ay = a'[x,y]
		// merge parents x and y, giving array node with x,y then remainders
		// of those graphs. dup a, a' points at merged array
		// new joined parent so create new singleton pointing to it, a'
		var spc = SingletonPredictionContext.create(parent, a.returnState);
		if (mergeCache !== null) {
			mergeCache.set(a, b, spc);
		}
		return spc;
	} else {
		// a != b payloads differ
		// see if we can collapse parents due to $+x parents if local ctx
		var singleParent = null;
		if (a === b || a.parentCtx !== null && a.parentCtx === b.parentCtx) {
			// ax +
			// bx =
			// [a,b]x
			singleParent = a.parentCtx;
		}
		if (singleParent !== null) {
			// parents are same
			// sort payloads and use same parent
			var payloads = [a.returnState, b.returnState];
			if (a.returnState > b.returnState) {
				payloads[0] = b.returnState;
				payloads[1] = a.returnState;
			}
			var parents = [singleParent, singleParent];
			var apc = new ArrayPredictionContext(parents, payloads);
			if (mergeCache !== null) {
				mergeCache.set(a, b, apc);
			}
			return apc;
		}
		// parents differ and can't merge them. Just pack together
		// into array; can't merge.
		// ax + by = [ax,by]
		var payloads = [a.returnState, b.returnState];
		var parents = [a.parentCtx, b.parentCtx];
		if (a.returnState > b.returnState) {
			// sort by payload
			payloads[0] = b.returnState;
			payloads[1] = a.returnState;
			parents = [b.parentCtx, a.parentCtx];
		}
		var a_ = new ArrayPredictionContext(parents, payloads);
		if (mergeCache !== null) {
			mergeCache.set(a, b, a_);
		}
		return a_;
	}
}

//
// Handle case where at least one of {@code a} or {@code b} is
// {@link //EMPTY}. In the following diagrams, the symbol {@code $} is used
// to represent {@link //EMPTY}.
//
// <h2>Local-Context Merges</h2>
//
// <p>These local-context merge operations are used when {@code rootIsWildcard}
// is true.</p>
//
// <p>{@link //EMPTY} is superset of any graph; return {@link //EMPTY}.<br>
// <embed src="images/LocalMerge_EmptyRoot.svg" type="image/svg+xml"/></p>
//
// <p>{@link //EMPTY} and anything is {@code //EMPTY}, so merged parent is
// {@code //EMPTY}; return left graph.<br>
// <embed src="images/LocalMerge_EmptyParent.svg" type="image/svg+xml"/></p>
//
// <p>Special case of last merge if local context.<br>
// <embed src="images/LocalMerge_DiffRoots.svg" type="image/svg+xml"/></p>
//
// <h2>Full-Context Merges</h2>
//
// <p>These full-context merge operations are used when {@code rootIsWildcard}
// is false.</p>
//
// <p><embed src="images/FullMerge_EmptyRoots.svg" type="image/svg+xml"/></p>
//
// <p>Must keep all contexts; {@link //EMPTY} in array is a special value (and
// null parent).<br>
// <embed src="images/FullMerge_EmptyRoot.svg" type="image/svg+xml"/></p>
//
// <p><embed src="images/FullMerge_SameRoot.svg" type="image/svg+xml"/></p>
//
// @param a the first {@link SingletonPredictionContext}
// @param b the second {@link SingletonPredictionContext}
// @param rootIsWildcard {@code true} if this is a local-context merge,
// otherwise false to indicate a full-context merge
// /
function mergeRoot(a, b, rootIsWildcard) {
	if (rootIsWildcard) {
		if (a === PredictionContext.EMPTY) {
			return PredictionContext.EMPTY; // // + b =//
		}
		if (b === PredictionContext.EMPTY) {
			return PredictionContext.EMPTY; // a +// =//
		}
	} else {
		if (a === PredictionContext.EMPTY && b === PredictionContext.EMPTY) {
			return PredictionContext.EMPTY; // $ + $ = $
		} else if (a === PredictionContext.EMPTY) {
			// $ + x = [$,x]
			var payloads = [b.returnState, PredictionContext.EMPTY_RETURN_STATE];
			var parents = [b.parentCtx, null];
			return new ArrayPredictionContext(parents, payloads);
		} else if (b === PredictionContext.EMPTY) {
			// x + $ = [$,x] ($ is always first if present)
			var payloads = [a.returnState, PredictionContext.EMPTY_RETURN_STATE];
			var parents = [a.parentCtx, null];
			return new ArrayPredictionContext(parents, payloads);
		}
	}
	return null;
}

//
// Merge two {@link ArrayPredictionContext} instances.
//
// <p>Different tops, different parents.<br>
// <embed src="images/ArrayMerge_DiffTopDiffPar.svg" type="image/svg+xml"/></p>
//
// <p>Shared top, same parents.<br>
// <embed src="images/ArrayMerge_ShareTopSamePar.svg" type="image/svg+xml"/></p>
//
// <p>Shared top, different parents.<br>
// <embed src="images/ArrayMerge_ShareTopDiffPar.svg" type="image/svg+xml"/></p>
//
// <p>Shared top, all shared parents.<br>
// <embed src="images/ArrayMerge_ShareTopSharePar.svg"
// type="image/svg+xml"/></p>
//
// <p>Equal tops, merge parents and reduce top to
// {@link SingletonPredictionContext}.<br>
// <embed src="images/ArrayMerge_EqualTop.svg" type="image/svg+xml"/></p>
// /
function mergeArrays(a, b, rootIsWildcard, mergeCache) {
	if (mergeCache !== null) {
		var previous = mergeCache.get(a, b);
		if (previous !== null) {
			return previous;
		}
		previous = mergeCache.get(b, a);
		if (previous !== null) {
			return previous;
		}
	}
	// merge sorted payloads a + b => M
	var i = 0; // walks a
	var j = 0; // walks b
	var k = 0; // walks target M array

	var mergedReturnStates = [];
	var mergedParents = [];
	// walk and merge to yield mergedParents, mergedReturnStates
	while (i < a.returnStates.length && j < b.returnStates.length) {
		var a_parent = a.parents[i];
		var b_parent = b.parents[j];
		if (a.returnStates[i] === b.returnStates[j]) {
			// same payload (stack tops are equal), must yield merged singleton
			var payload = a.returnStates[i];
			// $+$ = $
			var bothDollars = payload === PredictionContext.EMPTY_RETURN_STATE && a_parent === null && b_parent === null;
			var ax_ax = a_parent !== null && b_parent !== null && a_parent === b_parent; // ax+ax
			// ->
			// ax
			if (bothDollars || ax_ax) {
				mergedParents[k] = a_parent; // choose left
				mergedReturnStates[k] = payload;
			} else {
				// ax+ay -> a'[x,y]
				var mergedParent = merge(a_parent, b_parent, rootIsWildcard, mergeCache);
				mergedParents[k] = mergedParent;
				mergedReturnStates[k] = payload;
			}
			i += 1; // hop over left one as usual
			j += 1; // but also skip one in right side since we merge
		} else if (a.returnStates[i] < b.returnStates[j]) {
			// copy a[i] to M
			mergedParents[k] = a_parent;
			mergedReturnStates[k] = a.returnStates[i];
			i += 1;
		} else {
			// b > a, copy b[j] to M
			mergedParents[k] = b_parent;
			mergedReturnStates[k] = b.returnStates[j];
			j += 1;
		}
		k += 1;
	}
	// copy over any payloads remaining in either array
	if (i < a.returnStates.length) {
		for (var p = i; p < a.returnStates.length; p++) {
			mergedParents[k] = a.parents[p];
			mergedReturnStates[k] = a.returnStates[p];
			k += 1;
		}
	} else {
		for (var p = j; p < b.returnStates.length; p++) {
			mergedParents[k] = b.parents[p];
			mergedReturnStates[k] = b.returnStates[p];
			k += 1;
		}
	}
	// trim merged if we combined a few that had same stack tops
	if (k < mergedParents.length) {
		// write index < last position; trim
		if (k === 1) {
			// for just one merged element, return singleton top
			var a_ = SingletonPredictionContext.create(mergedParents[0], mergedReturnStates[0]);
			if (mergeCache !== null) {
				mergeCache.set(a, b, a_);
			}
			return a_;
		}
		mergedParents = mergedParents.slice(0, k);
		mergedReturnStates = mergedReturnStates.slice(0, k);
	}

	var M = new ArrayPredictionContext(mergedParents, mergedReturnStates);

	// if we created same array as a or b, return that instead
	// TODO: track whether this is possible above during merge sort for speed
	if (M === a) {
		if (mergeCache !== null) {
			mergeCache.set(a, b, a);
		}
		return a;
	}
	if (M === b) {
		if (mergeCache !== null) {
			mergeCache.set(a, b, b);
		}
		return b;
	}
	combineCommonParents(mergedParents);

	if (mergeCache !== null) {
		mergeCache.set(a, b, M);
	}
	return M;
}

//
// Make pass over all <em>M</em> {@code parents}; merge any {@code equals()}
// ones.
// /
function combineCommonParents(parents) {
	var uniqueParents = {};

	for (var p = 0; p < parents.length; p++) {
		var parent = parents[p];
		if (!(parent in uniqueParents)) {
			uniqueParents[parent] = parent;
		}
	}
	for (var q = 0; q < parents.length; q++) {
		parents[q] = uniqueParents[parents[q]];
	}
}

function getCachedPredictionContext(context, contextCache, visited) {
	if (context.isEmpty()) {
		return context;
	}
	var existing = visited[context] || null;
	if (existing !== null) {
		return existing;
	}
	existing = contextCache.get(context);
	if (existing !== null) {
		visited[context] = existing;
		return existing;
	}
	var changed = false;
	var parents = [];
	for (var i = 0; i < parents.length; i++) {
		var parent = getCachedPredictionContext(context.getParent(i), contextCache, visited);
		if (changed || parent !== context.getParent(i)) {
			if (!changed) {
				parents = [];
				for (var j = 0; j < context.length; j++) {
					parents[j] = context.getParent(j);
				}
				changed = true;
			}
			parents[i] = parent;
		}
	}
	if (!changed) {
		contextCache.add(context);
		visited[context] = context;
		return context;
	}
	var updated = null;
	if (parents.length === 0) {
		updated = PredictionContext.EMPTY;
	} else if (parents.length === 1) {
		updated = SingletonPredictionContext.create(parents[0], context.getReturnState(0));
	} else {
		updated = new ArrayPredictionContext(parents, context.returnStates);
	}
	contextCache.add(updated);
	visited[updated] = updated;
	visited[context] = updated;

	return updated;
}

// ter's recursive version of Sam's getAllNodes()
function getAllContextNodes(context, nodes, visited) {
	if (nodes === null) {
		nodes = [];
		return getAllContextNodes(context, nodes, visited);
	} else if (visited === null) {
		visited = {};
		return getAllContextNodes(context, nodes, visited);
	} else {
		if (context === null || visited[context] !== null) {
			return nodes;
		}
		visited[context] = context;
		nodes.push(context);
		for (var i = 0; i < context.length; i++) {
			getAllContextNodes(context.getParent(i), nodes, visited);
		}
		return nodes;
	}
}

exports.merge = merge;
exports.PredictionContext = PredictionContext;
exports.PredictionContextCache = PredictionContextCache;
exports.SingletonPredictionContext = SingletonPredictionContext;
exports.predictionContextFromRuleContext = predictionContextFromRuleContext;
exports.getCachedPredictionContext = getCachedPredictionContext;

/***/ }),

/***/ "./node_modules/antlr4/Recognizer.js":
/*!*******************************************!*\
  !*** ./node_modules/antlr4/Recognizer.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
var ConsoleErrorListener = __webpack_require__(/*! ./error/ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ConsoleErrorListener;
var ProxyErrorListener = __webpack_require__(/*! ./error/ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ProxyErrorListener;

function Recognizer() {
    this._listeners = [ConsoleErrorListener.INSTANCE];
    this._interp = null;
    this._stateNumber = -1;
    return this;
}

Recognizer.tokenTypeMapCache = {};
Recognizer.ruleIndexMapCache = {};

Recognizer.prototype.checkVersion = function (toolVersion) {
    var runtimeVersion = "4.7.1";
    if (runtimeVersion !== toolVersion) {
        console.log("ANTLR runtime and generated code versions disagree: " + runtimeVersion + "!=" + toolVersion);
    }
};

Recognizer.prototype.addErrorListener = function (listener) {
    this._listeners.push(listener);
};

Recognizer.prototype.removeErrorListeners = function () {
    this._listeners = [];
};

Recognizer.prototype.getTokenTypeMap = function () {
    var tokenNames = this.getTokenNames();
    if (tokenNames === null) {
        throw "The current recognizer does not provide a list of token names.";
    }
    var result = this.tokenTypeMapCache[tokenNames];
    if (result === undefined) {
        result = tokenNames.reduce(function (o, k, i) {
            o[k] = i;
        });
        result.EOF = Token.EOF;
        this.tokenTypeMapCache[tokenNames] = result;
    }
    return result;
};

// Get a map from rule names to rule indexes.
//
// <p>Used for XPath and tree pattern compilation.</p>
//
Recognizer.prototype.getRuleIndexMap = function () {
    var ruleNames = this.ruleNames;
    if (ruleNames === null) {
        throw "The current recognizer does not provide a list of rule names.";
    }
    var result = this.ruleIndexMapCache[ruleNames];
    if (result === undefined) {
        result = ruleNames.reduce(function (o, k, i) {
            o[k] = i;
        });
        this.ruleIndexMapCache[ruleNames] = result;
    }
    return result;
};

Recognizer.prototype.getTokenType = function (tokenName) {
    var ttype = this.getTokenTypeMap()[tokenName];
    if (ttype !== undefined) {
        return ttype;
    } else {
        return Token.INVALID_TYPE;
    }
};

// What is the error header, normally line/character position information?//
Recognizer.prototype.getErrorHeader = function (e) {
    var line = e.getOffendingToken().line;
    var column = e.getOffendingToken().column;
    return "line " + line + ":" + column;
};

// How should a token be displayed in an error message? The default
//  is to display just the text, but during development you might
//  want to have a lot of information spit out.  Override in that case
//  to use t.toString() (which, for CommonToken, dumps everything about
//  the token). This is better than forcing you to override a method in
//  your token objects because you don't have to go modify your lexer
//  so that it creates a new Java type.
//
// @deprecated This method is not called by the ANTLR 4 Runtime. Specific
// implementations of {@link ANTLRErrorStrategy} may provide a similar
// feature when necessary. For example, see
// {@link DefaultErrorStrategy//getTokenErrorDisplay}.
//
Recognizer.prototype.getTokenErrorDisplay = function (t) {
    if (t === null) {
        return "<no token>";
    }
    var s = t.text;
    if (s === null) {
        if (t.type === Token.EOF) {
            s = "<EOF>";
        } else {
            s = "<" + t.type + ">";
        }
    }
    s = s.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
    return "'" + s + "'";
};

Recognizer.prototype.getErrorListenerDispatch = function () {
    return new ProxyErrorListener(this._listeners);
};

// subclass needs to override these if there are sempreds or actions
// that the ATN interp needs to execute
Recognizer.prototype.sempred = function (localctx, ruleIndex, actionIndex) {
    return true;
};

Recognizer.prototype.precpred = function (localctx, precedence) {
    return true;
};

//Indicate that the recognizer has changed internal state that is
//consistent with the ATN state passed in.  This way we always know
//where we are in the ATN as the parser goes along. The rule
//context objects form a stack that lets us see the stack of
//invoking rules. Combine this and we have complete ATN
//configuration information.

Object.defineProperty(Recognizer.prototype, "state", {
    get: function get() {
        return this._stateNumber;
    },
    set: function set(state) {
        this._stateNumber = state;
    }
});

exports.Recognizer = Recognizer;

/***/ }),

/***/ "./node_modules/antlr4/RuleContext.js":
/*!********************************************!*\
  !*** ./node_modules/antlr4/RuleContext.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

//  A rule context is a record of a single rule invocation. It knows
//  which context invoked it, if any. If there is no parent context, then
//  naturally the invoking state is not valid.  The parent link
//  provides a chain upwards from the current rule invocation to the root
//  of the invocation tree, forming a stack. We actually carry no
//  information about the rule associated with this context (except
//  when parsing). We keep only the state number of the invoking state from
//  the ATN submachine that invoked this. Contrast this with the s
//  pointer inside ParserRuleContext that tracks the current state
//  being "executed" for the current rule.
//
//  The parent contexts are useful for computing lookahead sets and
//  getting error information.
//
//  These objects are used during parsing and prediction.
//  For the special case of parsers, we use the subclass
//  ParserRuleContext.
//
//  @see ParserRuleContext
///

var RuleNode = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").RuleNode;
var INVALID_INTERVAL = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").INVALID_INTERVAL;
var INVALID_ALT_NUMBER = __webpack_require__(/*! ./atn/ATN */ "./node_modules/antlr4/atn/ATN.js").INVALID_ALT_NUMBER;

function RuleContext(parent, invokingState) {
	RuleNode.call(this);
	// What context invoked this rule?
	this.parentCtx = parent || null;
	// What state invoked the rule associated with this context?
	// The "return address" is the followState of invokingState
	// If parent is null, this should be -1.
	this.invokingState = invokingState || -1;
	return this;
}

RuleContext.prototype = Object.create(RuleNode.prototype);
RuleContext.prototype.constructor = RuleContext;

RuleContext.prototype.depth = function () {
	var n = 0;
	var p = this;
	while (p !== null) {
		p = p.parentCtx;
		n += 1;
	}
	return n;
};

// A context is empty if there is no invoking state; meaning nobody call
// current context.
RuleContext.prototype.isEmpty = function () {
	return this.invokingState === -1;
};

// satisfy the ParseTree / SyntaxTree interface

RuleContext.prototype.getSourceInterval = function () {
	return INVALID_INTERVAL;
};

RuleContext.prototype.getRuleContext = function () {
	return this;
};

RuleContext.prototype.getPayload = function () {
	return this;
};

// Return the combined text of all child nodes. This method only considers
// tokens which have been added to the parse tree.
// <p>
// Since tokens on hidden channels (e.g. whitespace or comments) are not
// added to the parse trees, they will not appear in the output of this
// method.
// /
RuleContext.prototype.getText = function () {
	if (this.getChildCount() === 0) {
		return "";
	} else {
		return this.children.map(function (child) {
			return child.getText();
		}).join("");
	}
};

// For rule associated with this parse tree internal node, return
// the outer alternative number used to match the input. Default
// implementation does not compute nor store this alt num. Create
// a subclass of ParserRuleContext with backing field and set
// option contextSuperClass.
// to set it.
RuleContext.prototype.getAltNumber = function () {
	return INVALID_ALT_NUMBER;
};

// Set the outer alternative number for this context node. Default
// implementation does nothing to avoid backing field overhead for
// trees that don't need it.  Create
// a subclass of ParserRuleContext with backing field and set
// option contextSuperClass.
RuleContext.prototype.setAltNumber = function (altNumber) {};

RuleContext.prototype.getChild = function (i) {
	return null;
};

RuleContext.prototype.getChildCount = function () {
	return 0;
};

RuleContext.prototype.accept = function (visitor) {
	return visitor.visitChildren(this);
};

//need to manage circular dependencies, so export now
exports.RuleContext = RuleContext;
var Trees = __webpack_require__(/*! ./tree/Trees */ "./node_modules/antlr4/tree/Trees.js").Trees;

// Print out a whole tree, not just a node, in LISP format
// (root child1 .. childN). Print just a node if this is a leaf.
//

RuleContext.prototype.toStringTree = function (ruleNames, recog) {
	return Trees.toStringTree(this, ruleNames, recog);
};

RuleContext.prototype.toString = function (ruleNames, stop) {
	ruleNames = ruleNames || null;
	stop = stop || null;
	var p = this;
	var s = "[";
	while (p !== null && p !== stop) {
		if (ruleNames === null) {
			if (!p.isEmpty()) {
				s += p.invokingState;
			}
		} else {
			var ri = p.ruleIndex;
			var ruleName = ri >= 0 && ri < ruleNames.length ? ruleNames[ri] : "" + ri;
			s += ruleName;
		}
		if (p.parentCtx !== null && (ruleNames !== null || !p.parentCtx.isEmpty())) {
			s += " ";
		}
		p = p.parentCtx;
	}
	s += "]";
	return s;
};

/***/ }),

/***/ "./node_modules/antlr4/Token.js":
/*!**************************************!*\
  !*** ./node_modules/antlr4/Token.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

// A token has properties: text, type, line, character position in the line
// (so we can ignore tabs), token channel, index, and source from which
// we obtained this token.

function Token() {
	this.source = null;
	this.type = null; // token type of the token
	this.channel = null; // The parser ignores everything not on DEFAULT_CHANNEL
	this.start = null; // optional; return -1 if not implemented.
	this.stop = null; // optional; return -1 if not implemented.
	this.tokenIndex = null; // from 0..n-1 of the token object in the input stream
	this.line = null; // line=1..n of the 1st character
	this.column = null; // beginning of the line at which it occurs, 0..n-1
	this._text = null; // text of the token.
	return this;
}

Token.INVALID_TYPE = 0;

// During lookahead operations, this "token" signifies we hit rule end ATN state
// and did not follow it despite needing to.
Token.EPSILON = -2;

Token.MIN_USER_TOKEN_TYPE = 1;

Token.EOF = -1;

// All tokens go to the parser (unless skip() is called in that rule)
// on a particular "channel". The parser tunes to a particular channel
// so that whitespace etc... can go to the parser on a "hidden" channel.

Token.DEFAULT_CHANNEL = 0;

// Anything on different channel than DEFAULT_CHANNEL is not parsed
// by parser.

Token.HIDDEN_CHANNEL = 1;

// Explicitly set the text for this token. If {code text} is not
// {@code null}, then {@link //getText} will return this value rather than
// extracting the text from the input.
//
// @param text The explicit text of the token, or {@code null} if the text
// should be obtained from the input along with the start and stop indexes
// of the token.

Object.defineProperty(Token.prototype, "text", {
	get: function get() {
		return this._text;
	},
	set: function set(text) {
		this._text = text;
	}
});

Token.prototype.getTokenSource = function () {
	return this.source[0];
};

Token.prototype.getInputStream = function () {
	return this.source[1];
};

function CommonToken(source, type, channel, start, stop) {
	Token.call(this);
	this.source = source !== undefined ? source : CommonToken.EMPTY_SOURCE;
	this.type = type !== undefined ? type : null;
	this.channel = channel !== undefined ? channel : Token.DEFAULT_CHANNEL;
	this.start = start !== undefined ? start : -1;
	this.stop = stop !== undefined ? stop : -1;
	this.tokenIndex = -1;
	if (this.source[0] !== null) {
		this.line = source[0].line;
		this.column = source[0].column;
	} else {
		this.column = -1;
	}
	return this;
}

CommonToken.prototype = Object.create(Token.prototype);
CommonToken.prototype.constructor = CommonToken;

// An empty {@link Pair} which is used as the default value of
// {@link //source} for tokens that do not have a source.
CommonToken.EMPTY_SOURCE = [null, null];

// Constructs a new {@link CommonToken} as a copy of another {@link Token}.
//
// <p>
// If {@code oldToken} is also a {@link CommonToken} instance, the newly
// constructed token will share a reference to the {@link //text} field and
// the {@link Pair} stored in {@link //source}. Otherwise, {@link //text} will
// be assigned the result of calling {@link //getText}, and {@link //source}
// will be constructed from the result of {@link Token//getTokenSource} and
// {@link Token//getInputStream}.</p>
//
// @param oldToken The token to copy.
//
CommonToken.prototype.clone = function () {
	var t = new CommonToken(this.source, this.type, this.channel, this.start, this.stop);
	t.tokenIndex = this.tokenIndex;
	t.line = this.line;
	t.column = this.column;
	t.text = this.text;
	return t;
};

Object.defineProperty(CommonToken.prototype, "text", {
	get: function get() {
		if (this._text !== null) {
			return this._text;
		}
		var input = this.getInputStream();
		if (input === null) {
			return null;
		}
		var n = input.size;
		if (this.start < n && this.stop < n) {
			return input.getText(this.start, this.stop);
		} else {
			return "<EOF>";
		}
	},
	set: function set(text) {
		this._text = text;
	}
});

CommonToken.prototype.toString = function () {
	var txt = this.text;
	if (txt !== null) {
		txt = txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
	} else {
		txt = "<no text>";
	}
	return "[@" + this.tokenIndex + "," + this.start + ":" + this.stop + "='" + txt + "',<" + this.type + ">" + (this.channel > 0 ? ",channel=" + this.channel : "") + "," + this.line + ":" + this.column + "]";
};

exports.Token = Token;
exports.CommonToken = CommonToken;

/***/ }),

/***/ "./node_modules/antlr4/Utils.js":
/*!**************************************!*\
  !*** ./node_modules/antlr4/Utils.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

function arrayToString(a) {
    return "[" + a.join(", ") + "]";
}

String.prototype.seed = String.prototype.seed || Math.round(Math.random() * Math.pow(2, 32));

String.prototype.hashCode = function () {
    var remainder,
        bytes,
        h1,
        h1b,
        c1,
        c1b,
        c2,
        c2b,
        k1,
        i,
        key = this.toString();

    remainder = key.length & 3; // key.length % 4
    bytes = key.length - remainder;
    h1 = String.prototype.seed;
    c1 = 0xcc9e2d51;
    c2 = 0x1b873593;
    i = 0;

    while (i < bytes) {
        k1 = key.charCodeAt(i) & 0xff | (key.charCodeAt(++i) & 0xff) << 8 | (key.charCodeAt(++i) & 0xff) << 16 | (key.charCodeAt(++i) & 0xff) << 24;
        ++i;

        k1 = (k1 & 0xffff) * c1 + (((k1 >>> 16) * c1 & 0xffff) << 16) & 0xffffffff;
        k1 = k1 << 15 | k1 >>> 17;
        k1 = (k1 & 0xffff) * c2 + (((k1 >>> 16) * c2 & 0xffff) << 16) & 0xffffffff;

        h1 ^= k1;
        h1 = h1 << 13 | h1 >>> 19;
        h1b = (h1 & 0xffff) * 5 + (((h1 >>> 16) * 5 & 0xffff) << 16) & 0xffffffff;
        h1 = (h1b & 0xffff) + 0x6b64 + (((h1b >>> 16) + 0xe654 & 0xffff) << 16);
    }

    k1 = 0;

    switch (remainder) {
        case 3:
            k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
        case 2:
            k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
        case 1:
            k1 ^= key.charCodeAt(i) & 0xff;

            k1 = (k1 & 0xffff) * c1 + (((k1 >>> 16) * c1 & 0xffff) << 16) & 0xffffffff;
            k1 = k1 << 15 | k1 >>> 17;
            k1 = (k1 & 0xffff) * c2 + (((k1 >>> 16) * c2 & 0xffff) << 16) & 0xffffffff;
            h1 ^= k1;
    }

    h1 ^= key.length;

    h1 ^= h1 >>> 16;
    h1 = (h1 & 0xffff) * 0x85ebca6b + (((h1 >>> 16) * 0x85ebca6b & 0xffff) << 16) & 0xffffffff;
    h1 ^= h1 >>> 13;
    h1 = (h1 & 0xffff) * 0xc2b2ae35 + (((h1 >>> 16) * 0xc2b2ae35 & 0xffff) << 16) & 0xffffffff;
    h1 ^= h1 >>> 16;

    return h1 >>> 0;
};

function standardEqualsFunction(a, b) {
    return a.equals(b);
}

function standardHashCodeFunction(a) {
    return a.hashCode();
}

function Set(hashFunction, equalsFunction) {
    this.data = {};
    this.hashFunction = hashFunction || standardHashCodeFunction;
    this.equalsFunction = equalsFunction || standardEqualsFunction;
    return this;
}

Object.defineProperty(Set.prototype, "length", {
    get: function get() {
        var l = 0;
        for (var key in this.data) {
            if (key.indexOf("hash_") === 0) {
                l = l + this.data[key].length;
            }
        }
        return l;
    }
});

Set.prototype.add = function (value) {
    var hash = this.hashFunction(value);
    var key = "hash_" + hash;
    if (key in this.data) {
        var values = this.data[key];
        for (var i = 0; i < values.length; i++) {
            if (this.equalsFunction(value, values[i])) {
                return values[i];
            }
        }
        values.push(value);
        return value;
    } else {
        this.data[key] = [value];
        return value;
    }
};

Set.prototype.contains = function (value) {
    return this.get(value) != null;
};

Set.prototype.get = function (value) {
    var hash = this.hashFunction(value);
    var key = "hash_" + hash;
    if (key in this.data) {
        var values = this.data[key];
        for (var i = 0; i < values.length; i++) {
            if (this.equalsFunction(value, values[i])) {
                return values[i];
            }
        }
    }
    return null;
};

Set.prototype.values = function () {
    var l = [];
    for (var key in this.data) {
        if (key.indexOf("hash_") === 0) {
            l = l.concat(this.data[key]);
        }
    }
    return l;
};

Set.prototype.toString = function () {
    return arrayToString(this.values());
};

function BitSet() {
    this.data = [];
    return this;
}

BitSet.prototype.add = function (value) {
    this.data[value] = true;
};

BitSet.prototype.or = function (set) {
    var bits = this;
    Object.keys(set.data).map(function (alt) {
        bits.add(alt);
    });
};

BitSet.prototype.remove = function (value) {
    delete this.data[value];
};

BitSet.prototype.contains = function (value) {
    return this.data[value] === true;
};

BitSet.prototype.values = function () {
    return Object.keys(this.data);
};

BitSet.prototype.minValue = function () {
    return Math.min.apply(null, this.values());
};

BitSet.prototype.hashCode = function () {
    var hash = new Hash();
    hash.update(this.values());
    return hash.finish();
};

BitSet.prototype.equals = function (other) {
    if (!(other instanceof BitSet)) {
        return false;
    }
    return this.hashCode() === other.hashCode();
};

Object.defineProperty(BitSet.prototype, "length", {
    get: function get() {
        return this.values().length;
    }
});

BitSet.prototype.toString = function () {
    return "{" + this.values().join(", ") + "}";
};

function Map(hashFunction, equalsFunction) {
    this.data = {};
    this.hashFunction = hashFunction || standardHashCodeFunction;
    this.equalsFunction = equalsFunction || standardEqualsFunction;
    return this;
}

Object.defineProperty(Map.prototype, "length", {
    get: function get() {
        var l = 0;
        for (var hashKey in this.data) {
            if (hashKey.indexOf("hash_") === 0) {
                l = l + this.data[hashKey].length;
            }
        }
        return l;
    }
});

Map.prototype.put = function (key, value) {
    var hashKey = "hash_" + this.hashFunction(key);
    if (hashKey in this.data) {
        var entries = this.data[hashKey];
        for (var i = 0; i < entries.length; i++) {
            var entry = entries[i];
            if (this.equalsFunction(key, entry.key)) {
                var oldValue = entry.value;
                entry.value = value;
                return oldValue;
            }
        }
        entries.push({ key: key, value: value });
        return value;
    } else {
        this.data[hashKey] = [{ key: key, value: value }];
        return value;
    }
};

Map.prototype.containsKey = function (key) {
    var hashKey = "hash_" + this.hashFunction(key);
    if (hashKey in this.data) {
        var entries = this.data[hashKey];
        for (var i = 0; i < entries.length; i++) {
            var entry = entries[i];
            if (this.equalsFunction(key, entry.key)) return true;
        }
    }
    return false;
};

Map.prototype.get = function (key) {
    var hashKey = "hash_" + this.hashFunction(key);
    if (hashKey in this.data) {
        var entries = this.data[hashKey];
        for (var i = 0; i < entries.length; i++) {
            var entry = entries[i];
            if (this.equalsFunction(key, entry.key)) return entry.value;
        }
    }
    return null;
};

Map.prototype.entries = function () {
    var l = [];
    for (var key in this.data) {
        if (key.indexOf("hash_") === 0) {
            l = l.concat(this.data[key]);
        }
    }
    return l;
};

Map.prototype.getKeys = function () {
    return this.entries().map(function (e) {
        return e.key;
    });
};

Map.prototype.getValues = function () {
    return this.entries().map(function (e) {
        return e.value;
    });
};

Map.prototype.toString = function () {
    var ss = this.entries().map(function (entry) {
        return '{' + entry.key + ':' + entry.value + '}';
    });
    return '[' + ss.join(", ") + ']';
};

function AltDict() {
    this.data = {};
    return this;
}

AltDict.prototype.get = function (key) {
    key = "k-" + key;
    if (key in this.data) {
        return this.data[key];
    } else {
        return null;
    }
};

AltDict.prototype.put = function (key, value) {
    key = "k-" + key;
    this.data[key] = value;
};

AltDict.prototype.values = function () {
    var data = this.data;
    var keys = Object.keys(this.data);
    return keys.map(function (key) {
        return data[key];
    });
};

function DoubleDict() {
    return this;
}

function Hash() {
    this.count = 0;
    this.hash = 0;
    return this;
}

Hash.prototype.update = function () {
    for (var i = 0; i < arguments.length; i++) {
        var value = arguments[i];
        if (value == null) continue;
        if (Array.isArray(value)) this.update.apply(value);else {
            var k = 0;
            switch (typeof value === "undefined" ? "undefined" : _typeof(value)) {
                case 'undefined':
                case 'function':
                    continue;
                case 'number':
                case 'boolean':
                    k = value;
                    break;
                case 'string':
                    k = value.hashCode();
                    break;
                default:
                    value.updateHashCode(this);
                    continue;
            }
            k = k * 0xCC9E2D51;
            k = k << 15 | k >>> 32 - 15;
            k = k * 0x1B873593;
            this.count = this.count + 1;
            var hash = this.hash ^ k;
            hash = hash << 13 | hash >>> 32 - 13;
            hash = hash * 5 + 0xE6546B64;
            this.hash = hash;
        }
    }
};

Hash.prototype.finish = function () {
    var hash = this.hash ^ this.count * 4;
    hash = hash ^ hash >>> 16;
    hash = hash * 0x85EBCA6B;
    hash = hash ^ hash >>> 13;
    hash = hash * 0xC2B2AE35;
    hash = hash ^ hash >>> 16;
    return hash;
};

function hashStuff() {
    var hash = new Hash();
    hash.update.apply(arguments);
    return hash.finish();
}

DoubleDict.prototype.get = function (a, b) {
    var d = this[a] || null;
    return d === null ? null : d[b] || null;
};

DoubleDict.prototype.set = function (a, b, o) {
    var d = this[a] || null;
    if (d === null) {
        d = {};
        this[a] = d;
    }
    d[b] = o;
};

function escapeWhitespace(s, escapeSpaces) {
    s = s.replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
    if (escapeSpaces) {
        s = s.replace(/ /g, "\xB7");
    }
    return s;
}

function titleCase(str) {
    return str.replace(/\w\S*/g, function (txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1);
    });
};

function equalArrays(a, b) {
    if (!Array.isArray(a) || !Array.isArray(b)) return false;
    if (a == b) return true;
    if (a.length != b.length) return false;
    for (var i = 0; i < a.length; i++) {
        if (a[i] == b[i]) continue;
        if (!a[i].equals(b[i])) return false;
    }
    return true;
};

exports.Hash = Hash;
exports.Set = Set;
exports.Map = Map;
exports.BitSet = BitSet;
exports.AltDict = AltDict;
exports.DoubleDict = DoubleDict;
exports.hashStuff = hashStuff;
exports.escapeWhitespace = escapeWhitespace;
exports.arrayToString = arrayToString;
exports.titleCase = titleCase;
exports.equalArrays = equalArrays;

/***/ }),

/***/ "./node_modules/antlr4/atn/ATN.js":
/*!****************************************!*\
  !*** ./node_modules/antlr4/atn/ATN.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

var LL1Analyzer = __webpack_require__(/*! ./../LL1Analyzer */ "./node_modules/antlr4/LL1Analyzer.js").LL1Analyzer;
var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;

function ATN(grammarType, maxTokenType) {

    // Used for runtime deserialization of ATNs from strings///
    // The type of the ATN.
    this.grammarType = grammarType;
    // The maximum value for any symbol recognized by a transition in the ATN.
    this.maxTokenType = maxTokenType;
    this.states = [];
    // Each subrule/rule is a decision point and we must track them so we
    //  can go back later and build DFA predictors for them.  This includes
    //  all the rules, subrules, optional blocks, ()+, ()* etc...
    this.decisionToState = [];
    // Maps from rule index to starting state number.
    this.ruleToStartState = [];
    // Maps from rule index to stop state number.
    this.ruleToStopState = null;
    this.modeNameToStartState = {};
    // For lexer ATNs, this maps the rule index to the resulting token type.
    // For parser ATNs, this maps the rule index to the generated bypass token
    // type if the
    // {@link ATNDeserializationOptions//isGenerateRuleBypassTransitions}
    // deserialization option was specified; otherwise, this is {@code null}.
    this.ruleToTokenType = null;
    // For lexer ATNs, this is an array of {@link LexerAction} objects which may
    // be referenced by action transitions in the ATN.
    this.lexerActions = null;
    this.modeToStartState = [];

    return this;
}

// Compute the set of valid tokens that can occur starting in state {@code s}.
//  If {@code ctx} is null, the set of tokens will not include what can follow
//  the rule surrounding {@code s}. In other words, the set will be
//  restricted to tokens reachable staying within {@code s}'s rule.
ATN.prototype.nextTokensInContext = function (s, ctx) {
    var anal = new LL1Analyzer(this);
    return anal.LOOK(s, null, ctx);
};

// Compute the set of valid tokens that can occur starting in {@code s} and
// staying in same rule. {@link Token//EPSILON} is in set if we reach end of
// rule.
ATN.prototype.nextTokensNoContext = function (s) {
    if (s.nextTokenWithinRule !== null) {
        return s.nextTokenWithinRule;
    }
    s.nextTokenWithinRule = this.nextTokensInContext(s, null);
    s.nextTokenWithinRule.readOnly = true;
    return s.nextTokenWithinRule;
};

ATN.prototype.nextTokens = function (s, ctx) {
    if (ctx === undefined) {
        return this.nextTokensNoContext(s);
    } else {
        return this.nextTokensInContext(s, ctx);
    }
};

ATN.prototype.addState = function (state) {
    if (state !== null) {
        state.atn = this;
        state.stateNumber = this.states.length;
    }
    this.states.push(state);
};

ATN.prototype.removeState = function (state) {
    this.states[state.stateNumber] = null; // just free mem, don't shift states in list
};

ATN.prototype.defineDecisionState = function (s) {
    this.decisionToState.push(s);
    s.decision = this.decisionToState.length - 1;
    return s.decision;
};

ATN.prototype.getDecisionState = function (decision) {
    if (this.decisionToState.length === 0) {
        return null;
    } else {
        return this.decisionToState[decision];
    }
};

// Computes the set of input symbols which could follow ATN state number
// {@code stateNumber} in the specified full {@code context}. This method
// considers the complete parser context, but does not evaluate semantic
// predicates (i.e. all predicates encountered during the calculation are
// assumed true). If a path in the ATN exists from the starting state to the
// {@link RuleStopState} of the outermost context without matching any
// symbols, {@link Token//EOF} is added to the returned set.
//
// <p>If {@code context} is {@code null}, it is treated as
// {@link ParserRuleContext//EMPTY}.</p>
//
// @param stateNumber the ATN state number
// @param context the full parse context
// @return The set of potentially valid input symbols which could follow the
// specified state in the specified context.
// @throws IllegalArgumentException if the ATN does not contain a state with
// number {@code stateNumber}
var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;

ATN.prototype.getExpectedTokens = function (stateNumber, ctx) {
    if (stateNumber < 0 || stateNumber >= this.states.length) {
        throw "Invalid state number.";
    }
    var s = this.states[stateNumber];
    var following = this.nextTokens(s);
    if (!following.contains(Token.EPSILON)) {
        return following;
    }
    var expected = new IntervalSet();
    expected.addSet(following);
    expected.removeOne(Token.EPSILON);
    while (ctx !== null && ctx.invokingState >= 0 && following.contains(Token.EPSILON)) {
        var invokingState = this.states[ctx.invokingState];
        var rt = invokingState.transitions[0];
        following = this.nextTokens(rt.followState);
        expected.addSet(following);
        expected.removeOne(Token.EPSILON);
        ctx = ctx.parentCtx;
    }
    if (following.contains(Token.EPSILON)) {
        expected.addOne(Token.EOF);
    }
    return expected;
};

ATN.INVALID_ALT_NUMBER = 0;

exports.ATN = ATN;

/***/ }),

/***/ "./node_modules/antlr4/atn/ATNConfig.js":
/*!**********************************************!*\
  !*** ./node_modules/antlr4/atn/ATNConfig.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

// A tuple: (ATN state, predicted alt, syntactic, semantic context).
//  The syntactic context is a graph-structured stack node whose
//  path(s) to the root is the rule invocation(s)
//  chain used to arrive at the state.  The semantic context is
//  the tree of semantic predicates encountered before reaching
//  an ATN state.
///

var DecisionState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").DecisionState;
var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
var Hash = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").Hash;

function checkParams(params, isCfg) {
    if (params === null) {
        var result = { state: null, alt: null, context: null, semanticContext: null };
        if (isCfg) {
            result.reachesIntoOuterContext = 0;
        }
        return result;
    } else {
        var props = {};
        props.state = params.state || null;
        props.alt = params.alt === undefined ? null : params.alt;
        props.context = params.context || null;
        props.semanticContext = params.semanticContext || null;
        if (isCfg) {
            props.reachesIntoOuterContext = params.reachesIntoOuterContext || 0;
            props.precedenceFilterSuppressed = params.precedenceFilterSuppressed || false;
        }
        return props;
    }
}

function ATNConfig(params, config) {
    this.checkContext(params, config);
    params = checkParams(params);
    config = checkParams(config, true);
    // The ATN state associated with this configuration///
    this.state = params.state !== null ? params.state : config.state;
    // What alt (or lexer rule) is predicted by this configuration///
    this.alt = params.alt !== null ? params.alt : config.alt;
    // The stack of invoking states leading to the rule/states associated
    //  with this config.  We track only those contexts pushed during
    //  execution of the ATN simulator.
    this.context = params.context !== null ? params.context : config.context;
    this.semanticContext = params.semanticContext !== null ? params.semanticContext : config.semanticContext !== null ? config.semanticContext : SemanticContext.NONE;
    // We cannot execute predicates dependent upon local context unless
    // we know for sure we are in the correct context. Because there is
    // no way to do this efficiently, we simply cannot evaluate
    // dependent predicates unless we are in the rule that initially
    // invokes the ATN simulator.
    //
    // closure() tracks the depth of how far we dip into the
    // outer context: depth &gt; 0.  Note that it may not be totally
    // accurate depth since I don't ever decrement. TODO: make it a boolean then
    this.reachesIntoOuterContext = config.reachesIntoOuterContext;
    this.precedenceFilterSuppressed = config.precedenceFilterSuppressed;
    return this;
}

ATNConfig.prototype.checkContext = function (params, config) {
    if ((params.context === null || params.context === undefined) && (config === null || config.context === null || config.context === undefined)) {
        this.context = null;
    }
};

ATNConfig.prototype.hashCode = function () {
    var hash = new Hash();
    this.updateHashCode(hash);
    return hash.finish();
};

ATNConfig.prototype.updateHashCode = function (hash) {
    hash.update(this.state.stateNumber, this.alt, this.context, this.semanticContext);
};

// An ATN configuration is equal to another if both have
//  the same state, they predict the same alternative, and
//  syntactic/semantic contexts are the same.

ATNConfig.prototype.equals = function (other) {
    if (this === other) {
        return true;
    } else if (!(other instanceof ATNConfig)) {
        return false;
    } else {
        return this.state.stateNumber === other.state.stateNumber && this.alt === other.alt && (this.context === null ? other.context === null : this.context.equals(other.context)) && this.semanticContext.equals(other.semanticContext) && this.precedenceFilterSuppressed === other.precedenceFilterSuppressed;
    }
};

ATNConfig.prototype.hashCodeForConfigSet = function () {
    var hash = new Hash();
    hash.update(this.state.stateNumber, this.alt, this.semanticContext);
    return hash.finish();
};

ATNConfig.prototype.equalsForConfigSet = function (other) {
    if (this === other) {
        return true;
    } else if (!(other instanceof ATNConfig)) {
        return false;
    } else {
        return this.state.stateNumber === other.state.stateNumber && this.alt === other.alt && this.semanticContext.equals(other.semanticContext);
    }
};

ATNConfig.prototype.toString = function () {
    return "(" + this.state + "," + this.alt + (this.context !== null ? ",[" + this.context.toString() + "]" : "") + (this.semanticContext !== SemanticContext.NONE ? "," + this.semanticContext.toString() : "") + (this.reachesIntoOuterContext > 0 ? ",up=" + this.reachesIntoOuterContext : "") + ")";
};

function LexerATNConfig(params, config) {
    ATNConfig.call(this, params, config);

    // This is the backing field for {@link //getLexerActionExecutor}.
    var lexerActionExecutor = params.lexerActionExecutor || null;
    this.lexerActionExecutor = lexerActionExecutor || (config !== null ? config.lexerActionExecutor : null);
    this.passedThroughNonGreedyDecision = config !== null ? this.checkNonGreedyDecision(config, this.state) : false;
    return this;
}

LexerATNConfig.prototype = Object.create(ATNConfig.prototype);
LexerATNConfig.prototype.constructor = LexerATNConfig;

LexerATNConfig.prototype.updateHashCode = function (hash) {
    hash.update(this.state.stateNumber, this.alt, this.context, this.semanticContext, this.passedThroughNonGreedyDecision, this.lexerActionExecutor);
};

LexerATNConfig.prototype.equals = function (other) {
    return this === other || other instanceof LexerATNConfig && this.passedThroughNonGreedyDecision == other.passedThroughNonGreedyDecision && (this.lexerActionExecutor ? this.lexerActionExecutor.equals(other.lexerActionExecutor) : !other.lexerActionExecutor) && ATNConfig.prototype.equals.call(this, other);
};

LexerATNConfig.prototype.hashCodeForConfigSet = LexerATNConfig.prototype.hashCode;

LexerATNConfig.prototype.equalsForConfigSet = LexerATNConfig.prototype.equals;

LexerATNConfig.prototype.checkNonGreedyDecision = function (source, target) {
    return source.passedThroughNonGreedyDecision || target instanceof DecisionState && target.nonGreedy;
};

exports.ATNConfig = ATNConfig;
exports.LexerATNConfig = LexerATNConfig;

/***/ }),

/***/ "./node_modules/antlr4/atn/ATNConfigSet.js":
/*!*************************************************!*\
  !*** ./node_modules/antlr4/atn/ATNConfigSet.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

//
// Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track
// info about the set, with support for combining similar configurations using a
// graph-structured stack.
///

var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
var Hash = Utils.Hash;
var Set = Utils.Set;
var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
var merge = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").merge;

function hashATNConfig(c) {
	return c.hashCodeForConfigSet();
}

function equalATNConfigs(a, b) {
	if (a === b) {
		return true;
	} else if (a === null || b === null) {
		return false;
	} else return a.equalsForConfigSet(b);
}

function ATNConfigSet(fullCtx) {
	//
	// The reason that we need this is because we don't want the hash map to use
	// the standard hash code and equals. We need all configurations with the
	// same
	// {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively
	// doubles
	// the number of objects associated with ATNConfigs. The other solution is
	// to
	// use a hash table that lets us specify the equals/hashcode operation.
	// All configs but hashed by (s, i, _, pi) not including context. Wiped out
	// when we go readonly as this set becomes a DFA state.
	this.configLookup = new Set(hashATNConfig, equalATNConfigs);
	// Indicates that this configuration set is part of a full context
	// LL prediction. It will be used to determine how to merge $. With SLL
	// it's a wildcard whereas it is not for LL context merge.
	this.fullCtx = fullCtx === undefined ? true : fullCtx;
	// Indicates that the set of configurations is read-only. Do not
	// allow any code to manipulate the set; DFA states will point at
	// the sets and they must not change. This does not protect the other
	// fields; in particular, conflictingAlts is set after
	// we've made this readonly.
	this.readOnly = false;
	// Track the elements as they are added to the set; supports get(i)///
	this.configs = [];

	// TODO: these fields make me pretty uncomfortable but nice to pack up info
	// together, saves recomputation
	// TODO: can we track conflicts as they are added to save scanning configs
	// later?
	this.uniqueAlt = 0;
	this.conflictingAlts = null;

	// Used in parser and lexer. In lexer, it indicates we hit a pred
	// while computing a closure operation. Don't make a DFA state from this.
	this.hasSemanticContext = false;
	this.dipsIntoOuterContext = false;

	this.cachedHashCode = -1;

	return this;
}

// Adding a new config means merging contexts with existing configs for
// {@code (s, i, pi, _)}, where {@code s} is the
// {@link ATNConfig//state}, {@code i} is the {@link ATNConfig//alt}, and
// {@code pi} is the {@link ATNConfig//semanticContext}. We use
// {@code (s,i,pi)} as key.
//
// <p>This method updates {@link //dipsIntoOuterContext} and
// {@link //hasSemanticContext} when necessary.</p>
// /
ATNConfigSet.prototype.add = function (config, mergeCache) {
	if (mergeCache === undefined) {
		mergeCache = null;
	}
	if (this.readOnly) {
		throw "This set is readonly";
	}
	if (config.semanticContext !== SemanticContext.NONE) {
		this.hasSemanticContext = true;
	}
	if (config.reachesIntoOuterContext > 0) {
		this.dipsIntoOuterContext = true;
	}
	var existing = this.configLookup.add(config);
	if (existing === config) {
		this.cachedHashCode = -1;
		this.configs.push(config); // track order here
		return true;
	}
	// a previous (s,i,pi,_), merge with it and save result
	var rootIsWildcard = !this.fullCtx;
	var merged = merge(existing.context, config.context, rootIsWildcard, mergeCache);
	// no need to check for existing.context, config.context in cache
	// since only way to create new graphs is "call rule" and here. We
	// cache at both places.
	existing.reachesIntoOuterContext = Math.max(existing.reachesIntoOuterContext, config.reachesIntoOuterContext);
	// make sure to preserve the precedence filter suppression during the merge
	if (config.precedenceFilterSuppressed) {
		existing.precedenceFilterSuppressed = true;
	}
	existing.context = merged; // replace context; no need to alt mapping
	return true;
};

ATNConfigSet.prototype.getStates = function () {
	var states = new Set();
	for (var i = 0; i < this.configs.length; i++) {
		states.add(this.configs[i].state);
	}
	return states;
};

ATNConfigSet.prototype.getPredicates = function () {
	var preds = [];
	for (var i = 0; i < this.configs.length; i++) {
		var c = this.configs[i].semanticContext;
		if (c !== SemanticContext.NONE) {
			preds.push(c.semanticContext);
		}
	}
	return preds;
};

Object.defineProperty(ATNConfigSet.prototype, "items", {
	get: function get() {
		return this.configs;
	}
});

ATNConfigSet.prototype.optimizeConfigs = function (interpreter) {
	if (this.readOnly) {
		throw "This set is readonly";
	}
	if (this.configLookup.length === 0) {
		return;
	}
	for (var i = 0; i < this.configs.length; i++) {
		var config = this.configs[i];
		config.context = interpreter.getCachedContext(config.context);
	}
};

ATNConfigSet.prototype.addAll = function (coll) {
	for (var i = 0; i < coll.length; i++) {
		this.add(coll[i]);
	}
	return false;
};

ATNConfigSet.prototype.equals = function (other) {
	return this === other || other instanceof ATNConfigSet && Utils.equalArrays(this.configs, other.configs) && this.fullCtx === other.fullCtx && this.uniqueAlt === other.uniqueAlt && this.conflictingAlts === other.conflictingAlts && this.hasSemanticContext === other.hasSemanticContext && this.dipsIntoOuterContext === other.dipsIntoOuterContext;
};

ATNConfigSet.prototype.hashCode = function () {
	var hash = new Hash();
	this.updateHashCode(hash);
	return hash.finish();
};

ATNConfigSet.prototype.updateHashCode = function (hash) {
	if (this.readOnly) {
		if (this.cachedHashCode === -1) {
			var hash = new Hash();
			hash.update(this.configs);
			this.cachedHashCode = hash.finish();
		}
		hash.update(this.cachedHashCode);
	} else {
		hash.update(this.configs);
	}
};

Object.defineProperty(ATNConfigSet.prototype, "length", {
	get: function get() {
		return this.configs.length;
	}
});

ATNConfigSet.prototype.isEmpty = function () {
	return this.configs.length === 0;
};

ATNConfigSet.prototype.contains = function (item) {
	if (this.configLookup === null) {
		throw "This method is not implemented for readonly sets.";
	}
	return this.configLookup.contains(item);
};

ATNConfigSet.prototype.containsFast = function (item) {
	if (this.configLookup === null) {
		throw "This method is not implemented for readonly sets.";
	}
	return this.configLookup.containsFast(item);
};

ATNConfigSet.prototype.clear = function () {
	if (this.readOnly) {
		throw "This set is readonly";
	}
	this.configs = [];
	this.cachedHashCode = -1;
	this.configLookup = new Set();
};

ATNConfigSet.prototype.setReadonly = function (readOnly) {
	this.readOnly = readOnly;
	if (readOnly) {
		this.configLookup = null; // can't mod, no need for lookup cache
	}
};

ATNConfigSet.prototype.toString = function () {
	return Utils.arrayToString(this.configs) + (this.hasSemanticContext ? ",hasSemanticContext=" + this.hasSemanticContext : "") + (this.uniqueAlt !== ATN.INVALID_ALT_NUMBER ? ",uniqueAlt=" + this.uniqueAlt : "") + (this.conflictingAlts !== null ? ",conflictingAlts=" + this.conflictingAlts : "") + (this.dipsIntoOuterContext ? ",dipsIntoOuterContext" : "");
};

function OrderedATNConfigSet() {
	ATNConfigSet.call(this);
	this.configLookup = new Set();
	return this;
}

OrderedATNConfigSet.prototype = Object.create(ATNConfigSet.prototype);
OrderedATNConfigSet.prototype.constructor = OrderedATNConfigSet;

exports.ATNConfigSet = ATNConfigSet;
exports.OrderedATNConfigSet = OrderedATNConfigSet;

/***/ }),

/***/ "./node_modules/antlr4/atn/ATNDeserializationOptions.js":
/*!**************************************************************!*\
  !*** ./node_modules/antlr4/atn/ATNDeserializationOptions.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

function ATNDeserializationOptions(copyFrom) {
  if (copyFrom === undefined) {
    copyFrom = null;
  }
  this.readOnly = false;
  this.verifyATN = copyFrom === null ? true : copyFrom.verifyATN;
  this.generateRuleBypassTransitions = copyFrom === null ? false : copyFrom.generateRuleBypassTransitions;

  return this;
}

ATNDeserializationOptions.defaultOptions = new ATNDeserializationOptions();
ATNDeserializationOptions.defaultOptions.readOnly = true;

//    def __setattr__(self, key, value):
//        if key!="readOnly" and self.readOnly:
//            raise Exception("The object is read only.")
//        super(type(self), self).__setattr__(key,value)

exports.ATNDeserializationOptions = ATNDeserializationOptions;

/***/ }),

/***/ "./node_modules/antlr4/atn/ATNDeserializer.js":
/*!****************************************************!*\
  !*** ./node_modules/antlr4/atn/ATNDeserializer.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
var ATNType = __webpack_require__(/*! ./ATNType */ "./node_modules/antlr4/atn/ATNType.js").ATNType;
var ATNStates = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js");
var ATNState = ATNStates.ATNState;
var BasicState = ATNStates.BasicState;
var DecisionState = ATNStates.DecisionState;
var BlockStartState = ATNStates.BlockStartState;
var BlockEndState = ATNStates.BlockEndState;
var LoopEndState = ATNStates.LoopEndState;
var RuleStartState = ATNStates.RuleStartState;
var RuleStopState = ATNStates.RuleStopState;
var TokensStartState = ATNStates.TokensStartState;
var PlusLoopbackState = ATNStates.PlusLoopbackState;
var StarLoopbackState = ATNStates.StarLoopbackState;
var StarLoopEntryState = ATNStates.StarLoopEntryState;
var PlusBlockStartState = ATNStates.PlusBlockStartState;
var StarBlockStartState = ATNStates.StarBlockStartState;
var BasicBlockStartState = ATNStates.BasicBlockStartState;
var Transitions = __webpack_require__(/*! ./Transition */ "./node_modules/antlr4/atn/Transition.js");
var Transition = Transitions.Transition;
var AtomTransition = Transitions.AtomTransition;
var SetTransition = Transitions.SetTransition;
var NotSetTransition = Transitions.NotSetTransition;
var RuleTransition = Transitions.RuleTransition;
var RangeTransition = Transitions.RangeTransition;
var ActionTransition = Transitions.ActionTransition;
var EpsilonTransition = Transitions.EpsilonTransition;
var WildcardTransition = Transitions.WildcardTransition;
var PredicateTransition = Transitions.PredicateTransition;
var PrecedencePredicateTransition = Transitions.PrecedencePredicateTransition;
var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
var ATNDeserializationOptions = __webpack_require__(/*! ./ATNDeserializationOptions */ "./node_modules/antlr4/atn/ATNDeserializationOptions.js").ATNDeserializationOptions;
var LexerActions = __webpack_require__(/*! ./LexerAction */ "./node_modules/antlr4/atn/LexerAction.js");
var LexerActionType = LexerActions.LexerActionType;
var LexerSkipAction = LexerActions.LexerSkipAction;
var LexerChannelAction = LexerActions.LexerChannelAction;
var LexerCustomAction = LexerActions.LexerCustomAction;
var LexerMoreAction = LexerActions.LexerMoreAction;
var LexerTypeAction = LexerActions.LexerTypeAction;
var LexerPushModeAction = LexerActions.LexerPushModeAction;
var LexerPopModeAction = LexerActions.LexerPopModeAction;
var LexerModeAction = LexerActions.LexerModeAction;
// This is the earliest supported serialized UUID.
// stick to serialized version for now, we don't need a UUID instance
var BASE_SERIALIZED_UUID = "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E";

//
// This UUID indicates the serialized ATN contains two sets of
// IntervalSets, where the second set's values are encoded as
// 32-bit integers to support the full Unicode SMP range up to U+10FFFF.
//
var ADDED_UNICODE_SMP = "59627784-3BE5-417A-B9EB-8131A7286089";

// This list contains all of the currently supported UUIDs, ordered by when
// the feature first appeared in this branch.
var SUPPORTED_UUIDS = [BASE_SERIALIZED_UUID, ADDED_UNICODE_SMP];

var SERIALIZED_VERSION = 3;

// This is the current serialized UUID.
var SERIALIZED_UUID = ADDED_UNICODE_SMP;

function initArray(length, value) {
    var tmp = [];
    tmp[length - 1] = value;
    return tmp.map(function (i) {
        return value;
    });
}

function ATNDeserializer(options) {

    if (options === undefined || options === null) {
        options = ATNDeserializationOptions.defaultOptions;
    }
    this.deserializationOptions = options;
    this.stateFactories = null;
    this.actionFactories = null;

    return this;
}

// Determines if a particular serialized representation of an ATN supports
// a particular feature, identified by the {@link UUID} used for serializing
// the ATN at the time the feature was first introduced.
//
// @param feature The {@link UUID} marking the first time the feature was
// supported in the serialized ATN.
// @param actualUuid The {@link UUID} of the actual serialized ATN which is
// currently being deserialized.
// @return {@code true} if the {@code actualUuid} value represents a
// serialized ATN at or after the feature identified by {@code feature} was
// introduced; otherwise, {@code false}.

ATNDeserializer.prototype.isFeatureSupported = function (feature, actualUuid) {
    var idx1 = SUPPORTED_UUIDS.indexOf(feature);
    if (idx1 < 0) {
        return false;
    }
    var idx2 = SUPPORTED_UUIDS.indexOf(actualUuid);
    return idx2 >= idx1;
};

ATNDeserializer.prototype.deserialize = function (data) {
    this.reset(data);
    this.checkVersion();
    this.checkUUID();
    var atn = this.readATN();
    this.readStates(atn);
    this.readRules(atn);
    this.readModes(atn);
    var sets = [];
    // First, deserialize sets with 16-bit arguments <= U+FFFF.
    this.readSets(atn, sets, this.readInt.bind(this));
    // Next, if the ATN was serialized with the Unicode SMP feature,
    // deserialize sets with 32-bit arguments <= U+10FFFF.
    if (this.isFeatureSupported(ADDED_UNICODE_SMP, this.uuid)) {
        this.readSets(atn, sets, this.readInt32.bind(this));
    }
    this.readEdges(atn, sets);
    this.readDecisions(atn);
    this.readLexerActions(atn);
    this.markPrecedenceDecisions(atn);
    this.verifyATN(atn);
    if (this.deserializationOptions.generateRuleBypassTransitions && atn.grammarType === ATNType.PARSER) {
        this.generateRuleBypassTransitions(atn);
        // re-verify after modification
        this.verifyATN(atn);
    }
    return atn;
};

ATNDeserializer.prototype.reset = function (data) {
    var adjust = function adjust(c) {
        var v = c.charCodeAt(0);
        return v > 1 ? v - 2 : v + 65533;
    };
    var temp = data.split("").map(adjust);
    // don't adjust the first value since that's the version number
    temp[0] = data.charCodeAt(0);
    this.data = temp;
    this.pos = 0;
};

ATNDeserializer.prototype.checkVersion = function () {
    var version = this.readInt();
    if (version !== SERIALIZED_VERSION) {
        throw "Could not deserialize ATN with version " + version + " (expected " + SERIALIZED_VERSION + ").";
    }
};

ATNDeserializer.prototype.checkUUID = function () {
    var uuid = this.readUUID();
    if (SUPPORTED_UUIDS.indexOf(uuid) < 0) {
        throw "Could not deserialize ATN with UUID: " + uuid + " (expected " + SERIALIZED_UUID + " or a legacy UUID).", uuid, SERIALIZED_UUID;
    }
    this.uuid = uuid;
};

ATNDeserializer.prototype.readATN = function () {
    var grammarType = this.readInt();
    var maxTokenType = this.readInt();
    return new ATN(grammarType, maxTokenType);
};

ATNDeserializer.prototype.readStates = function (atn) {
    var j, pair, stateNumber;
    var loopBackStateNumbers = [];
    var endStateNumbers = [];
    var nstates = this.readInt();
    for (var i = 0; i < nstates; i++) {
        var stype = this.readInt();
        // ignore bad type of states
        if (stype === ATNState.INVALID_TYPE) {
            atn.addState(null);
            continue;
        }
        var ruleIndex = this.readInt();
        if (ruleIndex === 0xFFFF) {
            ruleIndex = -1;
        }
        var s = this.stateFactory(stype, ruleIndex);
        if (stype === ATNState.LOOP_END) {
            // special case
            var loopBackStateNumber = this.readInt();
            loopBackStateNumbers.push([s, loopBackStateNumber]);
        } else if (s instanceof BlockStartState) {
            var endStateNumber = this.readInt();
            endStateNumbers.push([s, endStateNumber]);
        }
        atn.addState(s);
    }
    // delay the assignment of loop back and end states until we know all the
    // state instances have been initialized
    for (j = 0; j < loopBackStateNumbers.length; j++) {
        pair = loopBackStateNumbers[j];
        pair[0].loopBackState = atn.states[pair[1]];
    }

    for (j = 0; j < endStateNumbers.length; j++) {
        pair = endStateNumbers[j];
        pair[0].endState = atn.states[pair[1]];
    }

    var numNonGreedyStates = this.readInt();
    for (j = 0; j < numNonGreedyStates; j++) {
        stateNumber = this.readInt();
        atn.states[stateNumber].nonGreedy = true;
    }

    var numPrecedenceStates = this.readInt();
    for (j = 0; j < numPrecedenceStates; j++) {
        stateNumber = this.readInt();
        atn.states[stateNumber].isPrecedenceRule = true;
    }
};

ATNDeserializer.prototype.readRules = function (atn) {
    var i;
    var nrules = this.readInt();
    if (atn.grammarType === ATNType.LEXER) {
        atn.ruleToTokenType = initArray(nrules, 0);
    }
    atn.ruleToStartState = initArray(nrules, 0);
    for (i = 0; i < nrules; i++) {
        var s = this.readInt();
        var startState = atn.states[s];
        atn.ruleToStartState[i] = startState;
        if (atn.grammarType === ATNType.LEXER) {
            var tokenType = this.readInt();
            if (tokenType === 0xFFFF) {
                tokenType = Token.EOF;
            }
            atn.ruleToTokenType[i] = tokenType;
        }
    }
    atn.ruleToStopState = initArray(nrules, 0);
    for (i = 0; i < atn.states.length; i++) {
        var state = atn.states[i];
        if (!(state instanceof RuleStopState)) {
            continue;
        }
        atn.ruleToStopState[state.ruleIndex] = state;
        atn.ruleToStartState[state.ruleIndex].stopState = state;
    }
};

ATNDeserializer.prototype.readModes = function (atn) {
    var nmodes = this.readInt();
    for (var i = 0; i < nmodes; i++) {
        var s = this.readInt();
        atn.modeToStartState.push(atn.states[s]);
    }
};

ATNDeserializer.prototype.readSets = function (atn, sets, readUnicode) {
    var m = this.readInt();
    for (var i = 0; i < m; i++) {
        var iset = new IntervalSet();
        sets.push(iset);
        var n = this.readInt();
        var containsEof = this.readInt();
        if (containsEof !== 0) {
            iset.addOne(-1);
        }
        for (var j = 0; j < n; j++) {
            var i1 = readUnicode();
            var i2 = readUnicode();
            iset.addRange(i1, i2);
        }
    }
};

ATNDeserializer.prototype.readEdges = function (atn, sets) {
    var i, j, state, trans, target;
    var nedges = this.readInt();
    for (i = 0; i < nedges; i++) {
        var src = this.readInt();
        var trg = this.readInt();
        var ttype = this.readInt();
        var arg1 = this.readInt();
        var arg2 = this.readInt();
        var arg3 = this.readInt();
        trans = this.edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets);
        var srcState = atn.states[src];
        srcState.addTransition(trans);
    }
    // edges for rule stop states can be derived, so they aren't serialized
    for (i = 0; i < atn.states.length; i++) {
        state = atn.states[i];
        for (j = 0; j < state.transitions.length; j++) {
            var t = state.transitions[j];
            if (!(t instanceof RuleTransition)) {
                continue;
            }
            var outermostPrecedenceReturn = -1;
            if (atn.ruleToStartState[t.target.ruleIndex].isPrecedenceRule) {
                if (t.precedence === 0) {
                    outermostPrecedenceReturn = t.target.ruleIndex;
                }
            }

            trans = new EpsilonTransition(t.followState, outermostPrecedenceReturn);
            atn.ruleToStopState[t.target.ruleIndex].addTransition(trans);
        }
    }

    for (i = 0; i < atn.states.length; i++) {
        state = atn.states[i];
        if (state instanceof BlockStartState) {
            // we need to know the end state to set its start state
            if (state.endState === null) {
                throw "IllegalState";
            }
            // block end states can only be associated to a single block start
            // state
            if (state.endState.startState !== null) {
                throw "IllegalState";
            }
            state.endState.startState = state;
        }
        if (state instanceof PlusLoopbackState) {
            for (j = 0; j < state.transitions.length; j++) {
                target = state.transitions[j].target;
                if (target instanceof PlusBlockStartState) {
                    target.loopBackState = state;
                }
            }
        } else if (state instanceof StarLoopbackState) {
            for (j = 0; j < state.transitions.length; j++) {
                target = state.transitions[j].target;
                if (target instanceof StarLoopEntryState) {
                    target.loopBackState = state;
                }
            }
        }
    }
};

ATNDeserializer.prototype.readDecisions = function (atn) {
    var ndecisions = this.readInt();
    for (var i = 0; i < ndecisions; i++) {
        var s = this.readInt();
        var decState = atn.states[s];
        atn.decisionToState.push(decState);
        decState.decision = i;
    }
};

ATNDeserializer.prototype.readLexerActions = function (atn) {
    if (atn.grammarType === ATNType.LEXER) {
        var count = this.readInt();
        atn.lexerActions = initArray(count, null);
        for (var i = 0; i < count; i++) {
            var actionType = this.readInt();
            var data1 = this.readInt();
            if (data1 === 0xFFFF) {
                data1 = -1;
            }
            var data2 = this.readInt();
            if (data2 === 0xFFFF) {
                data2 = -1;
            }
            var lexerAction = this.lexerActionFactory(actionType, data1, data2);
            atn.lexerActions[i] = lexerAction;
        }
    }
};

ATNDeserializer.prototype.generateRuleBypassTransitions = function (atn) {
    var i;
    var count = atn.ruleToStartState.length;
    for (i = 0; i < count; i++) {
        atn.ruleToTokenType[i] = atn.maxTokenType + i + 1;
    }
    for (i = 0; i < count; i++) {
        this.generateRuleBypassTransition(atn, i);
    }
};

ATNDeserializer.prototype.generateRuleBypassTransition = function (atn, idx) {
    var i, state;
    var bypassStart = new BasicBlockStartState();
    bypassStart.ruleIndex = idx;
    atn.addState(bypassStart);

    var bypassStop = new BlockEndState();
    bypassStop.ruleIndex = idx;
    atn.addState(bypassStop);

    bypassStart.endState = bypassStop;
    atn.defineDecisionState(bypassStart);

    bypassStop.startState = bypassStart;

    var excludeTransition = null;
    var endState = null;

    if (atn.ruleToStartState[idx].isPrecedenceRule) {
        // wrap from the beginning of the rule to the StarLoopEntryState
        endState = null;
        for (i = 0; i < atn.states.length; i++) {
            state = atn.states[i];
            if (this.stateIsEndStateFor(state, idx)) {
                endState = state;
                excludeTransition = state.loopBackState.transitions[0];
                break;
            }
        }
        if (excludeTransition === null) {
            throw "Couldn't identify final state of the precedence rule prefix section.";
        }
    } else {
        endState = atn.ruleToStopState[idx];
    }

    // all non-excluded transitions that currently target end state need to
    // target blockEnd instead
    for (i = 0; i < atn.states.length; i++) {
        state = atn.states[i];
        for (var j = 0; j < state.transitions.length; j++) {
            var transition = state.transitions[j];
            if (transition === excludeTransition) {
                continue;
            }
            if (transition.target === endState) {
                transition.target = bypassStop;
            }
        }
    }

    // all transitions leaving the rule start state need to leave blockStart
    // instead
    var ruleToStartState = atn.ruleToStartState[idx];
    var count = ruleToStartState.transitions.length;
    while (count > 0) {
        bypassStart.addTransition(ruleToStartState.transitions[count - 1]);
        ruleToStartState.transitions = ruleToStartState.transitions.slice(-1);
    }
    // link the new states
    atn.ruleToStartState[idx].addTransition(new EpsilonTransition(bypassStart));
    bypassStop.addTransition(new EpsilonTransition(endState));

    var matchState = new BasicState();
    atn.addState(matchState);
    matchState.addTransition(new AtomTransition(bypassStop, atn.ruleToTokenType[idx]));
    bypassStart.addTransition(new EpsilonTransition(matchState));
};

ATNDeserializer.prototype.stateIsEndStateFor = function (state, idx) {
    if (state.ruleIndex !== idx) {
        return null;
    }
    if (!(state instanceof StarLoopEntryState)) {
        return null;
    }
    var maybeLoopEndState = state.transitions[state.transitions.length - 1].target;
    if (!(maybeLoopEndState instanceof LoopEndState)) {
        return null;
    }
    if (maybeLoopEndState.epsilonOnlyTransitions && maybeLoopEndState.transitions[0].target instanceof RuleStopState) {
        return state;
    } else {
        return null;
    }
};

//
// Analyze the {@link StarLoopEntryState} states in the specified ATN to set
// the {@link StarLoopEntryState//isPrecedenceDecision} field to the
// correct value.
//
// @param atn The ATN.
//
ATNDeserializer.prototype.markPrecedenceDecisions = function (atn) {
    for (var i = 0; i < atn.states.length; i++) {
        var state = atn.states[i];
        if (!(state instanceof StarLoopEntryState)) {
            continue;
        }
        // We analyze the ATN to determine if this ATN decision state is the
        // decision for the closure block that determines whether a
        // precedence rule should continue or complete.
        //
        if (atn.ruleToStartState[state.ruleIndex].isPrecedenceRule) {
            var maybeLoopEndState = state.transitions[state.transitions.length - 1].target;
            if (maybeLoopEndState instanceof LoopEndState) {
                if (maybeLoopEndState.epsilonOnlyTransitions && maybeLoopEndState.transitions[0].target instanceof RuleStopState) {
                    state.isPrecedenceDecision = true;
                }
            }
        }
    }
};

ATNDeserializer.prototype.verifyATN = function (atn) {
    if (!this.deserializationOptions.verifyATN) {
        return;
    }
    // verify assumptions
    for (var i = 0; i < atn.states.length; i++) {
        var state = atn.states[i];
        if (state === null) {
            continue;
        }
        this.checkCondition(state.epsilonOnlyTransitions || state.transitions.length <= 1);
        if (state instanceof PlusBlockStartState) {
            this.checkCondition(state.loopBackState !== null);
        } else if (state instanceof StarLoopEntryState) {
            this.checkCondition(state.loopBackState !== null);
            this.checkCondition(state.transitions.length === 2);
            if (state.transitions[0].target instanceof StarBlockStartState) {
                this.checkCondition(state.transitions[1].target instanceof LoopEndState);
                this.checkCondition(!state.nonGreedy);
            } else if (state.transitions[0].target instanceof LoopEndState) {
                this.checkCondition(state.transitions[1].target instanceof StarBlockStartState);
                this.checkCondition(state.nonGreedy);
            } else {
                throw "IllegalState";
            }
        } else if (state instanceof StarLoopbackState) {
            this.checkCondition(state.transitions.length === 1);
            this.checkCondition(state.transitions[0].target instanceof StarLoopEntryState);
        } else if (state instanceof LoopEndState) {
            this.checkCondition(state.loopBackState !== null);
        } else if (state instanceof RuleStartState) {
            this.checkCondition(state.stopState !== null);
        } else if (state instanceof BlockStartState) {
            this.checkCondition(state.endState !== null);
        } else if (state instanceof BlockEndState) {
            this.checkCondition(state.startState !== null);
        } else if (state instanceof DecisionState) {
            this.checkCondition(state.transitions.length <= 1 || state.decision >= 0);
        } else {
            this.checkCondition(state.transitions.length <= 1 || state instanceof RuleStopState);
        }
    }
};

ATNDeserializer.prototype.checkCondition = function (condition, message) {
    if (!condition) {
        if (message === undefined || message === null) {
            message = "IllegalState";
        }
        throw message;
    }
};

ATNDeserializer.prototype.readInt = function () {
    return this.data[this.pos++];
};

ATNDeserializer.prototype.readInt32 = function () {
    var low = this.readInt();
    var high = this.readInt();
    return low | high << 16;
};

ATNDeserializer.prototype.readLong = function () {
    var low = this.readInt32();
    var high = this.readInt32();
    return low & 0x00000000FFFFFFFF | high << 32;
};

function createByteToHex() {
    var bth = [];
    for (var i = 0; i < 256; i++) {
        bth[i] = (i + 0x100).toString(16).substr(1).toUpperCase();
    }
    return bth;
}

var byteToHex = createByteToHex();

ATNDeserializer.prototype.readUUID = function () {
    var bb = [];
    for (var i = 7; i >= 0; i--) {
        var int = this.readInt();
        /* jshint bitwise: false */
        bb[2 * i + 1] = int & 0xFF;
        bb[2 * i] = int >> 8 & 0xFF;
    }
    return byteToHex[bb[0]] + byteToHex[bb[1]] + byteToHex[bb[2]] + byteToHex[bb[3]] + '-' + byteToHex[bb[4]] + byteToHex[bb[5]] + '-' + byteToHex[bb[6]] + byteToHex[bb[7]] + '-' + byteToHex[bb[8]] + byteToHex[bb[9]] + '-' + byteToHex[bb[10]] + byteToHex[bb[11]] + byteToHex[bb[12]] + byteToHex[bb[13]] + byteToHex[bb[14]] + byteToHex[bb[15]];
};

ATNDeserializer.prototype.edgeFactory = function (atn, type, src, trg, arg1, arg2, arg3, sets) {
    var target = atn.states[trg];
    switch (type) {
        case Transition.EPSILON:
            return new EpsilonTransition(target);
        case Transition.RANGE:
            return arg3 !== 0 ? new RangeTransition(target, Token.EOF, arg2) : new RangeTransition(target, arg1, arg2);
        case Transition.RULE:
            return new RuleTransition(atn.states[arg1], arg2, arg3, target);
        case Transition.PREDICATE:
            return new PredicateTransition(target, arg1, arg2, arg3 !== 0);
        case Transition.PRECEDENCE:
            return new PrecedencePredicateTransition(target, arg1);
        case Transition.ATOM:
            return arg3 !== 0 ? new AtomTransition(target, Token.EOF) : new AtomTransition(target, arg1);
        case Transition.ACTION:
            return new ActionTransition(target, arg1, arg2, arg3 !== 0);
        case Transition.SET:
            return new SetTransition(target, sets[arg1]);
        case Transition.NOT_SET:
            return new NotSetTransition(target, sets[arg1]);
        case Transition.WILDCARD:
            return new WildcardTransition(target);
        default:
            throw "The specified transition type: " + type + " is not valid.";
    }
};

ATNDeserializer.prototype.stateFactory = function (type, ruleIndex) {
    if (this.stateFactories === null) {
        var sf = [];
        sf[ATNState.INVALID_TYPE] = null;
        sf[ATNState.BASIC] = function () {
            return new BasicState();
        };
        sf[ATNState.RULE_START] = function () {
            return new RuleStartState();
        };
        sf[ATNState.BLOCK_START] = function () {
            return new BasicBlockStartState();
        };
        sf[ATNState.PLUS_BLOCK_START] = function () {
            return new PlusBlockStartState();
        };
        sf[ATNState.STAR_BLOCK_START] = function () {
            return new StarBlockStartState();
        };
        sf[ATNState.TOKEN_START] = function () {
            return new TokensStartState();
        };
        sf[ATNState.RULE_STOP] = function () {
            return new RuleStopState();
        };
        sf[ATNState.BLOCK_END] = function () {
            return new BlockEndState();
        };
        sf[ATNState.STAR_LOOP_BACK] = function () {
            return new StarLoopbackState();
        };
        sf[ATNState.STAR_LOOP_ENTRY] = function () {
            return new StarLoopEntryState();
        };
        sf[ATNState.PLUS_LOOP_BACK] = function () {
            return new PlusLoopbackState();
        };
        sf[ATNState.LOOP_END] = function () {
            return new LoopEndState();
        };
        this.stateFactories = sf;
    }
    if (type > this.stateFactories.length || this.stateFactories[type] === null) {
        throw "The specified state type " + type + " is not valid.";
    } else {
        var s = this.stateFactories[type]();
        if (s !== null) {
            s.ruleIndex = ruleIndex;
            return s;
        }
    }
};

ATNDeserializer.prototype.lexerActionFactory = function (type, data1, data2) {
    if (this.actionFactories === null) {
        var af = [];
        af[LexerActionType.CHANNEL] = function (data1, data2) {
            return new LexerChannelAction(data1);
        };
        af[LexerActionType.CUSTOM] = function (data1, data2) {
            return new LexerCustomAction(data1, data2);
        };
        af[LexerActionType.MODE] = function (data1, data2) {
            return new LexerModeAction(data1);
        };
        af[LexerActionType.MORE] = function (data1, data2) {
            return LexerMoreAction.INSTANCE;
        };
        af[LexerActionType.POP_MODE] = function (data1, data2) {
            return LexerPopModeAction.INSTANCE;
        };
        af[LexerActionType.PUSH_MODE] = function (data1, data2) {
            return new LexerPushModeAction(data1);
        };
        af[LexerActionType.SKIP] = function (data1, data2) {
            return LexerSkipAction.INSTANCE;
        };
        af[LexerActionType.TYPE] = function (data1, data2) {
            return new LexerTypeAction(data1);
        };
        this.actionFactories = af;
    }
    if (type > this.actionFactories.length || this.actionFactories[type] === null) {
        throw "The specified lexer action type " + type + " is not valid.";
    } else {
        return this.actionFactories[type](data1, data2);
    }
};

exports.ATNDeserializer = ATNDeserializer;

/***/ }),

/***/ "./node_modules/antlr4/atn/ATNSimulator.js":
/*!*************************************************!*\
  !*** ./node_modules/antlr4/atn/ATNSimulator.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

var DFAState = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
var getCachedPredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").getCachedPredictionContext;

function ATNSimulator(atn, sharedContextCache) {

    // The context cache maps all PredictionContext objects that are ==
    //  to a single cached copy. This cache is shared across all contexts
    //  in all ATNConfigs in all DFA states.  We rebuild each ATNConfigSet
    //  to use only cached nodes/graphs in addDFAState(). We don't want to
    //  fill this during closure() since there are lots of contexts that
    //  pop up but are not used ever again. It also greatly slows down closure().
    //
    //  <p>This cache makes a huge difference in memory and a little bit in speed.
    //  For the Java grammar on java.*, it dropped the memory requirements
    //  at the end from 25M to 16M. We don't store any of the full context
    //  graphs in the DFA because they are limited to local context only,
    //  but apparently there's a lot of repetition there as well. We optimize
    //  the config contexts before storing the config set in the DFA states
    //  by literally rebuilding them with cached subgraphs only.</p>
    //
    //  <p>I tried a cache for use during closure operations, that was
    //  whacked after each adaptivePredict(). It cost a little bit
    //  more time I think and doesn't save on the overall footprint
    //  so it's not worth the complexity.</p>
    ///
    this.atn = atn;
    this.sharedContextCache = sharedContextCache;
    return this;
}

// Must distinguish between missing edge and edge we know leads nowhere///
ATNSimulator.ERROR = new DFAState(0x7FFFFFFF, new ATNConfigSet());

ATNSimulator.prototype.getCachedContext = function (context) {
    if (this.sharedContextCache === null) {
        return context;
    }
    var visited = {};
    return getCachedPredictionContext(context, this.sharedContextCache, visited);
};

exports.ATNSimulator = ATNSimulator;

/***/ }),

/***/ "./node_modules/antlr4/atn/ATNState.js":
/*!*********************************************!*\
  !*** ./node_modules/antlr4/atn/ATNState.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

// The following images show the relation of states and
// {@link ATNState//transitions} for various grammar constructs.
//
// <ul>
//
// <li>Solid edges marked with an &//0949; indicate a required
// {@link EpsilonTransition}.</li>
//
// <li>Dashed edges indicate locations where any transition derived from
// {@link Transition} might appear.</li>
//
// <li>Dashed nodes are place holders for either a sequence of linked
// {@link BasicState} states or the inclusion of a block representing a nested
// construct in one of the forms below.</li>
//
// <li>Nodes showing multiple outgoing alternatives with a {@code ...} support
// any number of alternatives (one or more). Nodes without the {@code ...} only
// support the exact number of alternatives shown in the diagram.</li>
//
// </ul>
//
// <h2>Basic Blocks</h2>
//
// <h3>Rule</h3>
//
// <embed src="images/Rule.svg" type="image/svg+xml"/>
//
// <h3>Block of 1 or more alternatives</h3>
//
// <embed src="images/Block.svg" type="image/svg+xml"/>
//
// <h2>Greedy Loops</h2>
//
// <h3>Greedy Closure: {@code (...)*}</h3>
//
// <embed src="images/ClosureGreedy.svg" type="image/svg+xml"/>
//
// <h3>Greedy Positive Closure: {@code (...)+}</h3>
//
// <embed src="images/PositiveClosureGreedy.svg" type="image/svg+xml"/>
//
// <h3>Greedy Optional: {@code (...)?}</h3>
//
// <embed src="images/OptionalGreedy.svg" type="image/svg+xml"/>
//
// <h2>Non-Greedy Loops</h2>
//
// <h3>Non-Greedy Closure: {@code (...)*?}</h3>
//
// <embed src="images/ClosureNonGreedy.svg" type="image/svg+xml"/>
//
// <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3>
//
// <embed src="images/PositiveClosureNonGreedy.svg" type="image/svg+xml"/>
//
// <h3>Non-Greedy Optional: {@code (...)??}</h3>
//
// <embed src="images/OptionalNonGreedy.svg" type="image/svg+xml"/>
//

var INITIAL_NUM_TRANSITIONS = 4;

function ATNState() {
  // Which ATN are we in?
  this.atn = null;
  this.stateNumber = ATNState.INVALID_STATE_NUMBER;
  this.stateType = null;
  this.ruleIndex = 0; // at runtime, we don't have Rule objects
  this.epsilonOnlyTransitions = false;
  // Track the transitions emanating from this ATN state.
  this.transitions = [];
  // Used to cache lookahead during parsing, not used during construction
  this.nextTokenWithinRule = null;
  return this;
}

// constants for serialization
ATNState.INVALID_TYPE = 0;
ATNState.BASIC = 1;
ATNState.RULE_START = 2;
ATNState.BLOCK_START = 3;
ATNState.PLUS_BLOCK_START = 4;
ATNState.STAR_BLOCK_START = 5;
ATNState.TOKEN_START = 6;
ATNState.RULE_STOP = 7;
ATNState.BLOCK_END = 8;
ATNState.STAR_LOOP_BACK = 9;
ATNState.STAR_LOOP_ENTRY = 10;
ATNState.PLUS_LOOP_BACK = 11;
ATNState.LOOP_END = 12;

ATNState.serializationNames = ["INVALID", "BASIC", "RULE_START", "BLOCK_START", "PLUS_BLOCK_START", "STAR_BLOCK_START", "TOKEN_START", "RULE_STOP", "BLOCK_END", "STAR_LOOP_BACK", "STAR_LOOP_ENTRY", "PLUS_LOOP_BACK", "LOOP_END"];

ATNState.INVALID_STATE_NUMBER = -1;

ATNState.prototype.toString = function () {
  return this.stateNumber;
};

ATNState.prototype.equals = function (other) {
  if (other instanceof ATNState) {
    return this.stateNumber === other.stateNumber;
  } else {
    return false;
  }
};

ATNState.prototype.isNonGreedyExitState = function () {
  return false;
};

ATNState.prototype.addTransition = function (trans, index) {
  if (index === undefined) {
    index = -1;
  }
  if (this.transitions.length === 0) {
    this.epsilonOnlyTransitions = trans.isEpsilon;
  } else if (this.epsilonOnlyTransitions !== trans.isEpsilon) {
    this.epsilonOnlyTransitions = false;
  }
  if (index === -1) {
    this.transitions.push(trans);
  } else {
    this.transitions.splice(index, 1, trans);
  }
};

function BasicState() {
  ATNState.call(this);
  this.stateType = ATNState.BASIC;
  return this;
}

BasicState.prototype = Object.create(ATNState.prototype);
BasicState.prototype.constructor = BasicState;

function DecisionState() {
  ATNState.call(this);
  this.decision = -1;
  this.nonGreedy = false;
  return this;
}

DecisionState.prototype = Object.create(ATNState.prototype);
DecisionState.prototype.constructor = DecisionState;

//  The start of a regular {@code (...)} block.
function BlockStartState() {
  DecisionState.call(this);
  this.endState = null;
  return this;
}

BlockStartState.prototype = Object.create(DecisionState.prototype);
BlockStartState.prototype.constructor = BlockStartState;

function BasicBlockStartState() {
  BlockStartState.call(this);
  this.stateType = ATNState.BLOCK_START;
  return this;
}

BasicBlockStartState.prototype = Object.create(BlockStartState.prototype);
BasicBlockStartState.prototype.constructor = BasicBlockStartState;

// Terminal node of a simple {@code (a|b|c)} block.
function BlockEndState() {
  ATNState.call(this);
  this.stateType = ATNState.BLOCK_END;
  this.startState = null;
  return this;
}

BlockEndState.prototype = Object.create(ATNState.prototype);
BlockEndState.prototype.constructor = BlockEndState;

// The last node in the ATN for a rule, unless that rule is the start symbol.
//  In that case, there is one transition to EOF. Later, we might encode
//  references to all calls to this rule to compute FOLLOW sets for
//  error handling.
//
function RuleStopState() {
  ATNState.call(this);
  this.stateType = ATNState.RULE_STOP;
  return this;
}

RuleStopState.prototype = Object.create(ATNState.prototype);
RuleStopState.prototype.constructor = RuleStopState;

function RuleStartState() {
  ATNState.call(this);
  this.stateType = ATNState.RULE_START;
  this.stopState = null;
  this.isPrecedenceRule = false;
  return this;
}

RuleStartState.prototype = Object.create(ATNState.prototype);
RuleStartState.prototype.constructor = RuleStartState;

// Decision state for {@code A+} and {@code (A|B)+}.  It has two transitions:
//  one to the loop back to start of the block and one to exit.
//
function PlusLoopbackState() {
  DecisionState.call(this);
  this.stateType = ATNState.PLUS_LOOP_BACK;
  return this;
}

PlusLoopbackState.prototype = Object.create(DecisionState.prototype);
PlusLoopbackState.prototype.constructor = PlusLoopbackState;

// Start of {@code (A|B|...)+} loop. Technically a decision state, but
//  we don't use for code generation; somebody might need it, so I'm defining
//  it for completeness. In reality, the {@link PlusLoopbackState} node is the
//  real decision-making note for {@code A+}.
//
function PlusBlockStartState() {
  BlockStartState.call(this);
  this.stateType = ATNState.PLUS_BLOCK_START;
  this.loopBackState = null;
  return this;
}

PlusBlockStartState.prototype = Object.create(BlockStartState.prototype);
PlusBlockStartState.prototype.constructor = PlusBlockStartState;

// The block that begins a closure loop.
function StarBlockStartState() {
  BlockStartState.call(this);
  this.stateType = ATNState.STAR_BLOCK_START;
  return this;
}

StarBlockStartState.prototype = Object.create(BlockStartState.prototype);
StarBlockStartState.prototype.constructor = StarBlockStartState;

function StarLoopbackState() {
  ATNState.call(this);
  this.stateType = ATNState.STAR_LOOP_BACK;
  return this;
}

StarLoopbackState.prototype = Object.create(ATNState.prototype);
StarLoopbackState.prototype.constructor = StarLoopbackState;

function StarLoopEntryState() {
  DecisionState.call(this);
  this.stateType = ATNState.STAR_LOOP_ENTRY;
  this.loopBackState = null;
  // Indicates whether this state can benefit from a precedence DFA during SLL decision making.
  this.isPrecedenceDecision = null;
  return this;
}

StarLoopEntryState.prototype = Object.create(DecisionState.prototype);
StarLoopEntryState.prototype.constructor = StarLoopEntryState;

// Mark the end of a * or + loop.
function LoopEndState() {
  ATNState.call(this);
  this.stateType = ATNState.LOOP_END;
  this.loopBackState = null;
  return this;
}

LoopEndState.prototype = Object.create(ATNState.prototype);
LoopEndState.prototype.constructor = LoopEndState;

// The Tokens rule start state linking to each lexer rule start state */
function TokensStartState() {
  DecisionState.call(this);
  this.stateType = ATNState.TOKEN_START;
  return this;
}

TokensStartState.prototype = Object.create(DecisionState.prototype);
TokensStartState.prototype.constructor = TokensStartState;

exports.ATNState = ATNState;
exports.BasicState = BasicState;
exports.DecisionState = DecisionState;
exports.BlockStartState = BlockStartState;
exports.BlockEndState = BlockEndState;
exports.LoopEndState = LoopEndState;
exports.RuleStartState = RuleStartState;
exports.RuleStopState = RuleStopState;
exports.TokensStartState = TokensStartState;
exports.PlusLoopbackState = PlusLoopbackState;
exports.StarLoopbackState = StarLoopbackState;
exports.StarLoopEntryState = StarLoopEntryState;
exports.PlusBlockStartState = PlusBlockStartState;
exports.StarBlockStartState = StarBlockStartState;
exports.BasicBlockStartState = BasicBlockStartState;

/***/ }),

/***/ "./node_modules/antlr4/atn/ATNType.js":
/*!********************************************!*\
  !*** ./node_modules/antlr4/atn/ATNType.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

// Represents the type of recognizer an ATN applies to.

function ATNType() {}

ATNType.LEXER = 0;
ATNType.PARSER = 1;

exports.ATNType = ATNType;

/***/ }),

/***/ "./node_modules/antlr4/atn/LexerATNSimulator.js":
/*!******************************************************!*\
  !*** ./node_modules/antlr4/atn/LexerATNSimulator.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

// When we hit an accept state in either the DFA or the ATN, we
//  have to notify the character stream to start buffering characters
//  via {@link IntStream//mark} and record the current state. The current sim state
//  includes the current index into the input, the current line,
//  and current character position in that line. Note that the Lexer is
//  tracking the starting line and characterization of the token. These
//  variables track the "state" of the simulator when it hits an accept state.
//
//  <p>We track these variables separately for the DFA and ATN simulation
//  because the DFA simulation often has to fail over to the ATN
//  simulation. If the ATN simulation fails, we need the DFA to fall
//  back to its previously accepted state, if any. If the ATN succeeds,
//  then the ATN does the accept and the DFA simulator that invoked it
//  can simply return the predicted token type.</p>
///

var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
var Lexer = __webpack_require__(/*! ./../Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
var ATNSimulator = __webpack_require__(/*! ./ATNSimulator */ "./node_modules/antlr4/atn/ATNSimulator.js").ATNSimulator;
var DFAState = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
var OrderedATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").OrderedATNConfigSet;
var PredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").PredictionContext;
var SingletonPredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").SingletonPredictionContext;
var RuleStopState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
var LexerATNConfig = __webpack_require__(/*! ./ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").LexerATNConfig;
var Transition = __webpack_require__(/*! ./Transition */ "./node_modules/antlr4/atn/Transition.js").Transition;
var LexerActionExecutor = __webpack_require__(/*! ./LexerActionExecutor */ "./node_modules/antlr4/atn/LexerActionExecutor.js").LexerActionExecutor;
var LexerNoViableAltException = __webpack_require__(/*! ./../error/Errors */ "./node_modules/antlr4/error/Errors.js").LexerNoViableAltException;

function resetSimState(sim) {
	sim.index = -1;
	sim.line = 0;
	sim.column = -1;
	sim.dfaState = null;
}

function SimState() {
	resetSimState(this);
	return this;
}

SimState.prototype.reset = function () {
	resetSimState(this);
};

function LexerATNSimulator(recog, atn, decisionToDFA, sharedContextCache) {
	ATNSimulator.call(this, atn, sharedContextCache);
	this.decisionToDFA = decisionToDFA;
	this.recog = recog;
	// The current token's starting index into the character stream.
	// Shared across DFA to ATN simulation in case the ATN fails and the
	// DFA did not have a previous accept state. In this case, we use the
	// ATN-generated exception object.
	this.startIndex = -1;
	// line number 1..n within the input///
	this.line = 1;
	// The index of the character relative to the beginning of the line
	// 0..n-1///
	this.column = 0;
	this.mode = Lexer.DEFAULT_MODE;
	// Used during DFA/ATN exec to record the most recent accept configuration
	// info
	this.prevAccept = new SimState();
	// done
	return this;
}

LexerATNSimulator.prototype = Object.create(ATNSimulator.prototype);
LexerATNSimulator.prototype.constructor = LexerATNSimulator;

LexerATNSimulator.debug = false;
LexerATNSimulator.dfa_debug = false;

LexerATNSimulator.MIN_DFA_EDGE = 0;
LexerATNSimulator.MAX_DFA_EDGE = 127; // forces unicode to stay in ATN

LexerATNSimulator.match_calls = 0;

LexerATNSimulator.prototype.copyState = function (simulator) {
	this.column = simulator.column;
	this.line = simulator.line;
	this.mode = simulator.mode;
	this.startIndex = simulator.startIndex;
};

LexerATNSimulator.prototype.match = function (input, mode) {
	this.match_calls += 1;
	this.mode = mode;
	var mark = input.mark();
	try {
		this.startIndex = input.index;
		this.prevAccept.reset();
		var dfa = this.decisionToDFA[mode];
		if (dfa.s0 === null) {
			return this.matchATN(input);
		} else {
			return this.execATN(input, dfa.s0);
		}
	} finally {
		input.release(mark);
	}
};

LexerATNSimulator.prototype.reset = function () {
	this.prevAccept.reset();
	this.startIndex = -1;
	this.line = 1;
	this.column = 0;
	this.mode = Lexer.DEFAULT_MODE;
};

LexerATNSimulator.prototype.matchATN = function (input) {
	var startState = this.atn.modeToStartState[this.mode];

	if (LexerATNSimulator.debug) {
		console.log("matchATN mode " + this.mode + " start: " + startState);
	}
	var old_mode = this.mode;
	var s0_closure = this.computeStartState(input, startState);
	var suppressEdge = s0_closure.hasSemanticContext;
	s0_closure.hasSemanticContext = false;

	var next = this.addDFAState(s0_closure);
	if (!suppressEdge) {
		this.decisionToDFA[this.mode].s0 = next;
	}

	var predict = this.execATN(input, next);

	if (LexerATNSimulator.debug) {
		console.log("DFA after matchATN: " + this.decisionToDFA[old_mode].toLexerString());
	}
	return predict;
};

LexerATNSimulator.prototype.execATN = function (input, ds0) {
	if (LexerATNSimulator.debug) {
		console.log("start state closure=" + ds0.configs);
	}
	if (ds0.isAcceptState) {
		// allow zero-length tokens
		this.captureSimState(this.prevAccept, input, ds0);
	}
	var t = input.LA(1);
	var s = ds0; // s is current/from DFA state

	while (true) {
		// while more work
		if (LexerATNSimulator.debug) {
			console.log("execATN loop starting closure: " + s.configs);
		}

		// As we move src->trg, src->trg, we keep track of the previous trg to
		// avoid looking up the DFA state again, which is expensive.
		// If the previous target was already part of the DFA, we might
		// be able to avoid doing a reach operation upon t. If s!=null,
		// it means that semantic predicates didn't prevent us from
		// creating a DFA state. Once we know s!=null, we check to see if
		// the DFA state has an edge already for t. If so, we can just reuse
		// it's configuration set; there's no point in re-computing it.
		// This is kind of like doing DFA simulation within the ATN
		// simulation because DFA simulation is really just a way to avoid
		// computing reach/closure sets. Technically, once we know that
		// we have a previously added DFA state, we could jump over to
		// the DFA simulator. But, that would mean popping back and forth
		// a lot and making things more complicated algorithmically.
		// This optimization makes a lot of sense for loops within DFA.
		// A character will take us back to an existing DFA state
		// that already has lots of edges out of it. e.g., .* in comments.
		// print("Target for:" + str(s) + " and:" + str(t))
		var target = this.getExistingTargetState(s, t);
		// print("Existing:" + str(target))
		if (target === null) {
			target = this.computeTargetState(input, s, t);
			// print("Computed:" + str(target))
		}
		if (target === ATNSimulator.ERROR) {
			break;
		}
		// If this is a consumable input element, make sure to consume before
		// capturing the accept state so the input index, line, and char
		// position accurately reflect the state of the interpreter at the
		// end of the token.
		if (t !== Token.EOF) {
			this.consume(input);
		}
		if (target.isAcceptState) {
			this.captureSimState(this.prevAccept, input, target);
			if (t === Token.EOF) {
				break;
			}
		}
		t = input.LA(1);
		s = target; // flip; current DFA target becomes new src/from state
	}
	return this.failOrAccept(this.prevAccept, input, s.configs, t);
};

// Get an existing target state for an edge in the DFA. If the target state
// for the edge has not yet been computed or is otherwise not available,
// this method returns {@code null}.
//
// @param s The current DFA state
// @param t The next input symbol
// @return The existing target DFA state for the given input symbol
// {@code t}, or {@code null} if the target state for this edge is not
// already cached
LexerATNSimulator.prototype.getExistingTargetState = function (s, t) {
	if (s.edges === null || t < LexerATNSimulator.MIN_DFA_EDGE || t > LexerATNSimulator.MAX_DFA_EDGE) {
		return null;
	}

	var target = s.edges[t - LexerATNSimulator.MIN_DFA_EDGE];
	if (target === undefined) {
		target = null;
	}
	if (LexerATNSimulator.debug && target !== null) {
		console.log("reuse state " + s.stateNumber + " edge to " + target.stateNumber);
	}
	return target;
};

// Compute a target state for an edge in the DFA, and attempt to add the
// computed state and corresponding edge to the DFA.
//
// @param input The input stream
// @param s The current DFA state
// @param t The next input symbol
//
// @return The computed target DFA state for the given input symbol
// {@code t}. If {@code t} does not lead to a valid DFA state, this method
// returns {@link //ERROR}.
LexerATNSimulator.prototype.computeTargetState = function (input, s, t) {
	var reach = new OrderedATNConfigSet();
	// if we don't find an existing DFA state
	// Fill reach starting from closure, following t transitions
	this.getReachableConfigSet(input, s.configs, reach, t);

	if (reach.items.length === 0) {
		// we got nowhere on t from s
		if (!reach.hasSemanticContext) {
			// we got nowhere on t, don't throw out this knowledge; it'd
			// cause a failover from DFA later.
			this.addDFAEdge(s, t, ATNSimulator.ERROR);
		}
		// stop when we can't match any more char
		return ATNSimulator.ERROR;
	}
	// Add an edge from s to target DFA found/created for reach
	return this.addDFAEdge(s, t, null, reach);
};

LexerATNSimulator.prototype.failOrAccept = function (prevAccept, input, reach, t) {
	if (this.prevAccept.dfaState !== null) {
		var lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor;
		this.accept(input, lexerActionExecutor, this.startIndex, prevAccept.index, prevAccept.line, prevAccept.column);
		return prevAccept.dfaState.prediction;
	} else {
		// if no accept and EOF is first char, return EOF
		if (t === Token.EOF && input.index === this.startIndex) {
			return Token.EOF;
		}
		throw new LexerNoViableAltException(this.recog, input, this.startIndex, reach);
	}
};

// Given a starting configuration set, figure out all ATN configurations
// we can reach upon input {@code t}. Parameter {@code reach} is a return
// parameter.
LexerATNSimulator.prototype.getReachableConfigSet = function (input, closure, reach, t) {
	// this is used to skip processing for configs which have a lower priority
	// than a config that already reached an accept state for the same rule
	var skipAlt = ATN.INVALID_ALT_NUMBER;
	for (var i = 0; i < closure.items.length; i++) {
		var cfg = closure.items[i];
		var currentAltReachedAcceptState = cfg.alt === skipAlt;
		if (currentAltReachedAcceptState && cfg.passedThroughNonGreedyDecision) {
			continue;
		}
		if (LexerATNSimulator.debug) {
			console.log("testing %s at %s\n", this.getTokenName(t), cfg.toString(this.recog, true));
		}
		for (var j = 0; j < cfg.state.transitions.length; j++) {
			var trans = cfg.state.transitions[j]; // for each transition
			var target = this.getReachableTarget(trans, t);
			if (target !== null) {
				var lexerActionExecutor = cfg.lexerActionExecutor;
				if (lexerActionExecutor !== null) {
					lexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.index - this.startIndex);
				}
				var treatEofAsEpsilon = t === Token.EOF;
				var config = new LexerATNConfig({ state: target, lexerActionExecutor: lexerActionExecutor }, cfg);
				if (this.closure(input, config, reach, currentAltReachedAcceptState, true, treatEofAsEpsilon)) {
					// any remaining configs for this alt have a lower priority
					// than the one that just reached an accept state.
					skipAlt = cfg.alt;
				}
			}
		}
	}
};

LexerATNSimulator.prototype.accept = function (input, lexerActionExecutor, startIndex, index, line, charPos) {
	if (LexerATNSimulator.debug) {
		console.log("ACTION %s\n", lexerActionExecutor);
	}
	// seek to after last char in token
	input.seek(index);
	this.line = line;
	this.column = charPos;
	if (lexerActionExecutor !== null && this.recog !== null) {
		lexerActionExecutor.execute(this.recog, input, startIndex);
	}
};

LexerATNSimulator.prototype.getReachableTarget = function (trans, t) {
	if (trans.matches(t, 0, Lexer.MAX_CHAR_VALUE)) {
		return trans.target;
	} else {
		return null;
	}
};

LexerATNSimulator.prototype.computeStartState = function (input, p) {
	var initialContext = PredictionContext.EMPTY;
	var configs = new OrderedATNConfigSet();
	for (var i = 0; i < p.transitions.length; i++) {
		var target = p.transitions[i].target;
		var cfg = new LexerATNConfig({ state: target, alt: i + 1, context: initialContext }, null);
		this.closure(input, cfg, configs, false, false, false);
	}
	return configs;
};

// Since the alternatives within any lexer decision are ordered by
// preference, this method stops pursuing the closure as soon as an accept
// state is reached. After the first accept state is reached by depth-first
// search from {@code config}, all other (potentially reachable) states for
// this rule would have a lower priority.
//
// @return {@code true} if an accept state is reached, otherwise
// {@code false}.
LexerATNSimulator.prototype.closure = function (input, config, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon) {
	var cfg = null;
	if (LexerATNSimulator.debug) {
		console.log("closure(" + config.toString(this.recog, true) + ")");
	}
	if (config.state instanceof RuleStopState) {
		if (LexerATNSimulator.debug) {
			if (this.recog !== null) {
				console.log("closure at %s rule stop %s\n", this.recog.ruleNames[config.state.ruleIndex], config);
			} else {
				console.log("closure at rule stop %s\n", config);
			}
		}
		if (config.context === null || config.context.hasEmptyPath()) {
			if (config.context === null || config.context.isEmpty()) {
				configs.add(config);
				return true;
			} else {
				configs.add(new LexerATNConfig({ state: config.state, context: PredictionContext.EMPTY }, config));
				currentAltReachedAcceptState = true;
			}
		}
		if (config.context !== null && !config.context.isEmpty()) {
			for (var i = 0; i < config.context.length; i++) {
				if (config.context.getReturnState(i) !== PredictionContext.EMPTY_RETURN_STATE) {
					var newContext = config.context.getParent(i); // "pop" return state
					var returnState = this.atn.states[config.context.getReturnState(i)];
					cfg = new LexerATNConfig({ state: returnState, context: newContext }, config);
					currentAltReachedAcceptState = this.closure(input, cfg, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);
				}
			}
		}
		return currentAltReachedAcceptState;
	}
	// optimization
	if (!config.state.epsilonOnlyTransitions) {
		if (!currentAltReachedAcceptState || !config.passedThroughNonGreedyDecision) {
			configs.add(config);
		}
	}
	for (var j = 0; j < config.state.transitions.length; j++) {
		var trans = config.state.transitions[j];
		cfg = this.getEpsilonTarget(input, config, trans, configs, speculative, treatEofAsEpsilon);
		if (cfg !== null) {
			currentAltReachedAcceptState = this.closure(input, cfg, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);
		}
	}
	return currentAltReachedAcceptState;
};

// side-effect: can alter configs.hasSemanticContext
LexerATNSimulator.prototype.getEpsilonTarget = function (input, config, trans, configs, speculative, treatEofAsEpsilon) {
	var cfg = null;
	if (trans.serializationType === Transition.RULE) {
		var newContext = SingletonPredictionContext.create(config.context, trans.followState.stateNumber);
		cfg = new LexerATNConfig({ state: trans.target, context: newContext }, config);
	} else if (trans.serializationType === Transition.PRECEDENCE) {
		throw "Precedence predicates are not supported in lexers.";
	} else if (trans.serializationType === Transition.PREDICATE) {
		// Track traversing semantic predicates. If we traverse,
		// we cannot add a DFA state for this "reach" computation
		// because the DFA would not test the predicate again in the
		// future. Rather than creating collections of semantic predicates
		// like v3 and testing them on prediction, v4 will test them on the
		// fly all the time using the ATN not the DFA. This is slower but
		// semantically it's not used that often. One of the key elements to
		// this predicate mechanism is not adding DFA states that see
		// predicates immediately afterwards in the ATN. For example,

		// a : ID {p1}? | ID {p2}? ;

		// should create the start state for rule 'a' (to save start state
		// competition), but should not create target of ID state. The
		// collection of ATN states the following ID references includes
		// states reached by traversing predicates. Since this is when we
		// test them, we cannot cash the DFA state target of ID.

		if (LexerATNSimulator.debug) {
			console.log("EVAL rule " + trans.ruleIndex + ":" + trans.predIndex);
		}
		configs.hasSemanticContext = true;
		if (this.evaluatePredicate(input, trans.ruleIndex, trans.predIndex, speculative)) {
			cfg = new LexerATNConfig({ state: trans.target }, config);
		}
	} else if (trans.serializationType === Transition.ACTION) {
		if (config.context === null || config.context.hasEmptyPath()) {
			// execute actions anywhere in the start rule for a token.
			//
			// TODO: if the entry rule is invoked recursively, some
			// actions may be executed during the recursive call. The
			// problem can appear when hasEmptyPath() is true but
			// isEmpty() is false. In this case, the config needs to be
			// split into two contexts - one with just the empty path
			// and another with everything but the empty path.
			// Unfortunately, the current algorithm does not allow
			// getEpsilonTarget to return two configurations, so
			// additional modifications are needed before we can support
			// the split operation.
			var lexerActionExecutor = LexerActionExecutor.append(config.lexerActionExecutor, this.atn.lexerActions[trans.actionIndex]);
			cfg = new LexerATNConfig({ state: trans.target, lexerActionExecutor: lexerActionExecutor }, config);
		} else {
			// ignore actions in referenced rules
			cfg = new LexerATNConfig({ state: trans.target }, config);
		}
	} else if (trans.serializationType === Transition.EPSILON) {
		cfg = new LexerATNConfig({ state: trans.target }, config);
	} else if (trans.serializationType === Transition.ATOM || trans.serializationType === Transition.RANGE || trans.serializationType === Transition.SET) {
		if (treatEofAsEpsilon) {
			if (trans.matches(Token.EOF, 0, Lexer.MAX_CHAR_VALUE)) {
				cfg = new LexerATNConfig({ state: trans.target }, config);
			}
		}
	}
	return cfg;
};

// Evaluate a predicate specified in the lexer.
//
// <p>If {@code speculative} is {@code true}, this method was called before
// {@link //consume} for the matched character. This method should call
// {@link //consume} before evaluating the predicate to ensure position
// sensitive values, including {@link Lexer//getText}, {@link Lexer//getLine},
// and {@link Lexer//getcolumn}, properly reflect the current
// lexer state. This method should restore {@code input} and the simulator
// to the original state before returning (i.e. undo the actions made by the
// call to {@link //consume}.</p>
//
// @param input The input stream.
// @param ruleIndex The rule containing the predicate.
// @param predIndex The index of the predicate within the rule.
// @param speculative {@code true} if the current index in {@code input} is
// one character before the predicate's location.
//
// @return {@code true} if the specified predicate evaluates to
// {@code true}.
// /
LexerATNSimulator.prototype.evaluatePredicate = function (input, ruleIndex, predIndex, speculative) {
	// assume true if no recognizer was provided
	if (this.recog === null) {
		return true;
	}
	if (!speculative) {
		return this.recog.sempred(null, ruleIndex, predIndex);
	}
	var savedcolumn = this.column;
	var savedLine = this.line;
	var index = input.index;
	var marker = input.mark();
	try {
		this.consume(input);
		return this.recog.sempred(null, ruleIndex, predIndex);
	} finally {
		this.column = savedcolumn;
		this.line = savedLine;
		input.seek(index);
		input.release(marker);
	}
};

LexerATNSimulator.prototype.captureSimState = function (settings, input, dfaState) {
	settings.index = input.index;
	settings.line = this.line;
	settings.column = this.column;
	settings.dfaState = dfaState;
};

LexerATNSimulator.prototype.addDFAEdge = function (from_, tk, to, cfgs) {
	if (to === undefined) {
		to = null;
	}
	if (cfgs === undefined) {
		cfgs = null;
	}
	if (to === null && cfgs !== null) {
		// leading to this call, ATNConfigSet.hasSemanticContext is used as a
		// marker indicating dynamic predicate evaluation makes this edge
		// dependent on the specific input sequence, so the static edge in the
		// DFA should be omitted. The target DFAState is still created since
		// execATN has the ability to resynchronize with the DFA state cache
		// following the predicate evaluation step.
		//
		// TJP notes: next time through the DFA, we see a pred again and eval.
		// If that gets us to a previously created (but dangling) DFA
		// state, we can continue in pure DFA mode from there.
		// /
		var suppressEdge = cfgs.hasSemanticContext;
		cfgs.hasSemanticContext = false;

		to = this.addDFAState(cfgs);

		if (suppressEdge) {
			return to;
		}
	}
	// add the edge
	if (tk < LexerATNSimulator.MIN_DFA_EDGE || tk > LexerATNSimulator.MAX_DFA_EDGE) {
		// Only track edges within the DFA bounds
		return to;
	}
	if (LexerATNSimulator.debug) {
		console.log("EDGE " + from_ + " -> " + to + " upon " + tk);
	}
	if (from_.edges === null) {
		// make room for tokens 1..n and -1 masquerading as index 0
		from_.edges = [];
	}
	from_.edges[tk - LexerATNSimulator.MIN_DFA_EDGE] = to; // connect

	return to;
};

// Add a new DFA state if there isn't one with this set of
// configurations already. This method also detects the first
// configuration containing an ATN rule stop state. Later, when
// traversing the DFA, we will know which rule to accept.
LexerATNSimulator.prototype.addDFAState = function (configs) {
	var proposed = new DFAState(null, configs);
	var firstConfigWithRuleStopState = null;
	for (var i = 0; i < configs.items.length; i++) {
		var cfg = configs.items[i];
		if (cfg.state instanceof RuleStopState) {
			firstConfigWithRuleStopState = cfg;
			break;
		}
	}
	if (firstConfigWithRuleStopState !== null) {
		proposed.isAcceptState = true;
		proposed.lexerActionExecutor = firstConfigWithRuleStopState.lexerActionExecutor;
		proposed.prediction = this.atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex];
	}
	var dfa = this.decisionToDFA[this.mode];
	var existing = dfa.states.get(proposed);
	if (existing !== null) {
		return existing;
	}
	var newState = proposed;
	newState.stateNumber = dfa.states.length;
	configs.setReadonly(true);
	newState.configs = configs;
	dfa.states.add(newState);
	return newState;
};

LexerATNSimulator.prototype.getDFA = function (mode) {
	return this.decisionToDFA[mode];
};

// Get the text matched so far for the current token.
LexerATNSimulator.prototype.getText = function (input) {
	// index is first lookahead char, don't include.
	return input.getText(this.startIndex, input.index - 1);
};

LexerATNSimulator.prototype.consume = function (input) {
	var curChar = input.LA(1);
	if (curChar === "\n".charCodeAt(0)) {
		this.line += 1;
		this.column = 0;
	} else {
		this.column += 1;
	}
	input.consume();
};

LexerATNSimulator.prototype.getTokenName = function (tt) {
	if (tt === -1) {
		return "EOF";
	} else {
		return "'" + String.fromCharCode(tt) + "'";
	}
};

exports.LexerATNSimulator = LexerATNSimulator;

/***/ }),

/***/ "./node_modules/antlr4/atn/LexerAction.js":
/*!************************************************!*\
  !*** ./node_modules/antlr4/atn/LexerAction.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

function LexerActionType() {}

LexerActionType.CHANNEL = 0; //The type of a {@link LexerChannelAction} action.
LexerActionType.CUSTOM = 1; //The type of a {@link LexerCustomAction} action.
LexerActionType.MODE = 2; //The type of a {@link LexerModeAction} action.
LexerActionType.MORE = 3; //The type of a {@link LexerMoreAction} action.
LexerActionType.POP_MODE = 4; //The type of a {@link LexerPopModeAction} action.
LexerActionType.PUSH_MODE = 5; //The type of a {@link LexerPushModeAction} action.
LexerActionType.SKIP = 6; //The type of a {@link LexerSkipAction} action.
LexerActionType.TYPE = 7; //The type of a {@link LexerTypeAction} action.

function LexerAction(action) {
    this.actionType = action;
    this.isPositionDependent = false;
    return this;
}

LexerAction.prototype.hashCode = function () {
    var hash = new Hash();
    this.updateHashCode(hash);
    return hash.finish();
};

LexerAction.prototype.updateHashCode = function (hash) {
    hash.update(this.actionType);
};

LexerAction.prototype.equals = function (other) {
    return this === other;
};

//
// Implements the {@code skip} lexer action by calling {@link Lexer//skip}.
//
// <p>The {@code skip} command does not have any parameters, so this action is
// implemented as a singleton instance exposed by {@link //INSTANCE}.</p>
function LexerSkipAction() {
    LexerAction.call(this, LexerActionType.SKIP);
    return this;
}

LexerSkipAction.prototype = Object.create(LexerAction.prototype);
LexerSkipAction.prototype.constructor = LexerSkipAction;

// Provides a singleton instance of this parameterless lexer action.
LexerSkipAction.INSTANCE = new LexerSkipAction();

LexerSkipAction.prototype.execute = function (lexer) {
    lexer.skip();
};

LexerSkipAction.prototype.toString = function () {
    return "skip";
};

//  Implements the {@code type} lexer action by calling {@link Lexer//setType}
// with the assigned type.
function LexerTypeAction(type) {
    LexerAction.call(this, LexerActionType.TYPE);
    this.type = type;
    return this;
}

LexerTypeAction.prototype = Object.create(LexerAction.prototype);
LexerTypeAction.prototype.constructor = LexerTypeAction;

LexerTypeAction.prototype.execute = function (lexer) {
    lexer.type = this.type;
};

LexerTypeAction.prototype.updateHashCode = function (hash) {
    hash.update(this.actionType, this.type);
};

LexerTypeAction.prototype.equals = function (other) {
    if (this === other) {
        return true;
    } else if (!(other instanceof LexerTypeAction)) {
        return false;
    } else {
        return this.type === other.type;
    }
};

LexerTypeAction.prototype.toString = function () {
    return "type(" + this.type + ")";
};

// Implements the {@code pushMode} lexer action by calling
// {@link Lexer//pushMode} with the assigned mode.
function LexerPushModeAction(mode) {
    LexerAction.call(this, LexerActionType.PUSH_MODE);
    this.mode = mode;
    return this;
}

LexerPushModeAction.prototype = Object.create(LexerAction.prototype);
LexerPushModeAction.prototype.constructor = LexerPushModeAction;

// <p>This action is implemented by calling {@link Lexer//pushMode} with the
// value provided by {@link //getMode}.</p>
LexerPushModeAction.prototype.execute = function (lexer) {
    lexer.pushMode(this.mode);
};

LexerPushModeAction.prototype.updateHashCode = function (hash) {
    hash.update(this.actionType, this.mode);
};

LexerPushModeAction.prototype.equals = function (other) {
    if (this === other) {
        return true;
    } else if (!(other instanceof LexerPushModeAction)) {
        return false;
    } else {
        return this.mode === other.mode;
    }
};

LexerPushModeAction.prototype.toString = function () {
    return "pushMode(" + this.mode + ")";
};

// Implements the {@code popMode} lexer action by calling {@link Lexer//popMode}.
//
// <p>The {@code popMode} command does not have any parameters, so this action is
// implemented as a singleton instance exposed by {@link //INSTANCE}.</p>
function LexerPopModeAction() {
    LexerAction.call(this, LexerActionType.POP_MODE);
    return this;
}

LexerPopModeAction.prototype = Object.create(LexerAction.prototype);
LexerPopModeAction.prototype.constructor = LexerPopModeAction;

LexerPopModeAction.INSTANCE = new LexerPopModeAction();

// <p>This action is implemented by calling {@link Lexer//popMode}.</p>
LexerPopModeAction.prototype.execute = function (lexer) {
    lexer.popMode();
};

LexerPopModeAction.prototype.toString = function () {
    return "popMode";
};

// Implements the {@code more} lexer action by calling {@link Lexer//more}.
//
// <p>The {@code more} command does not have any parameters, so this action is
// implemented as a singleton instance exposed by {@link //INSTANCE}.</p>
function LexerMoreAction() {
    LexerAction.call(this, LexerActionType.MORE);
    return this;
}

LexerMoreAction.prototype = Object.create(LexerAction.prototype);
LexerMoreAction.prototype.constructor = LexerMoreAction;

LexerMoreAction.INSTANCE = new LexerMoreAction();

// <p>This action is implemented by calling {@link Lexer//popMode}.</p>
LexerMoreAction.prototype.execute = function (lexer) {
    lexer.more();
};

LexerMoreAction.prototype.toString = function () {
    return "more";
};

// Implements the {@code mode} lexer action by calling {@link Lexer//mode} with
// the assigned mode.
function LexerModeAction(mode) {
    LexerAction.call(this, LexerActionType.MODE);
    this.mode = mode;
    return this;
}

LexerModeAction.prototype = Object.create(LexerAction.prototype);
LexerModeAction.prototype.constructor = LexerModeAction;

// <p>This action is implemented by calling {@link Lexer//mode} with the
// value provided by {@link //getMode}.</p>
LexerModeAction.prototype.execute = function (lexer) {
    lexer.mode(this.mode);
};

LexerModeAction.prototype.updateHashCode = function (hash) {
    hash.update(this.actionType, this.mode);
};

LexerModeAction.prototype.equals = function (other) {
    if (this === other) {
        return true;
    } else if (!(other instanceof LexerModeAction)) {
        return false;
    } else {
        return this.mode === other.mode;
    }
};

LexerModeAction.prototype.toString = function () {
    return "mode(" + this.mode + ")";
};

// Executes a custom lexer action by calling {@link Recognizer//action} with the
// rule and action indexes assigned to the custom action. The implementation of
// a custom action is added to the generated code for the lexer in an override
// of {@link Recognizer//action} when the grammar is compiled.
//
// <p>This class may represent embedded actions created with the <code>{...}</code>
// syntax in ANTLR 4, as well as actions created for lexer commands where the
// command argument could not be evaluated when the grammar was compiled.</p>


// Constructs a custom lexer action with the specified rule and action
// indexes.
//
// @param ruleIndex The rule index to use for calls to
// {@link Recognizer//action}.
// @param actionIndex The action index to use for calls to
// {@link Recognizer//action}.

function LexerCustomAction(ruleIndex, actionIndex) {
    LexerAction.call(this, LexerActionType.CUSTOM);
    this.ruleIndex = ruleIndex;
    this.actionIndex = actionIndex;
    this.isPositionDependent = true;
    return this;
}

LexerCustomAction.prototype = Object.create(LexerAction.prototype);
LexerCustomAction.prototype.constructor = LexerCustomAction;

// <p>Custom actions are implemented by calling {@link Lexer//action} with the
// appropriate rule and action indexes.</p>
LexerCustomAction.prototype.execute = function (lexer) {
    lexer.action(null, this.ruleIndex, this.actionIndex);
};

LexerCustomAction.prototype.updateHashCode = function (hash) {
    hash.update(this.actionType, this.ruleIndex, this.actionIndex);
};

LexerCustomAction.prototype.equals = function (other) {
    if (this === other) {
        return true;
    } else if (!(other instanceof LexerCustomAction)) {
        return false;
    } else {
        return this.ruleIndex === other.ruleIndex && this.actionIndex === other.actionIndex;
    }
};

// Implements the {@code channel} lexer action by calling
// {@link Lexer//setChannel} with the assigned channel.
// Constructs a new {@code channel} action with the specified channel value.
// @param channel The channel value to pass to {@link Lexer//setChannel}.
function LexerChannelAction(channel) {
    LexerAction.call(this, LexerActionType.CHANNEL);
    this.channel = channel;
    return this;
}

LexerChannelAction.prototype = Object.create(LexerAction.prototype);
LexerChannelAction.prototype.constructor = LexerChannelAction;

// <p>This action is implemented by calling {@link Lexer//setChannel} with the
// value provided by {@link //getChannel}.</p>
LexerChannelAction.prototype.execute = function (lexer) {
    lexer._channel = this.channel;
};

LexerChannelAction.prototype.updateHashCode = function (hash) {
    hash.update(this.actionType, this.channel);
};

LexerChannelAction.prototype.equals = function (other) {
    if (this === other) {
        return true;
    } else if (!(other instanceof LexerChannelAction)) {
        return false;
    } else {
        return this.channel === other.channel;
    }
};

LexerChannelAction.prototype.toString = function () {
    return "channel(" + this.channel + ")";
};

// This implementation of {@link LexerAction} is used for tracking input offsets
// for position-dependent actions within a {@link LexerActionExecutor}.
//
// <p>This action is not serialized as part of the ATN, and is only required for
// position-dependent lexer actions which appear at a location other than the
// end of a rule. For more information about DFA optimizations employed for
// lexer actions, see {@link LexerActionExecutor//append} and
// {@link LexerActionExecutor//fixOffsetBeforeMatch}.</p>

// Constructs a new indexed custom action by associating a character offset
// with a {@link LexerAction}.
//
// <p>Note: This class is only required for lexer actions for which
// {@link LexerAction//isPositionDependent} returns {@code true}.</p>
//
// @param offset The offset into the input {@link CharStream}, relative to
// the token start index, at which the specified lexer action should be
// executed.
// @param action The lexer action to execute at a particular offset in the
// input {@link CharStream}.
function LexerIndexedCustomAction(offset, action) {
    LexerAction.call(this, action.actionType);
    this.offset = offset;
    this.action = action;
    this.isPositionDependent = true;
    return this;
}

LexerIndexedCustomAction.prototype = Object.create(LexerAction.prototype);
LexerIndexedCustomAction.prototype.constructor = LexerIndexedCustomAction;

// <p>This method calls {@link //execute} on the result of {@link //getAction}
// using the provided {@code lexer}.</p>
LexerIndexedCustomAction.prototype.execute = function (lexer) {
    // assume the input stream position was properly set by the calling code
    this.action.execute(lexer);
};

LexerIndexedCustomAction.prototype.updateHashCode = function (hash) {
    hash.update(this.actionType, this.offset, this.action);
};

LexerIndexedCustomAction.prototype.equals = function (other) {
    if (this === other) {
        return true;
    } else if (!(other instanceof LexerIndexedCustomAction)) {
        return false;
    } else {
        return this.offset === other.offset && this.action === other.action;
    }
};

exports.LexerActionType = LexerActionType;
exports.LexerSkipAction = LexerSkipAction;
exports.LexerChannelAction = LexerChannelAction;
exports.LexerCustomAction = LexerCustomAction;
exports.LexerIndexedCustomAction = LexerIndexedCustomAction;
exports.LexerMoreAction = LexerMoreAction;
exports.LexerTypeAction = LexerTypeAction;
exports.LexerPushModeAction = LexerPushModeAction;
exports.LexerPopModeAction = LexerPopModeAction;
exports.LexerModeAction = LexerModeAction;

/***/ }),

/***/ "./node_modules/antlr4/atn/LexerActionExecutor.js":
/*!********************************************************!*\
  !*** ./node_modules/antlr4/atn/LexerActionExecutor.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

// Represents an executor for a sequence of lexer actions which traversed during
// the matching operation of a lexer rule (token).
//
// <p>The executor tracks position information for position-dependent lexer actions
// efficiently, ensuring that actions appearing only at the end of the rule do
// not cause bloating of the {@link DFA} created for the lexer.</p>

var hashStuff = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").hashStuff;
var LexerIndexedCustomAction = __webpack_require__(/*! ./LexerAction */ "./node_modules/antlr4/atn/LexerAction.js").LexerIndexedCustomAction;

function LexerActionExecutor(lexerActions) {
	this.lexerActions = lexerActions === null ? [] : lexerActions;
	// Caches the result of {@link //hashCode} since the hash code is an element
	// of the performance-critical {@link LexerATNConfig//hashCode} operation.
	this.cachedHashCode = hashStuff(lexerActions); // "".join([str(la) for la in
	// lexerActions]))
	return this;
}

// Creates a {@link LexerActionExecutor} which executes the actions for
// the input {@code lexerActionExecutor} followed by a specified
// {@code lexerAction}.
//
// @param lexerActionExecutor The executor for actions already traversed by
// the lexer while matching a token within a particular
// {@link LexerATNConfig}. If this is {@code null}, the method behaves as
// though it were an empty executor.
// @param lexerAction The lexer action to execute after the actions
// specified in {@code lexerActionExecutor}.
//
// @return A {@link LexerActionExecutor} for executing the combine actions
// of {@code lexerActionExecutor} and {@code lexerAction}.
LexerActionExecutor.append = function (lexerActionExecutor, lexerAction) {
	if (lexerActionExecutor === null) {
		return new LexerActionExecutor([lexerAction]);
	}
	var lexerActions = lexerActionExecutor.lexerActions.concat([lexerAction]);
	return new LexerActionExecutor(lexerActions);
};

// Creates a {@link LexerActionExecutor} which encodes the current offset
// for position-dependent lexer actions.
//
// <p>Normally, when the executor encounters lexer actions where
// {@link LexerAction//isPositionDependent} returns {@code true}, it calls
// {@link IntStream//seek} on the input {@link CharStream} to set the input
// position to the <em>end</em> of the current token. This behavior provides
// for efficient DFA representation of lexer actions which appear at the end
// of a lexer rule, even when the lexer rule matches a variable number of
// characters.</p>
//
// <p>Prior to traversing a match transition in the ATN, the current offset
// from the token start index is assigned to all position-dependent lexer
// actions which have not already been assigned a fixed offset. By storing
// the offsets relative to the token start index, the DFA representation of
// lexer actions which appear in the middle of tokens remains efficient due
// to sharing among tokens of the same length, regardless of their absolute
// position in the input stream.</p>
//
// <p>If the current executor already has offsets assigned to all
// position-dependent lexer actions, the method returns {@code this}.</p>
//
// @param offset The current offset to assign to all position-dependent
// lexer actions which do not already have offsets assigned.
//
// @return A {@link LexerActionExecutor} which stores input stream offsets
// for all position-dependent lexer actions.
// /
LexerActionExecutor.prototype.fixOffsetBeforeMatch = function (offset) {
	var updatedLexerActions = null;
	for (var i = 0; i < this.lexerActions.length; i++) {
		if (this.lexerActions[i].isPositionDependent && !(this.lexerActions[i] instanceof LexerIndexedCustomAction)) {
			if (updatedLexerActions === null) {
				updatedLexerActions = this.lexerActions.concat([]);
			}
			updatedLexerActions[i] = new LexerIndexedCustomAction(offset, this.lexerActions[i]);
		}
	}
	if (updatedLexerActions === null) {
		return this;
	} else {
		return new LexerActionExecutor(updatedLexerActions);
	}
};

// Execute the actions encapsulated by this executor within the context of a
// particular {@link Lexer}.
//
// <p>This method calls {@link IntStream//seek} to set the position of the
// {@code input} {@link CharStream} prior to calling
// {@link LexerAction//execute} on a position-dependent action. Before the
// method returns, the input position will be restored to the same position
// it was in when the method was invoked.</p>
//
// @param lexer The lexer instance.
// @param input The input stream which is the source for the current token.
// When this method is called, the current {@link IntStream//index} for
// {@code input} should be the start of the following token, i.e. 1
// character past the end of the current token.
// @param startIndex The token start index. This value may be passed to
// {@link IntStream//seek} to set the {@code input} position to the beginning
// of the token.
// /
LexerActionExecutor.prototype.execute = function (lexer, input, startIndex) {
	var requiresSeek = false;
	var stopIndex = input.index;
	try {
		for (var i = 0; i < this.lexerActions.length; i++) {
			var lexerAction = this.lexerActions[i];
			if (lexerAction instanceof LexerIndexedCustomAction) {
				var offset = lexerAction.offset;
				input.seek(startIndex + offset);
				lexerAction = lexerAction.action;
				requiresSeek = startIndex + offset !== stopIndex;
			} else if (lexerAction.isPositionDependent) {
				input.seek(stopIndex);
				requiresSeek = false;
			}
			lexerAction.execute(lexer);
		}
	} finally {
		if (requiresSeek) {
			input.seek(stopIndex);
		}
	}
};

LexerActionExecutor.prototype.hashCode = function () {
	return this.cachedHashCode;
};

LexerActionExecutor.prototype.updateHashCode = function (hash) {
	hash.update(this.cachedHashCode);
};

LexerActionExecutor.prototype.equals = function (other) {
	if (this === other) {
		return true;
	} else if (!(other instanceof LexerActionExecutor)) {
		return false;
	} else if (this.cachedHashCode != other.cachedHashCode) {
		return false;
	} else if (this.lexerActions.length != other.lexerActions.length) {
		return false;
	} else {
		var numActions = this.lexerActions.length;
		for (var idx = 0; idx < numActions; ++idx) {
			if (!this.lexerActions[idx].equals(other.lexerActions[idx])) {
				return false;
			}
		}
		return true;
	}
};

exports.LexerActionExecutor = LexerActionExecutor;

/***/ }),

/***/ "./node_modules/antlr4/atn/ParserATNSimulator.js":
/*!*******************************************************!*\
  !*** ./node_modules/antlr4/atn/ParserATNSimulator.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

//
// The embodiment of the adaptive LL(*), ALL(*), parsing strategy.
//
// <p>
// The basic complexity of the adaptive strategy makes it harder to understand.
// We begin with ATN simulation to build paths in a DFA. Subsequent prediction
// requests go through the DFA first. If they reach a state without an edge for
// the current symbol, the algorithm fails over to the ATN simulation to
// complete the DFA path for the current input (until it finds a conflict state
// or uniquely predicting state).</p>
//
// <p>
// All of that is done without using the outer context because we want to create
// a DFA that is not dependent upon the rule invocation stack when we do a
// prediction. One DFA works in all contexts. We avoid using context not
// necessarily because it's slower, although it can be, but because of the DFA
// caching problem. The closure routine only considers the rule invocation stack
// created during prediction beginning in the decision rule. For example, if
// prediction occurs without invoking another rule's ATN, there are no context
// stacks in the configurations. When lack of context leads to a conflict, we
// don't know if it's an ambiguity or a weakness in the strong LL(*) parsing
// strategy (versus full LL(*)).</p>
//
// <p>
// When SLL yields a configuration set with conflict, we rewind the input and
// retry the ATN simulation, this time using full outer context without adding
// to the DFA. Configuration context stacks will be the full invocation stacks
// from the start rule. If we get a conflict using full context, then we can
// definitively say we have a true ambiguity for that input sequence. If we
// don't get a conflict, it implies that the decision is sensitive to the outer
// context. (It is not context-sensitive in the sense of context-sensitive
// grammars.)</p>
//
// <p>
// The next time we reach this DFA state with an SLL conflict, through DFA
// simulation, we will again retry the ATN simulation using full context mode.
// This is slow because we can't save the results and have to "interpret" the
// ATN each time we get that input.</p>
//
// <p>
// <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>
//
// <p>
// We could cache results from full context to predicted alternative easily and
// that saves a lot of time but doesn't work in presence of predicates. The set
// of visible predicates from the ATN start state changes depending on the
// context, because closure can fall off the end of a rule. I tried to cache
// tuples (stack context, semantic context, predicted alt) but it was slower
// than interpreting and much more complicated. Also required a huge amount of
// memory. The goal is not to create the world's fastest parser anyway. I'd like
// to keep this algorithm simple. By launching multiple threads, we can improve
// the speed of parsing across a large number of files.</p>
//
// <p>
// There is no strict ordering between the amount of input used by SLL vs LL,
// which makes it really hard to build a cache for full context. Let's say that
// we have input A B C that leads to an SLL conflict with full context X. That
// implies that using X we might only use A B but we could also use A B C D to
// resolve conflict. Input A B C D could predict alternative 1 in one position
// in the input and A B C E could predict alternative 2 in another position in
// input. The conflicting SLL configurations could still be non-unique in the
// full context prediction, which would lead us to requiring more input than the
// original A B C.	To make a	prediction cache work, we have to track	the exact
// input	used during the previous prediction. That amounts to a cache that maps
// X to a specific DFA for that context.</p>
//
// <p>
// Something should be done for left-recursive expression predictions. They are
// likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry
// with full LL thing Sam does.</p>
//
// <p>
// <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>
//
// <p>
// We avoid doing full context retry when the outer context is empty, we did not
// dip into the outer context by falling off the end of the decision state rule,
// or when we force SLL mode.</p>
//
// <p>
// As an example of the not dip into outer context case, consider as super
// constructor calls versus function calls. One grammar might look like
// this:</p>
//
// <pre>
// ctorBody
//   : '{' superCall? stat* '}'
//   ;
// </pre>
//
// <p>
// Or, you might see something like</p>
//
// <pre>
// stat
//   : superCall ';'
//   | expression ';'
//   | ...
//   ;
// </pre>
//
// <p>
// In both cases I believe that no closure operations will dip into the outer
// context. In the first case ctorBody in the worst case will stop at the '}'.
// In the 2nd case it should stop at the ';'. Both cases should stay within the
// entry rule and not dip into the outer context.</p>
//
// <p>
// <strong>PREDICATES</strong></p>
//
// <p>
// Predicates are always evaluated if present in either SLL or LL both. SLL and
// LL simulation deals with predicates differently. SLL collects predicates as
// it performs closure operations like ANTLR v3 did. It delays predicate
// evaluation until it reaches and accept state. This allows us to cache the SLL
// ATN simulation whereas, if we had evaluated predicates on-the-fly during
// closure, the DFA state configuration sets would be different and we couldn't
// build up a suitable DFA.</p>
//
// <p>
// When building a DFA accept state during ATN simulation, we evaluate any
// predicates and return the sole semantically valid alternative. If there is
// more than 1 alternative, we report an ambiguity. If there are 0 alternatives,
// we throw an exception. Alternatives without predicates act like they have
// true predicates. The simple way to think about it is to strip away all
// alternatives with false predicates and choose the minimum alternative that
// remains.</p>
//
// <p>
// When we start in the DFA and reach an accept state that's predicated, we test
// those and return the minimum semantically viable alternative. If no
// alternatives are viable, we throw an exception.</p>
//
// <p>
// During full LL ATN simulation, closure always evaluates predicates and
// on-the-fly. This is crucial to reducing the configuration set size during
// closure. It hits a landmine when parsing with the Java grammar, for example,
// without this on-the-fly evaluation.</p>
//
// <p>
// <strong>SHARING DFA</strong></p>
//
// <p>
// All instances of the same parser share the same decision DFAs through a
// static field. Each instance gets its own ATN simulator but they share the
// same {@link //decisionToDFA} field. They also share a
// {@link PredictionContextCache} object that makes sure that all
// {@link PredictionContext} objects are shared among the DFA states. This makes
// a big size difference.</p>
//
// <p>
// <strong>THREAD SAFETY</strong></p>
//
// <p>
// The {@link ParserATNSimulator} locks on the {@link //decisionToDFA} field when
// it adds a new DFA object to that array. {@link //addDFAEdge}
// locks on the DFA for the current decision when setting the
// {@link DFAState//edges} field. {@link //addDFAState} locks on
// the DFA for the current decision when looking up a DFA state to see if it
// already exists. We must make sure that all requests to add DFA states that
// are equivalent result in the same shared DFA object. This is because lots of
// threads will be trying to update the DFA at once. The
// {@link //addDFAState} method also locks inside the DFA lock
// but this time on the shared context cache when it rebuilds the
// configurations' {@link PredictionContext} objects using cached
// subgraphs/nodes. No other locking occurs, even during DFA simulation. This is
// safe as long as we can guarantee that all threads referencing
// {@code s.edge[t]} get the same physical target {@link DFAState}, or
// {@code null}. Once into the DFA, the DFA simulation does not reference the
// {@link DFA//states} map. It follows the {@link DFAState//edges} field to new
// targets. The DFA simulator will either find {@link DFAState//edges} to be
// {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or
// {@code dfa.edges[t]} to be non-null. The
// {@link //addDFAEdge} method could be racing to set the field
// but in either case the DFA simulator works; if {@code null}, and requests ATN
// simulation. It could also race trying to get {@code dfa.edges[t]}, but either
// way it will work because it's not doing a test and set operation.</p>
//
// <p>
// <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage
// Parsing)</strong></p>
//
// <p>
// Sam pointed out that if SLL does not give a syntax error, then there is no
// point in doing full LL, which is slower. We only have to try LL if we get a
// syntax error. For maximum speed, Sam starts the parser set to pure SLL
// mode with the {@link BailErrorStrategy}:</p>
//
// <pre>
// parser.{@link Parser//getInterpreter() getInterpreter()}.{@link //setPredictionMode setPredictionMode}{@code (}{@link PredictionMode//SLL}{@code )};
// parser.{@link Parser//setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());
// </pre>
//
// <p>
// If it does not get a syntax error, then we're done. If it does get a syntax
// error, we need to retry with the combined SLL/LL strategy.</p>
//
// <p>
// The reason this works is as follows. If there are no SLL conflicts, then the
// grammar is SLL (at least for that input set). If there is an SLL conflict,
// the full LL analysis must yield a set of viable alternatives which is a
// subset of the alternatives reported by SLL. If the LL set is a singleton,
// then the grammar is LL but not SLL. If the LL set is the same size as the SLL
// set, the decision is SLL. If the LL set has size &gt; 1, then that decision
// is truly ambiguous on the current input. If the LL set is smaller, then the
// SLL conflict resolution might choose an alternative that the full LL would
// rule out as a possibility based upon better context information. If that's
// the case, then the SLL parse will definitely get an error because the full LL
// analysis says it's not viable. If SLL conflict resolution chooses an
// alternative within the LL set, them both SLL and LL would choose the same
// alternative because they both choose the minimum of multiple conflicting
// alternatives.</p>
//
// <p>
// Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and
// a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL
// parsing will get an error because SLL will pursue alternative 1. If
// <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will
// choose the same alternative because alternative one is the minimum of either
// set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax
// error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>
//
// <p>
// Of course, if the input is invalid, then we will get an error for sure in
// both SLL and LL parsing. Erroneous input will therefore require 2 passes over
// the input.</p>
//

var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
var Set = Utils.Set;
var BitSet = Utils.BitSet;
var DoubleDict = Utils.DoubleDict;
var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
var ATNState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").ATNState;
var ATNConfig = __webpack_require__(/*! ./ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").ATNConfig;
var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
var DFAState = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
var PredPrediction = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").PredPrediction;
var ATNSimulator = __webpack_require__(/*! ./ATNSimulator */ "./node_modules/antlr4/atn/ATNSimulator.js").ATNSimulator;
var PredictionMode = __webpack_require__(/*! ./PredictionMode */ "./node_modules/antlr4/atn/PredictionMode.js").PredictionMode;
var RuleContext = __webpack_require__(/*! ./../RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
var ParserRuleContext = __webpack_require__(/*! ./../ParserRuleContext */ "./node_modules/antlr4/ParserRuleContext.js").ParserRuleContext;
var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
var StarLoopEntryState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").StarLoopEntryState;
var RuleStopState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
var PredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").PredictionContext;
var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
var Transitions = __webpack_require__(/*! ./Transition */ "./node_modules/antlr4/atn/Transition.js");
var Transition = Transitions.Transition;
var SetTransition = Transitions.SetTransition;
var NotSetTransition = Transitions.NotSetTransition;
var RuleTransition = Transitions.RuleTransition;
var ActionTransition = Transitions.ActionTransition;
var NoViableAltException = __webpack_require__(/*! ./../error/Errors */ "./node_modules/antlr4/error/Errors.js").NoViableAltException;

var SingletonPredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").SingletonPredictionContext;
var predictionContextFromRuleContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").predictionContextFromRuleContext;

function ParserATNSimulator(parser, atn, decisionToDFA, sharedContextCache) {
    ATNSimulator.call(this, atn, sharedContextCache);
    this.parser = parser;
    this.decisionToDFA = decisionToDFA;
    // SLL, LL, or LL + exact ambig detection?//
    this.predictionMode = PredictionMode.LL;
    // LAME globals to avoid parameters!!!!! I need these down deep in predTransition
    this._input = null;
    this._startIndex = 0;
    this._outerContext = null;
    this._dfa = null;
    // Each prediction operation uses a cache for merge of prediction contexts.
    //  Don't keep around as it wastes huge amounts of memory. DoubleKeyMap
    //  isn't synchronized but we're ok since two threads shouldn't reuse same
    //  parser/atnsim object because it can only handle one input at a time.
    //  This maps graphs a and b to merged result c. (a,b)&rarr;c. We can avoid
    //  the merge if we ever see a and b again.  Note that (b,a)&rarr;c should
    //  also be examined during cache lookup.
    //
    this.mergeCache = null;
    return this;
}

ParserATNSimulator.prototype = Object.create(ATNSimulator.prototype);
ParserATNSimulator.prototype.constructor = ParserATNSimulator;

ParserATNSimulator.prototype.debug = false;
ParserATNSimulator.prototype.debug_closure = false;
ParserATNSimulator.prototype.debug_add = false;
ParserATNSimulator.prototype.debug_list_atn_decisions = false;
ParserATNSimulator.prototype.dfa_debug = false;
ParserATNSimulator.prototype.retry_debug = false;

ParserATNSimulator.prototype.reset = function () {};

ParserATNSimulator.prototype.adaptivePredict = function (input, decision, outerContext) {
    if (this.debug || this.debug_list_atn_decisions) {
        console.log("adaptivePredict decision " + decision + " exec LA(1)==" + this.getLookaheadName(input) + " line " + input.LT(1).line + ":" + input.LT(1).column);
    }
    this._input = input;
    this._startIndex = input.index;
    this._outerContext = outerContext;

    var dfa = this.decisionToDFA[decision];
    this._dfa = dfa;
    var m = input.mark();
    var index = input.index;

    // Now we are certain to have a specific decision's DFA
    // But, do we still need an initial state?
    try {
        var s0;
        if (dfa.precedenceDfa) {
            // the start state for a precedence DFA depends on the current
            // parser precedence, and is provided by a DFA method.
            s0 = dfa.getPrecedenceStartState(this.parser.getPrecedence());
        } else {
            // the start state for a "regular" DFA is just s0
            s0 = dfa.s0;
        }
        if (s0 === null) {
            if (outerContext === null) {
                outerContext = RuleContext.EMPTY;
            }
            if (this.debug || this.debug_list_atn_decisions) {
                console.log("predictATN decision " + dfa.decision + " exec LA(1)==" + this.getLookaheadName(input) + ", outerContext=" + outerContext.toString(this.parser.ruleNames));
            }

            var fullCtx = false;
            var s0_closure = this.computeStartState(dfa.atnStartState, RuleContext.EMPTY, fullCtx);

            if (dfa.precedenceDfa) {
                // If this is a precedence DFA, we use applyPrecedenceFilter
                // to convert the computed start state to a precedence start
                // state. We then use DFA.setPrecedenceStartState to set the
                // appropriate start state for the precedence level rather
                // than simply setting DFA.s0.
                //
                dfa.s0.configs = s0_closure; // not used for prediction but useful to know start configs anyway
                s0_closure = this.applyPrecedenceFilter(s0_closure);
                s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));
                dfa.setPrecedenceStartState(this.parser.getPrecedence(), s0);
            } else {
                s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));
                dfa.s0 = s0;
            }
        }
        var alt = this.execATN(dfa, s0, input, index, outerContext);
        if (this.debug) {
            console.log("DFA after predictATN: " + dfa.toString(this.parser.literalNames));
        }
        return alt;
    } finally {
        this._dfa = null;
        this.mergeCache = null; // wack cache after each prediction
        input.seek(index);
        input.release(m);
    }
};
// Performs ATN simulation to compute a predicted alternative based
//  upon the remaining input, but also updates the DFA cache to avoid
//  having to traverse the ATN again for the same input sequence.

// There are some key conditions we're looking for after computing a new
// set of ATN configs (proposed DFA state):
// if the set is empty, there is no viable alternative for current symbol
// does the state uniquely predict an alternative?
// does the state have a conflict that would prevent us from
//   putting it on the work list?

// We also have some key operations to do:
// add an edge from previous DFA state to potentially new DFA state, D,
//   upon current symbol but only if adding to work list, which means in all
//   cases except no viable alternative (and possibly non-greedy decisions?)
// collecting predicates and adding semantic context to DFA accept states
// adding rule context to context-sensitive DFA accept states
// consuming an input symbol
// reporting a conflict
// reporting an ambiguity
// reporting a context sensitivity
// reporting insufficient predicates

// cover these cases:
//    dead end
//    single alt
//    single alt + preds
//    conflict
//    conflict + preds
//
ParserATNSimulator.prototype.execATN = function (dfa, s0, input, startIndex, outerContext) {
    if (this.debug || this.debug_list_atn_decisions) {
        console.log("execATN decision " + dfa.decision + " exec LA(1)==" + this.getLookaheadName(input) + " line " + input.LT(1).line + ":" + input.LT(1).column);
    }
    var alt;
    var previousD = s0;

    if (this.debug) {
        console.log("s0 = " + s0);
    }
    var t = input.LA(1);
    while (true) {
        // while more work
        var D = this.getExistingTargetState(previousD, t);
        if (D === null) {
            D = this.computeTargetState(dfa, previousD, t);
        }
        if (D === ATNSimulator.ERROR) {
            // if any configs in previous dipped into outer context, that
            // means that input up to t actually finished entry rule
            // at least for SLL decision. Full LL doesn't dip into outer
            // so don't need special case.
            // We will get an error no matter what so delay until after
            // decision; better error message. Also, no reachable target
            // ATN states in SLL implies LL will also get nowhere.
            // If conflict in states that dip out, choose min since we
            // will get error no matter what.
            var e = this.noViableAlt(input, outerContext, previousD.configs, startIndex);
            input.seek(startIndex);
            alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext);
            if (alt !== ATN.INVALID_ALT_NUMBER) {
                return alt;
            } else {
                throw e;
            }
        }
        if (D.requiresFullContext && this.predictionMode !== PredictionMode.SLL) {
            // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)
            var conflictingAlts = null;
            if (D.predicates !== null) {
                if (this.debug) {
                    console.log("DFA state has preds in DFA sim LL failover");
                }
                var conflictIndex = input.index;
                if (conflictIndex !== startIndex) {
                    input.seek(startIndex);
                }
                conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true);
                if (conflictingAlts.length === 1) {
                    if (this.debug) {
                        console.log("Full LL avoided");
                    }
                    return conflictingAlts.minValue();
                }
                if (conflictIndex !== startIndex) {
                    // restore the index so reporting the fallback to full
                    // context occurs with the index at the correct spot
                    input.seek(conflictIndex);
                }
            }
            if (this.dfa_debug) {
                console.log("ctx sensitive state " + outerContext + " in " + D);
            }
            var fullCtx = true;
            var s0_closure = this.computeStartState(dfa.atnStartState, outerContext, fullCtx);
            this.reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index);
            alt = this.execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext);
            return alt;
        }
        if (D.isAcceptState) {
            if (D.predicates === null) {
                return D.prediction;
            }
            var stopIndex = input.index;
            input.seek(startIndex);
            var alts = this.evalSemanticContext(D.predicates, outerContext, true);
            if (alts.length === 0) {
                throw this.noViableAlt(input, outerContext, D.configs, startIndex);
            } else if (alts.length === 1) {
                return alts.minValue();
            } else {
                // report ambiguity after predicate evaluation to make sure the correct set of ambig alts is reported.
                this.reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs);
                return alts.minValue();
            }
        }
        previousD = D;

        if (t !== Token.EOF) {
            input.consume();
            t = input.LA(1);
        }
    }
};
//
// Get an existing target state for an edge in the DFA. If the target state
// for the edge has not yet been computed or is otherwise not available,
// this method returns {@code null}.
//
// @param previousD The current DFA state
// @param t The next input symbol
// @return The existing target DFA state for the given input symbol
// {@code t}, or {@code null} if the target state for this edge is not
// already cached
//
ParserATNSimulator.prototype.getExistingTargetState = function (previousD, t) {
    var edges = previousD.edges;
    if (edges === null) {
        return null;
    } else {
        return edges[t + 1] || null;
    }
};
//
// Compute a target state for an edge in the DFA, and attempt to add the
// computed state and corresponding edge to the DFA.
//
// @param dfa The DFA
// @param previousD The current DFA state
// @param t The next input symbol
//
// @return The computed target DFA state for the given input symbol
// {@code t}. If {@code t} does not lead to a valid DFA state, this method
// returns {@link //ERROR}.
//
ParserATNSimulator.prototype.computeTargetState = function (dfa, previousD, t) {
    var reach = this.computeReachSet(previousD.configs, t, false);
    if (reach === null) {
        this.addDFAEdge(dfa, previousD, t, ATNSimulator.ERROR);
        return ATNSimulator.ERROR;
    }
    // create new target state; we'll add to DFA after it's complete
    var D = new DFAState(null, reach);

    var predictedAlt = this.getUniqueAlt(reach);

    if (this.debug) {
        var altSubSets = PredictionMode.getConflictingAltSubsets(reach);
        console.log("SLL altSubSets=" + Utils.arrayToString(altSubSets) + ", previous=" + previousD.configs + ", configs=" + reach + ", predict=" + predictedAlt + ", allSubsetsConflict=" + PredictionMode.allSubsetsConflict(altSubSets) + ", conflictingAlts=" + this.getConflictingAlts(reach));
    }
    if (predictedAlt !== ATN.INVALID_ALT_NUMBER) {
        // NO CONFLICT, UNIQUELY PREDICTED ALT
        D.isAcceptState = true;
        D.configs.uniqueAlt = predictedAlt;
        D.prediction = predictedAlt;
    } else if (PredictionMode.hasSLLConflictTerminatingPrediction(this.predictionMode, reach)) {
        // MORE THAN ONE VIABLE ALTERNATIVE
        D.configs.conflictingAlts = this.getConflictingAlts(reach);
        D.requiresFullContext = true;
        // in SLL-only mode, we will stop at this state and return the minimum alt
        D.isAcceptState = true;
        D.prediction = D.configs.conflictingAlts.minValue();
    }
    if (D.isAcceptState && D.configs.hasSemanticContext) {
        this.predicateDFAState(D, this.atn.getDecisionState(dfa.decision));
        if (D.predicates !== null) {
            D.prediction = ATN.INVALID_ALT_NUMBER;
        }
    }
    // all adds to dfa are done after we've created full D state
    D = this.addDFAEdge(dfa, previousD, t, D);
    return D;
};

ParserATNSimulator.prototype.predicateDFAState = function (dfaState, decisionState) {
    // We need to test all predicates, even in DFA states that
    // uniquely predict alternative.
    var nalts = decisionState.transitions.length;
    // Update DFA so reach becomes accept state with (predicate,alt)
    // pairs if preds found for conflicting alts
    var altsToCollectPredsFrom = this.getConflictingAltsOrUniqueAlt(dfaState.configs);
    var altToPred = this.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts);
    if (altToPred !== null) {
        dfaState.predicates = this.getPredicatePredictions(altsToCollectPredsFrom, altToPred);
        dfaState.prediction = ATN.INVALID_ALT_NUMBER; // make sure we use preds
    } else {
        // There are preds in configs but they might go away
        // when OR'd together like {p}? || NONE == NONE. If neither
        // alt has preds, resolve to min alt
        dfaState.prediction = altsToCollectPredsFrom.minValue();
    }
};

// comes back with reach.uniqueAlt set to a valid alt
ParserATNSimulator.prototype.execATNWithFullContext = function (dfa, D, // how far we got before failing over
s0, input, startIndex, outerContext) {
    if (this.debug || this.debug_list_atn_decisions) {
        console.log("execATNWithFullContext " + s0);
    }
    var fullCtx = true;
    var foundExactAmbig = false;
    var reach = null;
    var previous = s0;
    input.seek(startIndex);
    var t = input.LA(1);
    var predictedAlt = -1;
    while (true) {
        // while more work
        reach = this.computeReachSet(previous, t, fullCtx);
        if (reach === null) {
            // if any configs in previous dipped into outer context, that
            // means that input up to t actually finished entry rule
            // at least for LL decision. Full LL doesn't dip into outer
            // so don't need special case.
            // We will get an error no matter what so delay until after
            // decision; better error message. Also, no reachable target
            // ATN states in SLL implies LL will also get nowhere.
            // If conflict in states that dip out, choose min since we
            // will get error no matter what.
            var e = this.noViableAlt(input, outerContext, previous, startIndex);
            input.seek(startIndex);
            var alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext);
            if (alt !== ATN.INVALID_ALT_NUMBER) {
                return alt;
            } else {
                throw e;
            }
        }
        var altSubSets = PredictionMode.getConflictingAltSubsets(reach);
        if (this.debug) {
            console.log("LL altSubSets=" + altSubSets + ", predict=" + PredictionMode.getUniqueAlt(altSubSets) + ", resolvesToJustOneViableAlt=" + PredictionMode.resolvesToJustOneViableAlt(altSubSets));
        }
        reach.uniqueAlt = this.getUniqueAlt(reach);
        // unique prediction?
        if (reach.uniqueAlt !== ATN.INVALID_ALT_NUMBER) {
            predictedAlt = reach.uniqueAlt;
            break;
        } else if (this.predictionMode !== PredictionMode.LL_EXACT_AMBIG_DETECTION) {
            predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets);
            if (predictedAlt !== ATN.INVALID_ALT_NUMBER) {
                break;
            }
        } else {
            // In exact ambiguity mode, we never try to terminate early.
            // Just keeps scarfing until we know what the conflict is
            if (PredictionMode.allSubsetsConflict(altSubSets) && PredictionMode.allSubsetsEqual(altSubSets)) {
                foundExactAmbig = true;
                predictedAlt = PredictionMode.getSingleViableAlt(altSubSets);
                break;
            }
            // else there are multiple non-conflicting subsets or
            // we're not sure what the ambiguity is yet.
            // So, keep going.
        }
        previous = reach;
        if (t !== Token.EOF) {
            input.consume();
            t = input.LA(1);
        }
    }
    // If the configuration set uniquely predicts an alternative,
    // without conflict, then we know that it's a full LL decision
    // not SLL.
    if (reach.uniqueAlt !== ATN.INVALID_ALT_NUMBER) {
        this.reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index);
        return predictedAlt;
    }
    // We do not check predicates here because we have checked them
    // on-the-fly when doing full context prediction.

    //
    // In non-exact ambiguity detection mode, we might	actually be able to
    // detect an exact ambiguity, but I'm not going to spend the cycles
    // needed to check. We only emit ambiguity warnings in exact ambiguity
    // mode.
    //
    // For example, we might know that we have conflicting configurations.
    // But, that does not mean that there is no way forward without a
    // conflict. It's possible to have nonconflicting alt subsets as in:

    // altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]

    // from
    //
    //    [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),
    //     (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]
    //
    // In this case, (17,1,[5 $]) indicates there is some next sequence that
    // would resolve this without conflict to alternative 1. Any other viable
    // next sequence, however, is associated with a conflict.  We stop
    // looking for input because no amount of further lookahead will alter
    // the fact that we should predict alternative 1.  We just can't say for
    // sure that there is an ambiguity without looking further.

    this.reportAmbiguity(dfa, D, startIndex, input.index, foundExactAmbig, null, reach);

    return predictedAlt;
};

ParserATNSimulator.prototype.computeReachSet = function (closure, t, fullCtx) {
    if (this.debug) {
        console.log("in computeReachSet, starting closure: " + closure);
    }
    if (this.mergeCache === null) {
        this.mergeCache = new DoubleDict();
    }
    var intermediate = new ATNConfigSet(fullCtx);

    // Configurations already in a rule stop state indicate reaching the end
    // of the decision rule (local context) or end of the start rule (full
    // context). Once reached, these configurations are never updated by a
    // closure operation, so they are handled separately for the performance
    // advantage of having a smaller intermediate set when calling closure.
    //
    // For full-context reach operations, separate handling is required to
    // ensure that the alternative matching the longest overall sequence is
    // chosen when multiple such configurations can match the input.

    var skippedStopStates = null;

    // First figure out where we can reach on input t
    for (var i = 0; i < closure.items.length; i++) {
        var c = closure.items[i];
        if (this.debug_add) {
            console.log("testing " + this.getTokenName(t) + " at " + c);
        }
        if (c.state instanceof RuleStopState) {
            if (fullCtx || t === Token.EOF) {
                if (skippedStopStates === null) {
                    skippedStopStates = [];
                }
                skippedStopStates.push(c);
                if (this.debug_add) {
                    console.log("added " + c + " to skippedStopStates");
                }
            }
            continue;
        }
        for (var j = 0; j < c.state.transitions.length; j++) {
            var trans = c.state.transitions[j];
            var target = this.getReachableTarget(trans, t);
            if (target !== null) {
                var cfg = new ATNConfig({ state: target }, c);
                intermediate.add(cfg, this.mergeCache);
                if (this.debug_add) {
                    console.log("added " + cfg + " to intermediate");
                }
            }
        }
    }
    // Now figure out where the reach operation can take us...
    var reach = null;

    // This block optimizes the reach operation for intermediate sets which
    // trivially indicate a termination state for the overall
    // adaptivePredict operation.
    //
    // The conditions assume that intermediate
    // contains all configurations relevant to the reach set, but this
    // condition is not true when one or more configurations have been
    // withheld in skippedStopStates, or when the current symbol is EOF.
    //
    if (skippedStopStates === null && t !== Token.EOF) {
        if (intermediate.items.length === 1) {
            // Don't pursue the closure if there is just one state.
            // It can only have one alternative; just add to result
            // Also don't pursue the closure if there is unique alternative
            // among the configurations.
            reach = intermediate;
        } else if (this.getUniqueAlt(intermediate) !== ATN.INVALID_ALT_NUMBER) {
            // Also don't pursue the closure if there is unique alternative
            // among the configurations.
            reach = intermediate;
        }
    }
    // If the reach set could not be trivially determined, perform a closure
    // operation on the intermediate set to compute its initial value.
    //
    if (reach === null) {
        reach = new ATNConfigSet(fullCtx);
        var closureBusy = new Set();
        var treatEofAsEpsilon = t === Token.EOF;
        for (var k = 0; k < intermediate.items.length; k++) {
            this.closure(intermediate.items[k], reach, closureBusy, false, fullCtx, treatEofAsEpsilon);
        }
    }
    if (t === Token.EOF) {
        // After consuming EOF no additional input is possible, so we are
        // only interested in configurations which reached the end of the
        // decision rule (local context) or end of the start rule (full
        // context). Update reach to contain only these configurations. This
        // handles both explicit EOF transitions in the grammar and implicit
        // EOF transitions following the end of the decision or start rule.
        //
        // When reach==intermediate, no closure operation was performed. In
        // this case, removeAllConfigsNotInRuleStopState needs to check for
        // reachable rule stop states as well as configurations already in
        // a rule stop state.
        //
        // This is handled before the configurations in skippedStopStates,
        // because any configurations potentially added from that list are
        // already guaranteed to meet this condition whether or not it's
        // required.
        //
        reach = this.removeAllConfigsNotInRuleStopState(reach, reach === intermediate);
    }
    // If skippedStopStates!==null, then it contains at least one
    // configuration. For full-context reach operations, these
    // configurations reached the end of the start rule, in which case we
    // only add them back to reach if no configuration during the current
    // closure operation reached such a state. This ensures adaptivePredict
    // chooses an alternative matching the longest overall sequence when
    // multiple alternatives are viable.
    //
    if (skippedStopStates !== null && (!fullCtx || !PredictionMode.hasConfigInRuleStopState(reach))) {
        for (var l = 0; l < skippedStopStates.length; l++) {
            reach.add(skippedStopStates[l], this.mergeCache);
        }
    }
    if (reach.items.length === 0) {
        return null;
    } else {
        return reach;
    }
};
//
// Return a configuration set containing only the configurations from
// {@code configs} which are in a {@link RuleStopState}. If all
// configurations in {@code configs} are already in a rule stop state, this
// method simply returns {@code configs}.
//
// <p>When {@code lookToEndOfRule} is true, this method uses
// {@link ATN//nextTokens} for each configuration in {@code configs} which is
// not already in a rule stop state to see if a rule stop state is reachable
// from the configuration via epsilon-only transitions.</p>
//
// @param configs the configuration set to update
// @param lookToEndOfRule when true, this method checks for rule stop states
// reachable by epsilon-only transitions from each configuration in
// {@code configs}.
//
// @return {@code configs} if all configurations in {@code configs} are in a
// rule stop state, otherwise return a new configuration set containing only
// the configurations from {@code configs} which are in a rule stop state
//
ParserATNSimulator.prototype.removeAllConfigsNotInRuleStopState = function (configs, lookToEndOfRule) {
    if (PredictionMode.allConfigsInRuleStopStates(configs)) {
        return configs;
    }
    var result = new ATNConfigSet(configs.fullCtx);
    for (var i = 0; i < configs.items.length; i++) {
        var config = configs.items[i];
        if (config.state instanceof RuleStopState) {
            result.add(config, this.mergeCache);
            continue;
        }
        if (lookToEndOfRule && config.state.epsilonOnlyTransitions) {
            var nextTokens = this.atn.nextTokens(config.state);
            if (nextTokens.contains(Token.EPSILON)) {
                var endOfRuleState = this.atn.ruleToStopState[config.state.ruleIndex];
                result.add(new ATNConfig({ state: endOfRuleState }, config), this.mergeCache);
            }
        }
    }
    return result;
};

ParserATNSimulator.prototype.computeStartState = function (p, ctx, fullCtx) {
    // always at least the implicit call to start rule
    var initialContext = predictionContextFromRuleContext(this.atn, ctx);
    var configs = new ATNConfigSet(fullCtx);
    for (var i = 0; i < p.transitions.length; i++) {
        var target = p.transitions[i].target;
        var c = new ATNConfig({ state: target, alt: i + 1, context: initialContext }, null);
        var closureBusy = new Set();
        this.closure(c, configs, closureBusy, true, fullCtx, false);
    }
    return configs;
};

//
// This method transforms the start state computed by
// {@link //computeStartState} to the special start state used by a
// precedence DFA for a particular precedence value. The transformation
// process applies the following changes to the start state's configuration
// set.
//
// <ol>
// <li>Evaluate the precedence predicates for each configuration using
// {@link SemanticContext//evalPrecedence}.</li>
// <li>Remove all configurations which predict an alternative greater than
// 1, for which another configuration that predicts alternative 1 is in the
// same ATN state with the same prediction context. This transformation is
// valid for the following reasons:
// <ul>
// <li>The closure block cannot contain any epsilon transitions which bypass
// the body of the closure, so all states reachable via alternative 1 are
// part of the precedence alternatives of the transformed left-recursive
// rule.</li>
// <li>The "primary" portion of a left recursive rule cannot contain an
// epsilon transition, so the only way an alternative other than 1 can exist
// in a state that is also reachable via alternative 1 is by nesting calls
// to the left-recursive rule, with the outer calls not being at the
// preferred precedence level.</li>
// </ul>
// </li>
// </ol>
//
// <p>
// The prediction context must be considered by this filter to address
// situations like the following.
// </p>
// <code>
// <pre>
// grammar TA;
// prog: statement* EOF;
// statement: letterA | statement letterA 'b' ;
// letterA: 'a';
// </pre>
// </code>
// <p>
// If the above grammar, the ATN state immediately before the token
// reference {@code 'a'} in {@code letterA} is reachable from the left edge
// of both the primary and closure blocks of the left-recursive rule
// {@code statement}. The prediction context associated with each of these
// configurations distinguishes between them, and prevents the alternative
// which stepped out to {@code prog} (and then back in to {@code statement}
// from being eliminated by the filter.
// </p>
//
// @param configs The configuration set computed by
// {@link //computeStartState} as the start state for the DFA.
// @return The transformed configuration set representing the start state
// for a precedence DFA at a particular precedence level (determined by
// calling {@link Parser//getPrecedence}).
//
ParserATNSimulator.prototype.applyPrecedenceFilter = function (configs) {
    var config;
    var statesFromAlt1 = [];
    var configSet = new ATNConfigSet(configs.fullCtx);
    for (var i = 0; i < configs.items.length; i++) {
        config = configs.items[i];
        // handle alt 1 first
        if (config.alt !== 1) {
            continue;
        }
        var updatedContext = config.semanticContext.evalPrecedence(this.parser, this._outerContext);
        if (updatedContext === null) {
            // the configuration was eliminated
            continue;
        }
        statesFromAlt1[config.state.stateNumber] = config.context;
        if (updatedContext !== config.semanticContext) {
            configSet.add(new ATNConfig({ semanticContext: updatedContext }, config), this.mergeCache);
        } else {
            configSet.add(config, this.mergeCache);
        }
    }
    for (i = 0; i < configs.items.length; i++) {
        config = configs.items[i];
        if (config.alt === 1) {
            // already handled
            continue;
        }
        // In the future, this elimination step could be updated to also
        // filter the prediction context for alternatives predicting alt>1
        // (basically a graph subtraction algorithm).
        if (!config.precedenceFilterSuppressed) {
            var context = statesFromAlt1[config.state.stateNumber] || null;
            if (context !== null && context.equals(config.context)) {
                // eliminated
                continue;
            }
        }
        configSet.add(config, this.mergeCache);
    }
    return configSet;
};

ParserATNSimulator.prototype.getReachableTarget = function (trans, ttype) {
    if (trans.matches(ttype, 0, this.atn.maxTokenType)) {
        return trans.target;
    } else {
        return null;
    }
};

ParserATNSimulator.prototype.getPredsForAmbigAlts = function (ambigAlts, configs, nalts) {
    // REACH=[1|1|[]|0:0, 1|2|[]|0:1]
    // altToPred starts as an array of all null contexts. The entry at index i
    // corresponds to alternative i. altToPred[i] may have one of three values:
    //   1. null: no ATNConfig c is found such that c.alt==i
    //   2. SemanticContext.NONE: At least one ATNConfig c exists such that
    //      c.alt==i and c.semanticContext==SemanticContext.NONE. In other words,
    //      alt i has at least one unpredicated config.
    //   3. Non-NONE Semantic Context: There exists at least one, and for all
    //      ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE.
    //
    // From this, it is clear that NONE||anything==NONE.
    //
    var altToPred = [];
    for (var i = 0; i < configs.items.length; i++) {
        var c = configs.items[i];
        if (ambigAlts.contains(c.alt)) {
            altToPred[c.alt] = SemanticContext.orContext(altToPred[c.alt] || null, c.semanticContext);
        }
    }
    var nPredAlts = 0;
    for (i = 1; i < nalts + 1; i++) {
        var pred = altToPred[i] || null;
        if (pred === null) {
            altToPred[i] = SemanticContext.NONE;
        } else if (pred !== SemanticContext.NONE) {
            nPredAlts += 1;
        }
    }
    // nonambig alts are null in altToPred
    if (nPredAlts === 0) {
        altToPred = null;
    }
    if (this.debug) {
        console.log("getPredsForAmbigAlts result " + Utils.arrayToString(altToPred));
    }
    return altToPred;
};

ParserATNSimulator.prototype.getPredicatePredictions = function (ambigAlts, altToPred) {
    var pairs = [];
    var containsPredicate = false;
    for (var i = 1; i < altToPred.length; i++) {
        var pred = altToPred[i];
        // unpredicated is indicated by SemanticContext.NONE
        if (ambigAlts !== null && ambigAlts.contains(i)) {
            pairs.push(new PredPrediction(pred, i));
        }
        if (pred !== SemanticContext.NONE) {
            containsPredicate = true;
        }
    }
    if (!containsPredicate) {
        return null;
    }
    return pairs;
};

//
// This method is used to improve the localization of error messages by
// choosing an alternative rather than throwing a
// {@link NoViableAltException} in particular prediction scenarios where the
// {@link //ERROR} state was reached during ATN simulation.
//
// <p>
// The default implementation of this method uses the following
// algorithm to identify an ATN configuration which successfully parsed the
// decision entry rule. Choosing such an alternative ensures that the
// {@link ParserRuleContext} returned by the calling rule will be complete
// and valid, and the syntax error will be reported later at a more
// localized location.</p>
//
// <ul>
// <li>If a syntactically valid path or paths reach the end of the decision rule and
// they are semantically valid if predicated, return the min associated alt.</li>
// <li>Else, if a semantically invalid but syntactically valid path exist
// or paths exist, return the minimum associated alt.
// </li>
// <li>Otherwise, return {@link ATN//INVALID_ALT_NUMBER}.</li>
// </ul>
//
// <p>
// In some scenarios, the algorithm described above could predict an
// alternative which will result in a {@link FailedPredicateException} in
// the parser. Specifically, this could occur if the <em>only</em> configuration
// capable of successfully parsing to the end of the decision rule is
// blocked by a semantic predicate. By choosing this alternative within
// {@link //adaptivePredict} instead of throwing a
// {@link NoViableAltException}, the resulting
// {@link FailedPredicateException} in the parser will identify the specific
// predicate which is preventing the parser from successfully parsing the
// decision rule, which helps developers identify and correct logic errors
// in semantic predicates.
// </p>
//
// @param configs The ATN configurations which were valid immediately before
// the {@link //ERROR} state was reached
// @param outerContext The is the \gamma_0 initial parser context from the paper
// or the parser stack at the instant before prediction commences.
//
// @return The value to return from {@link //adaptivePredict}, or
// {@link ATN//INVALID_ALT_NUMBER} if a suitable alternative was not
// identified and {@link //adaptivePredict} should report an error instead.
//
ParserATNSimulator.prototype.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule = function (configs, outerContext) {
    var cfgs = this.splitAccordingToSemanticValidity(configs, outerContext);
    var semValidConfigs = cfgs[0];
    var semInvalidConfigs = cfgs[1];
    var alt = this.getAltThatFinishedDecisionEntryRule(semValidConfigs);
    if (alt !== ATN.INVALID_ALT_NUMBER) {
        // semantically/syntactically viable path exists
        return alt;
    }
    // Is there a syntactically valid path with a failed pred?
    if (semInvalidConfigs.items.length > 0) {
        alt = this.getAltThatFinishedDecisionEntryRule(semInvalidConfigs);
        if (alt !== ATN.INVALID_ALT_NUMBER) {
            // syntactically viable path exists
            return alt;
        }
    }
    return ATN.INVALID_ALT_NUMBER;
};

ParserATNSimulator.prototype.getAltThatFinishedDecisionEntryRule = function (configs) {
    var alts = [];
    for (var i = 0; i < configs.items.length; i++) {
        var c = configs.items[i];
        if (c.reachesIntoOuterContext > 0 || c.state instanceof RuleStopState && c.context.hasEmptyPath()) {
            if (alts.indexOf(c.alt) < 0) {
                alts.push(c.alt);
            }
        }
    }
    if (alts.length === 0) {
        return ATN.INVALID_ALT_NUMBER;
    } else {
        return Math.min.apply(null, alts);
    }
};
// Walk the list of configurations and split them according to
//  those that have preds evaluating to true/false.  If no pred, assume
//  true pred and include in succeeded set.  Returns Pair of sets.
//
//  Create a new set so as not to alter the incoming parameter.
//
//  Assumption: the input stream has been restored to the starting point
//  prediction, which is where predicates need to evaluate.
//
ParserATNSimulator.prototype.splitAccordingToSemanticValidity = function (configs, outerContext) {
    var succeeded = new ATNConfigSet(configs.fullCtx);
    var failed = new ATNConfigSet(configs.fullCtx);
    for (var i = 0; i < configs.items.length; i++) {
        var c = configs.items[i];
        if (c.semanticContext !== SemanticContext.NONE) {
            var predicateEvaluationResult = c.semanticContext.evaluate(this.parser, outerContext);
            if (predicateEvaluationResult) {
                succeeded.add(c);
            } else {
                failed.add(c);
            }
        } else {
            succeeded.add(c);
        }
    }
    return [succeeded, failed];
};

// Look through a list of predicate/alt pairs, returning alts for the
//  pairs that win. A {@code NONE} predicate indicates an alt containing an
//  unpredicated config which behaves as "always true." If !complete
//  then we stop at the first predicate that evaluates to true. This
//  includes pairs with null predicates.
//
ParserATNSimulator.prototype.evalSemanticContext = function (predPredictions, outerContext, complete) {
    var predictions = new BitSet();
    for (var i = 0; i < predPredictions.length; i++) {
        var pair = predPredictions[i];
        if (pair.pred === SemanticContext.NONE) {
            predictions.add(pair.alt);
            if (!complete) {
                break;
            }
            continue;
        }
        var predicateEvaluationResult = pair.pred.evaluate(this.parser, outerContext);
        if (this.debug || this.dfa_debug) {
            console.log("eval pred " + pair + "=" + predicateEvaluationResult);
        }
        if (predicateEvaluationResult) {
            if (this.debug || this.dfa_debug) {
                console.log("PREDICT " + pair.alt);
            }
            predictions.add(pair.alt);
            if (!complete) {
                break;
            }
        }
    }
    return predictions;
};

// TODO: If we are doing predicates, there is no point in pursuing
//     closure operations if we reach a DFA state that uniquely predicts
//     alternative. We will not be caching that DFA state and it is a
//     waste to pursue the closure. Might have to advance when we do
//     ambig detection thought :(
//

ParserATNSimulator.prototype.closure = function (config, configs, closureBusy, collectPredicates, fullCtx, treatEofAsEpsilon) {
    var initialDepth = 0;
    this.closureCheckingStopState(config, configs, closureBusy, collectPredicates, fullCtx, initialDepth, treatEofAsEpsilon);
};

ParserATNSimulator.prototype.closureCheckingStopState = function (config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
    if (this.debug || this.debug_closure) {
        console.log("closure(" + config.toString(this.parser, true) + ")");
        // console.log("configs(" + configs.toString() + ")");
        if (config.reachesIntoOuterContext > 50) {
            throw "problem";
        }
    }
    if (config.state instanceof RuleStopState) {
        // We hit rule end. If we have context info, use it
        // run thru all possible stack tops in ctx
        if (!config.context.isEmpty()) {
            for (var i = 0; i < config.context.length; i++) {
                if (config.context.getReturnState(i) === PredictionContext.EMPTY_RETURN_STATE) {
                    if (fullCtx) {
                        configs.add(new ATNConfig({ state: config.state, context: PredictionContext.EMPTY }, config), this.mergeCache);
                        continue;
                    } else {
                        // we have no context info, just chase follow links (if greedy)
                        if (this.debug) {
                            console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex));
                        }
                        this.closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon);
                    }
                    continue;
                }
                var returnState = this.atn.states[config.context.getReturnState(i)];
                var newContext = config.context.getParent(i); // "pop" return state
                var parms = { state: returnState, alt: config.alt, context: newContext, semanticContext: config.semanticContext };
                var c = new ATNConfig(parms, null);
                // While we have context to pop back from, we may have
                // gotten that context AFTER having falling off a rule.
                // Make sure we track that we are now out of context.
                c.reachesIntoOuterContext = config.reachesIntoOuterContext;
                this.closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth - 1, treatEofAsEpsilon);
            }
            return;
        } else if (fullCtx) {
            // reached end of start rule
            configs.add(config, this.mergeCache);
            return;
        } else {
            // else if we have no context info, just chase follow links (if greedy)
            if (this.debug) {
                console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex));
            }
        }
    }
    this.closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon);
};

// Do the actual work of walking epsilon edges//
ParserATNSimulator.prototype.closure_ = function (config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
    var p = config.state;
    // optimization
    if (!p.epsilonOnlyTransitions) {
        configs.add(config, this.mergeCache);
        // make sure to not return here, because EOF transitions can act as
        // both epsilon transitions and non-epsilon transitions.
    }
    for (var i = 0; i < p.transitions.length; i++) {
        if (i == 0 && this.canDropLoopEntryEdgeInLeftRecursiveRule(config)) continue;

        var t = p.transitions[i];
        var continueCollecting = collectPredicates && !(t instanceof ActionTransition);
        var c = this.getEpsilonTarget(config, t, continueCollecting, depth === 0, fullCtx, treatEofAsEpsilon);
        if (c !== null) {
            if (!t.isEpsilon && closureBusy.add(c) !== c) {
                // avoid infinite recursion for EOF* and EOF+
                continue;
            }
            var newDepth = depth;
            if (config.state instanceof RuleStopState) {
                // target fell off end of rule; mark resulting c as having dipped into outer context
                // We can't get here if incoming config was rule stop and we had context
                // track how far we dip into outer context.  Might
                // come in handy and we avoid evaluating context dependent
                // preds if this is > 0.

                if (closureBusy.add(c) !== c) {
                    // avoid infinite recursion for right-recursive rules
                    continue;
                }

                if (this._dfa !== null && this._dfa.precedenceDfa) {
                    if (t.outermostPrecedenceReturn === this._dfa.atnStartState.ruleIndex) {
                        c.precedenceFilterSuppressed = true;
                    }
                }

                c.reachesIntoOuterContext += 1;
                configs.dipsIntoOuterContext = true; // TODO: can remove? only care when we add to set per middle of this method
                newDepth -= 1;
                if (this.debug) {
                    console.log("dips into outer ctx: " + c);
                }
            } else if (t instanceof RuleTransition) {
                // latch when newDepth goes negative - once we step out of the entry context we can't return
                if (newDepth >= 0) {
                    newDepth += 1;
                }
            }
            this.closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEofAsEpsilon);
        }
    }
};

ParserATNSimulator.prototype.canDropLoopEntryEdgeInLeftRecursiveRule = function (config) {
    // return False
    var p = config.state;
    // First check to see if we are in StarLoopEntryState generated during
    // left-recursion elimination. For efficiency, also check if
    // the context has an empty stack case. If so, it would mean
    // global FOLLOW so we can't perform optimization
    // Are we the special loop entry/exit state? or SLL wildcard
    if (p.stateType != ATNState.STAR_LOOP_ENTRY) return false;
    if (p.stateType != ATNState.STAR_LOOP_ENTRY || !p.isPrecedenceDecision || config.context.isEmpty() || config.context.hasEmptyPath()) return false;

    // Require all return states to return back to the same rule that p is in.
    var numCtxs = config.context.length;
    for (var i = 0; i < numCtxs; i++) {
        // for each stack context
        var returnState = this.atn.states[config.context.getReturnState(i)];
        if (returnState.ruleIndex != p.ruleIndex) return false;
    }

    var decisionStartState = p.transitions[0].target;
    var blockEndStateNum = decisionStartState.endState.stateNumber;
    var blockEndState = this.atn.states[blockEndStateNum];

    // Verify that the top of each stack context leads to loop entry/exit
    // state through epsilon edges and w/o leaving rule.
    for (var i = 0; i < numCtxs; i++) {
        // for each stack context
        var returnStateNumber = config.context.getReturnState(i);
        var returnState = this.atn.states[returnStateNumber];
        // all states must have single outgoing epsilon edge
        if (returnState.transitions.length != 1 || !returnState.transitions[0].isEpsilon) return false;

        // Look for prefix op case like 'not expr', (' type ')' expr
        var returnStateTarget = returnState.transitions[0].target;
        if (returnState.stateType == ATNState.BLOCK_END && returnStateTarget == p) continue;

        // Look for 'expr op expr' or case where expr's return state is block end
        // of (...)* internal block; the block end points to loop back
        // which points to p but we don't need to check that
        if (returnState == blockEndState) continue;

        // Look for ternary expr ? expr : expr. The return state points at block end,
        // which points at loop entry state
        if (returnStateTarget == blockEndState) continue;

        // Look for complex prefix 'between expr and expr' case where 2nd expr's
        // return state points at block end state of (...)* internal block
        if (returnStateTarget.stateType == ATNState.BLOCK_END && returnStateTarget.transitions.length == 1 && returnStateTarget.transitions[0].isEpsilon && returnStateTarget.transitions[0].target == p) continue;

        // anything else ain't conforming
        return false;
    }
    return true;
};

ParserATNSimulator.prototype.getRuleName = function (index) {
    if (this.parser !== null && index >= 0) {
        return this.parser.ruleNames[index];
    } else {
        return "<rule " + index + ">";
    }
};

ParserATNSimulator.prototype.getEpsilonTarget = function (config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon) {
    switch (t.serializationType) {
        case Transition.RULE:
            return this.ruleTransition(config, t);
        case Transition.PRECEDENCE:
            return this.precedenceTransition(config, t, collectPredicates, inContext, fullCtx);
        case Transition.PREDICATE:
            return this.predTransition(config, t, collectPredicates, inContext, fullCtx);
        case Transition.ACTION:
            return this.actionTransition(config, t);
        case Transition.EPSILON:
            return new ATNConfig({ state: t.target }, config);
        case Transition.ATOM:
        case Transition.RANGE:
        case Transition.SET:
            // EOF transitions act like epsilon transitions after the first EOF
            // transition is traversed
            if (treatEofAsEpsilon) {
                if (t.matches(Token.EOF, 0, 1)) {
                    return new ATNConfig({ state: t.target }, config);
                }
            }
            return null;
        default:
            return null;
    }
};

ParserATNSimulator.prototype.actionTransition = function (config, t) {
    if (this.debug) {
        var index = t.actionIndex == -1 ? 65535 : t.actionIndex;
        console.log("ACTION edge " + t.ruleIndex + ":" + index);
    }
    return new ATNConfig({ state: t.target }, config);
};

ParserATNSimulator.prototype.precedenceTransition = function (config, pt, collectPredicates, inContext, fullCtx) {
    if (this.debug) {
        console.log("PRED (collectPredicates=" + collectPredicates + ") " + pt.precedence + ">=_p, ctx dependent=true");
        if (this.parser !== null) {
            console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack()));
        }
    }
    var c = null;
    if (collectPredicates && inContext) {
        if (fullCtx) {
            // In full context mode, we can evaluate predicates on-the-fly
            // during closure, which dramatically reduces the size of
            // the config sets. It also obviates the need to test predicates
            // later during conflict resolution.
            var currentPosition = this._input.index;
            this._input.seek(this._startIndex);
            var predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);
            this._input.seek(currentPosition);
            if (predSucceeds) {
                c = new ATNConfig({ state: pt.target }, config); // no pred context
            }
        } else {
            var newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());
            c = new ATNConfig({ state: pt.target, semanticContext: newSemCtx }, config);
        }
    } else {
        c = new ATNConfig({ state: pt.target }, config);
    }
    if (this.debug) {
        console.log("config from pred transition=" + c);
    }
    return c;
};

ParserATNSimulator.prototype.predTransition = function (config, pt, collectPredicates, inContext, fullCtx) {
    if (this.debug) {
        console.log("PRED (collectPredicates=" + collectPredicates + ") " + pt.ruleIndex + ":" + pt.predIndex + ", ctx dependent=" + pt.isCtxDependent);
        if (this.parser !== null) {
            console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack()));
        }
    }
    var c = null;
    if (collectPredicates && (pt.isCtxDependent && inContext || !pt.isCtxDependent)) {
        if (fullCtx) {
            // In full context mode, we can evaluate predicates on-the-fly
            // during closure, which dramatically reduces the size of
            // the config sets. It also obviates the need to test predicates
            // later during conflict resolution.
            var currentPosition = this._input.index;
            this._input.seek(this._startIndex);
            var predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);
            this._input.seek(currentPosition);
            if (predSucceeds) {
                c = new ATNConfig({ state: pt.target }, config); // no pred context
            }
        } else {
            var newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());
            c = new ATNConfig({ state: pt.target, semanticContext: newSemCtx }, config);
        }
    } else {
        c = new ATNConfig({ state: pt.target }, config);
    }
    if (this.debug) {
        console.log("config from pred transition=" + c);
    }
    return c;
};

ParserATNSimulator.prototype.ruleTransition = function (config, t) {
    if (this.debug) {
        console.log("CALL rule " + this.getRuleName(t.target.ruleIndex) + ", ctx=" + config.context);
    }
    var returnState = t.followState;
    var newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber);
    return new ATNConfig({ state: t.target, context: newContext }, config);
};

ParserATNSimulator.prototype.getConflictingAlts = function (configs) {
    var altsets = PredictionMode.getConflictingAltSubsets(configs);
    return PredictionMode.getAlts(altsets);
};

// Sam pointed out a problem with the previous definition, v3, of
// ambiguous states. If we have another state associated with conflicting
// alternatives, we should keep going. For example, the following grammar
//
// s : (ID | ID ID?) ';' ;
//
// When the ATN simulation reaches the state before ';', it has a DFA
// state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally
// 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node
// because alternative to has another way to continue, via [6|2|[]].
// The key is that we have a single state that has config's only associated
// with a single alternative, 2, and crucially the state transitions
// among the configurations are all non-epsilon transitions. That means
// we don't consider any conflicts that include alternative 2. So, we
// ignore the conflict between alts 1 and 2. We ignore a set of
// conflicting alts when there is an intersection with an alternative
// associated with a single alt state in the state&rarr;config-list map.
//
// It's also the case that we might have two conflicting configurations but
// also a 3rd nonconflicting configuration for a different alternative:
// [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:
//
// a : A | A | A B ;
//
// After matching input A, we reach the stop state for rule A, state 1.
// State 8 is the state right before B. Clearly alternatives 1 and 2
// conflict and no amount of further lookahead will separate the two.
// However, alternative 3 will be able to continue and so we do not
// stop working on this state. In the previous example, we're concerned
// with states associated with the conflicting alternatives. Here alt
// 3 is not associated with the conflicting configs, but since we can continue
// looking for input reasonably, I don't declare the state done. We
// ignore a set of conflicting alts when we have an alternative
// that we still need to pursue.
//

ParserATNSimulator.prototype.getConflictingAltsOrUniqueAlt = function (configs) {
    var conflictingAlts = null;
    if (configs.uniqueAlt !== ATN.INVALID_ALT_NUMBER) {
        conflictingAlts = new BitSet();
        conflictingAlts.add(configs.uniqueAlt);
    } else {
        conflictingAlts = configs.conflictingAlts;
    }
    return conflictingAlts;
};

ParserATNSimulator.prototype.getTokenName = function (t) {
    if (t === Token.EOF) {
        return "EOF";
    }
    if (this.parser !== null && this.parser.literalNames !== null) {
        if (t >= this.parser.literalNames.length && t >= this.parser.symbolicNames.length) {
            console.log("" + t + " ttype out of range: " + this.parser.literalNames);
            console.log("" + this.parser.getInputStream().getTokens());
        } else {
            var name = this.parser.literalNames[t] || this.parser.symbolicNames[t];
            return name + "<" + t + ">";
        }
    }
    return "" + t;
};

ParserATNSimulator.prototype.getLookaheadName = function (input) {
    return this.getTokenName(input.LA(1));
};

// Used for debugging in adaptivePredict around execATN but I cut
//  it out for clarity now that alg. works well. We can leave this
//  "dead" code for a bit.
//
ParserATNSimulator.prototype.dumpDeadEndConfigs = function (nvae) {
    console.log("dead end configs: ");
    var decs = nvae.getDeadEndConfigs();
    for (var i = 0; i < decs.length; i++) {
        var c = decs[i];
        var trans = "no edges";
        if (c.state.transitions.length > 0) {
            var t = c.state.transitions[0];
            if (t instanceof AtomTransition) {
                trans = "Atom " + this.getTokenName(t.label);
            } else if (t instanceof SetTransition) {
                var neg = t instanceof NotSetTransition;
                trans = (neg ? "~" : "") + "Set " + t.set;
            }
        }
        console.error(c.toString(this.parser, true) + ":" + trans);
    }
};

ParserATNSimulator.prototype.noViableAlt = function (input, outerContext, configs, startIndex) {
    return new NoViableAltException(this.parser, input, input.get(startIndex), input.LT(1), configs, outerContext);
};

ParserATNSimulator.prototype.getUniqueAlt = function (configs) {
    var alt = ATN.INVALID_ALT_NUMBER;
    for (var i = 0; i < configs.items.length; i++) {
        var c = configs.items[i];
        if (alt === ATN.INVALID_ALT_NUMBER) {
            alt = c.alt; // found first alt
        } else if (c.alt !== alt) {
            return ATN.INVALID_ALT_NUMBER;
        }
    }
    return alt;
};

//
// Add an edge to the DFA, if possible. This method calls
// {@link //addDFAState} to ensure the {@code to} state is present in the
// DFA. If {@code from} is {@code null}, or if {@code t} is outside the
// range of edges that can be represented in the DFA tables, this method
// returns without adding the edge to the DFA.
//
// <p>If {@code to} is {@code null}, this method returns {@code null}.
// Otherwise, this method returns the {@link DFAState} returned by calling
// {@link //addDFAState} for the {@code to} state.</p>
//
// @param dfa The DFA
// @param from The source state for the edge
// @param t The input symbol
// @param to The target state for the edge
//
// @return If {@code to} is {@code null}, this method returns {@code null};
// otherwise this method returns the result of calling {@link //addDFAState}
// on {@code to}
//
ParserATNSimulator.prototype.addDFAEdge = function (dfa, from_, t, to) {
    if (this.debug) {
        console.log("EDGE " + from_ + " -> " + to + " upon " + this.getTokenName(t));
    }
    if (to === null) {
        return null;
    }
    to = this.addDFAState(dfa, to); // used existing if possible not incoming
    if (from_ === null || t < -1 || t > this.atn.maxTokenType) {
        return to;
    }
    if (from_.edges === null) {
        from_.edges = [];
    }
    from_.edges[t + 1] = to; // connect

    if (this.debug) {
        var literalNames = this.parser === null ? null : this.parser.literalNames;
        var symbolicNames = this.parser === null ? null : this.parser.symbolicNames;
        console.log("DFA=\n" + dfa.toString(literalNames, symbolicNames));
    }
    return to;
};
//
// Add state {@code D} to the DFA if it is not already present, and return
// the actual instance stored in the DFA. If a state equivalent to {@code D}
// is already in the DFA, the existing state is returned. Otherwise this
// method returns {@code D} after adding it to the DFA.
//
// <p>If {@code D} is {@link //ERROR}, this method returns {@link //ERROR} and
// does not change the DFA.</p>
//
// @param dfa The dfa
// @param D The DFA state to add
// @return The state stored in the DFA. This will be either the existing
// state if {@code D} is already in the DFA, or {@code D} itself if the
// state was not already present.
//
ParserATNSimulator.prototype.addDFAState = function (dfa, D) {
    if (D == ATNSimulator.ERROR) {
        return D;
    }
    var existing = dfa.states.get(D);
    if (existing !== null) {
        return existing;
    }
    D.stateNumber = dfa.states.length;
    if (!D.configs.readOnly) {
        D.configs.optimizeConfigs(this);
        D.configs.setReadonly(true);
    }
    dfa.states.add(D);
    if (this.debug) {
        console.log("adding new DFA state: " + D);
    }
    return D;
};

ParserATNSimulator.prototype.reportAttemptingFullContext = function (dfa, conflictingAlts, configs, startIndex, stopIndex) {
    if (this.debug || this.retry_debug) {
        var interval = new Interval(startIndex, stopIndex + 1);
        console.log("reportAttemptingFullContext decision=" + dfa.decision + ":" + configs + ", input=" + this.parser.getTokenStream().getText(interval));
    }
    if (this.parser !== null) {
        this.parser.getErrorListenerDispatch().reportAttemptingFullContext(this.parser, dfa, startIndex, stopIndex, conflictingAlts, configs);
    }
};

ParserATNSimulator.prototype.reportContextSensitivity = function (dfa, prediction, configs, startIndex, stopIndex) {
    if (this.debug || this.retry_debug) {
        var interval = new Interval(startIndex, stopIndex + 1);
        console.log("reportContextSensitivity decision=" + dfa.decision + ":" + configs + ", input=" + this.parser.getTokenStream().getText(interval));
    }
    if (this.parser !== null) {
        this.parser.getErrorListenerDispatch().reportContextSensitivity(this.parser, dfa, startIndex, stopIndex, prediction, configs);
    }
};

// If context sensitive parsing, we know it's ambiguity not conflict//
ParserATNSimulator.prototype.reportAmbiguity = function (dfa, D, startIndex, stopIndex, exact, ambigAlts, configs) {
    if (this.debug || this.retry_debug) {
        var interval = new Interval(startIndex, stopIndex + 1);
        console.log("reportAmbiguity " + ambigAlts + ":" + configs + ", input=" + this.parser.getTokenStream().getText(interval));
    }
    if (this.parser !== null) {
        this.parser.getErrorListenerDispatch().reportAmbiguity(this.parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs);
    }
};

exports.ParserATNSimulator = ParserATNSimulator;

/***/ }),

/***/ "./node_modules/antlr4/atn/PredictionMode.js":
/*!***************************************************!*\
  !*** ./node_modules/antlr4/atn/PredictionMode.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//
//
// This enumeration defines the prediction modes available in ANTLR 4 along with
// utility methods for analyzing configuration sets for conflicts and/or
// ambiguities.

var Set = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Set;
var Map = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Map;
var BitSet = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").BitSet;
var AltDict = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").AltDict;
var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
var RuleStopState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
var ATNConfig = __webpack_require__(/*! ./ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").ATNConfig;
var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
var Hash = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").Hash;
var hashStuff = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").hashStuff;
var equalArrays = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").equalArrays;

function PredictionMode() {
    return this;
}

//
// The SLL(*) prediction mode. This prediction mode ignores the current
// parser context when making predictions. This is the fastest prediction
// mode, and provides correct results for many grammars. This prediction
// mode is more powerful than the prediction mode provided by ANTLR 3, but
// may result in syntax errors for grammar and input combinations which are
// not SLL.
//
// <p>
// When using this prediction mode, the parser will either return a correct
// parse tree (i.e. the same parse tree that would be returned with the
// {@link //LL} prediction mode), or it will report a syntax error. If a
// syntax error is encountered when using the {@link //SLL} prediction mode,
// it may be due to either an actual syntax error in the input or indicate
// that the particular combination of grammar and input requires the more
// powerful {@link //LL} prediction abilities to complete successfully.</p>
//
// <p>
// This prediction mode does not provide any guarantees for prediction
// behavior for syntactically-incorrect inputs.</p>
//
PredictionMode.SLL = 0;
//
// The LL(*) prediction mode. This prediction mode allows the current parser
// context to be used for resolving SLL conflicts that occur during
// prediction. This is the fastest prediction mode that guarantees correct
// parse results for all combinations of grammars with syntactically correct
// inputs.
//
// <p>
// When using this prediction mode, the parser will make correct decisions
// for all syntactically-correct grammar and input combinations. However, in
// cases where the grammar is truly ambiguous this prediction mode might not
// report a precise answer for <em>exactly which</em> alternatives are
// ambiguous.</p>
//
// <p>
// This prediction mode does not provide any guarantees for prediction
// behavior for syntactically-incorrect inputs.</p>
//
PredictionMode.LL = 1;
//
// The LL(*) prediction mode with exact ambiguity detection. In addition to
// the correctness guarantees provided by the {@link //LL} prediction mode,
// this prediction mode instructs the prediction algorithm to determine the
// complete and exact set of ambiguous alternatives for every ambiguous
// decision encountered while parsing.
//
// <p>
// This prediction mode may be used for diagnosing ambiguities during
// grammar development. Due to the performance overhead of calculating sets
// of ambiguous alternatives, this prediction mode should be avoided when
// the exact results are not necessary.</p>
//
// <p>
// This prediction mode does not provide any guarantees for prediction
// behavior for syntactically-incorrect inputs.</p>
//
PredictionMode.LL_EXACT_AMBIG_DETECTION = 2;

//
// Computes the SLL prediction termination condition.
//
// <p>
// This method computes the SLL prediction termination condition for both of
// the following cases.</p>
//
// <ul>
// <li>The usual SLL+LL fallback upon SLL conflict</li>
// <li>Pure SLL without LL fallback</li>
// </ul>
//
// <p><strong>COMBINED SLL+LL PARSING</strong></p>
//
// <p>When LL-fallback is enabled upon SLL conflict, correct predictions are
// ensured regardless of how the termination condition is computed by this
// method. Due to the substantially higher cost of LL prediction, the
// prediction should only fall back to LL when the additional lookahead
// cannot lead to a unique SLL prediction.</p>
//
// <p>Assuming combined SLL+LL parsing, an SLL configuration set with only
// conflicting subsets should fall back to full LL, even if the
// configuration sets don't resolve to the same alternative (e.g.
// {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting
// configuration, SLL could continue with the hopes that more lookahead will
// resolve via one of those non-conflicting configurations.</p>
//
// <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)
// stops when it sees only conflicting configuration subsets. In contrast,
// full LL keeps going when there is uncertainty.</p>
//
// <p><strong>HEURISTIC</strong></p>
//
// <p>As a heuristic, we stop prediction when we see any conflicting subset
// unless we see a state that only has one alternative associated with it.
// The single-alt-state thing lets prediction continue upon rules like
// (otherwise, it would admit defeat too soon):</p>
//
// <p>{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}</p>
//
// <p>When the ATN simulation reaches the state before {@code ';'}, it has a
// DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally
// {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop
// processing this node because alternative to has another way to continue,
// via {@code [6|2|[]]}.</p>
//
// <p>It also let's us continue for this rule:</p>
//
// <p>{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}</p>
//
// <p>After matching input A, we reach the stop state for rule A, state 1.
// State 8 is the state right before B. Clearly alternatives 1 and 2
// conflict and no amount of further lookahead will separate the two.
// However, alternative 3 will be able to continue and so we do not stop
// working on this state. In the previous example, we're concerned with
// states associated with the conflicting alternatives. Here alt 3 is not
// associated with the conflicting configs, but since we can continue
// looking for input reasonably, don't declare the state done.</p>
//
// <p><strong>PURE SLL PARSING</strong></p>
//
// <p>To handle pure SLL parsing, all we have to do is make sure that we
// combine stack contexts for configurations that differ only by semantic
// predicate. From there, we can do the usual SLL termination heuristic.</p>
//
// <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>
//
// <p>SLL decisions don't evaluate predicates until after they reach DFA stop
// states because they need to create the DFA cache that works in all
// semantic situations. In contrast, full LL evaluates predicates collected
// during start state computation so it can ignore predicates thereafter.
// This means that SLL termination detection can totally ignore semantic
// predicates.</p>
//
// <p>Implementation-wise, {@link ATNConfigSet} combines stack contexts but not
// semantic predicate contexts so we might see two configurations like the
// following.</p>
//
// <p>{@code (s, 1, x, {}), (s, 1, x', {p})}</p>
//
// <p>Before testing these configurations against others, we have to merge
// {@code x} and {@code x'} (without modifying the existing configurations).
// For example, we test {@code (x+x')==x''} when looking for conflicts in
// the following configurations.</p>
//
// <p>{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}</p>
//
// <p>If the configuration set has predicates (as indicated by
// {@link ATNConfigSet//hasSemanticContext}), this algorithm makes a copy of
// the configurations to strip out all of the predicates so that a standard
// {@link ATNConfigSet} will merge everything ignoring predicates.</p>
//
PredictionMode.hasSLLConflictTerminatingPrediction = function (mode, configs) {
    // Configs in rule stop states indicate reaching the end of the decision
    // rule (local context) or end of start rule (full context). If all
    // configs meet this condition, then none of the configurations is able
    // to match additional input so we terminate prediction.
    //
    if (PredictionMode.allConfigsInRuleStopStates(configs)) {
        return true;
    }
    // pure SLL mode parsing
    if (mode === PredictionMode.SLL) {
        // Don't bother with combining configs from different semantic
        // contexts if we can fail over to full LL; costs more time
        // since we'll often fail over anyway.
        if (configs.hasSemanticContext) {
            // dup configs, tossing out semantic predicates
            var dup = new ATNConfigSet();
            for (var i = 0; i < configs.items.length; i++) {
                var c = configs.items[i];
                c = new ATNConfig({ semanticContext: SemanticContext.NONE }, c);
                dup.add(c);
            }
            configs = dup;
        }
        // now we have combined contexts for configs with dissimilar preds
    }
    // pure SLL or combined SLL+LL mode parsing
    var altsets = PredictionMode.getConflictingAltSubsets(configs);
    return PredictionMode.hasConflictingAltSet(altsets) && !PredictionMode.hasStateAssociatedWithOneAlt(configs);
};

// Checks if any configuration in {@code configs} is in a
// {@link RuleStopState}. Configurations meeting this condition have reached
// the end of the decision rule (local context) or end of start rule (full
// context).
//
// @param configs the configuration set to test
// @return {@code true} if any configuration in {@code configs} is in a
// {@link RuleStopState}, otherwise {@code false}
PredictionMode.hasConfigInRuleStopState = function (configs) {
    for (var i = 0; i < configs.items.length; i++) {
        var c = configs.items[i];
        if (c.state instanceof RuleStopState) {
            return true;
        }
    }
    return false;
};

// Checks if all configurations in {@code configs} are in a
// {@link RuleStopState}. Configurations meeting this condition have reached
// the end of the decision rule (local context) or end of start rule (full
// context).
//
// @param configs the configuration set to test
// @return {@code true} if all configurations in {@code configs} are in a
// {@link RuleStopState}, otherwise {@code false}
PredictionMode.allConfigsInRuleStopStates = function (configs) {
    for (var i = 0; i < configs.items.length; i++) {
        var c = configs.items[i];
        if (!(c.state instanceof RuleStopState)) {
            return false;
        }
    }
    return true;
};

//
// Full LL prediction termination.
//
// <p>Can we stop looking ahead during ATN simulation or is there some
// uncertainty as to which alternative we will ultimately pick, after
// consuming more input? Even if there are partial conflicts, we might know
// that everything is going to resolve to the same minimum alternative. That
// means we can stop since no more lookahead will change that fact. On the
// other hand, there might be multiple conflicts that resolve to different
// minimums. That means we need more look ahead to decide which of those
// alternatives we should predict.</p>
//
// <p>The basic idea is to split the set of configurations {@code C}, into
// conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with
// non-conflicting configurations. Two configurations conflict if they have
// identical {@link ATNConfig//state} and {@link ATNConfig//context} values
// but different {@link ATNConfig//alt} value, e.g. {@code (s, i, ctx, _)}
// and {@code (s, j, ctx, _)} for {@code i!=j}.</p>
//
// <p>Reduce these configuration subsets to the set of possible alternatives.
// You can compute the alternative subsets in one pass as follows:</p>
//
// <p>{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in
// {@code C} holding {@code s} and {@code ctx} fixed.</p>
//
// <p>Or in pseudo-code, for each configuration {@code c} in {@code C}:</p>
//
// <pre>
// map[c] U= c.{@link ATNConfig//alt alt} // map hash/equals uses s and x, not
// alt and not pred
// </pre>
//
// <p>The values in {@code map} are the set of {@code A_s,ctx} sets.</p>
//
// <p>If {@code |A_s,ctx|=1} then there is no conflict associated with
// {@code s} and {@code ctx}.</p>
//
// <p>Reduce the subsets to singletons by choosing a minimum of each subset. If
// the union of these alternative subsets is a singleton, then no amount of
// more lookahead will help us. We will always pick that alternative. If,
// however, there is more than one alternative, then we are uncertain which
// alternative to predict and must continue looking for resolution. We may
// or may not discover an ambiguity in the future, even if there are no
// conflicting subsets this round.</p>
//
// <p>The biggest sin is to terminate early because it means we've made a
// decision but were uncertain as to the eventual outcome. We haven't used
// enough lookahead. On the other hand, announcing a conflict too late is no
// big deal; you will still have the conflict. It's just inefficient. It
// might even look until the end of file.</p>
//
// <p>No special consideration for semantic predicates is required because
// predicates are evaluated on-the-fly for full LL prediction, ensuring that
// no configuration contains a semantic context during the termination
// check.</p>
//
// <p><strong>CONFLICTING CONFIGS</strong></p>
//
// <p>Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict
// when {@code i!=j} but {@code x=x'}. Because we merge all
// {@code (s, i, _)} configurations together, that means that there are at
// most {@code n} configurations associated with state {@code s} for
// {@code n} possible alternatives in the decision. The merged stacks
// complicate the comparison of configuration contexts {@code x} and
// {@code x'}. Sam checks to see if one is a subset of the other by calling
// merge and checking to see if the merged result is either {@code x} or
// {@code x'}. If the {@code x} associated with lowest alternative {@code i}
// is the superset, then {@code i} is the only possible prediction since the
// others resolve to {@code min(i)} as well. However, if {@code x} is
// associated with {@code j>i} then at least one stack configuration for
// {@code j} is not in conflict with alternative {@code i}. The algorithm
// should keep going, looking for more lookahead due to the uncertainty.</p>
//
// <p>For simplicity, I'm doing a equality check between {@code x} and
// {@code x'} that lets the algorithm continue to consume lookahead longer
// than necessary. The reason I like the equality is of course the
// simplicity but also because that is the test you need to detect the
// alternatives that are actually in conflict.</p>
//
// <p><strong>CONTINUE/STOP RULE</strong></p>
//
// <p>Continue if union of resolved alternative sets from non-conflicting and
// conflicting alternative subsets has more than one alternative. We are
// uncertain about which alternative to predict.</p>
//
// <p>The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which
// alternatives are still in the running for the amount of input we've
// consumed at this point. The conflicting sets let us to strip away
// configurations that won't lead to more states because we resolve
// conflicts to the configuration with a minimum alternate for the
// conflicting set.</p>
//
// <p><strong>CASES</strong></p>
//
// <ul>
//
// <li>no conflicts and more than 1 alternative in set =&gt; continue</li>
//
// <li> {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)},
// {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set
// {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =
// {@code {1,3}} =&gt; continue
// </li>
//
// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},
// {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set
// {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =
// {@code {1}} =&gt; stop and predict 1</li>
//
// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},
// {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U
// {@code {1}} = {@code {1}} =&gt; stop and predict 1, can announce
// ambiguity {@code {1,2}}</li>
//
// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)},
// {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U
// {@code {2}} = {@code {1,2}} =&gt; continue</li>
//
// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)},
// {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U
// {@code {3}} = {@code {1,3}} =&gt; continue</li>
//
// </ul>
//
// <p><strong>EXACT AMBIGUITY DETECTION</strong></p>
//
// <p>If all states report the same conflicting set of alternatives, then we
// know we have the exact ambiguity set.</p>
//
// <p><code>|A_<em>i</em>|&gt;1</code> and
// <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>
//
// <p>In other words, we continue examining lookahead until all {@code A_i}
// have more than one alternative and all {@code A_i} are the same. If
// {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate
// because the resolved set is {@code {1}}. To determine what the real
// ambiguity is, we have to know whether the ambiguity is between one and
// two or one and three so we keep going. We can only stop prediction when
// we need exact ambiguity detection when the sets look like
// {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>
//
PredictionMode.resolvesToJustOneViableAlt = function (altsets) {
    return PredictionMode.getSingleViableAlt(altsets);
};

//
// Determines if every alternative subset in {@code altsets} contains more
// than one alternative.
//
// @param altsets a collection of alternative subsets
// @return {@code true} if every {@link BitSet} in {@code altsets} has
// {@link BitSet//cardinality cardinality} &gt; 1, otherwise {@code false}
//
PredictionMode.allSubsetsConflict = function (altsets) {
    return !PredictionMode.hasNonConflictingAltSet(altsets);
};
//
// Determines if any single alternative subset in {@code altsets} contains
// exactly one alternative.
//
// @param altsets a collection of alternative subsets
// @return {@code true} if {@code altsets} contains a {@link BitSet} with
// {@link BitSet//cardinality cardinality} 1, otherwise {@code false}
//
PredictionMode.hasNonConflictingAltSet = function (altsets) {
    for (var i = 0; i < altsets.length; i++) {
        var alts = altsets[i];
        if (alts.length === 1) {
            return true;
        }
    }
    return false;
};

//
// Determines if any single alternative subset in {@code altsets} contains
// more than one alternative.
//
// @param altsets a collection of alternative subsets
// @return {@code true} if {@code altsets} contains a {@link BitSet} with
// {@link BitSet//cardinality cardinality} &gt; 1, otherwise {@code false}
//
PredictionMode.hasConflictingAltSet = function (altsets) {
    for (var i = 0; i < altsets.length; i++) {
        var alts = altsets[i];
        if (alts.length > 1) {
            return true;
        }
    }
    return false;
};

//
// Determines if every alternative subset in {@code altsets} is equivalent.
//
// @param altsets a collection of alternative subsets
// @return {@code true} if every member of {@code altsets} is equal to the
// others, otherwise {@code false}
//
PredictionMode.allSubsetsEqual = function (altsets) {
    var first = null;
    for (var i = 0; i < altsets.length; i++) {
        var alts = altsets[i];
        if (first === null) {
            first = alts;
        } else if (alts !== first) {
            return false;
        }
    }
    return true;
};

//
// Returns the unique alternative predicted by all alternative subsets in
// {@code altsets}. If no such alternative exists, this method returns
// {@link ATN//INVALID_ALT_NUMBER}.
//
// @param altsets a collection of alternative subsets
//
PredictionMode.getUniqueAlt = function (altsets) {
    var all = PredictionMode.getAlts(altsets);
    if (all.length === 1) {
        return all.minValue();
    } else {
        return ATN.INVALID_ALT_NUMBER;
    }
};

// Gets the complete set of represented alternatives for a collection of
// alternative subsets. This method returns the union of each {@link BitSet}
// in {@code altsets}.
//
// @param altsets a collection of alternative subsets
// @return the set of represented alternatives in {@code altsets}
//
PredictionMode.getAlts = function (altsets) {
    var all = new BitSet();
    altsets.map(function (alts) {
        all.or(alts);
    });
    return all;
};

//
// This function gets the conflicting alt subsets from a configuration set.
// For each configuration {@code c} in {@code configs}:
//
// <pre>
// map[c] U= c.{@link ATNConfig//alt alt} // map hash/equals uses s and x, not
// alt and not pred
// </pre>

PredictionMode.getConflictingAltSubsets = function (configs) {
    var configToAlts = new Map();
    configToAlts.hashFunction = function (cfg) {
        hashStuff(cfg.state.stateNumber, cfg.context);
    };
    configToAlts.equalsFunction = function (c1, c2) {
        return c1.state.stateNumber == c2.state.stateNumber && c1.context.equals(c2.context);
    };
    configs.items.map(function (cfg) {
        var alts = configToAlts.get(cfg);
        if (alts === null) {
            alts = new BitSet();
            configToAlts.put(cfg, alts);
        }
        alts.add(cfg.alt);
    });
    return configToAlts.getValues();
};

//
// Get a map from state to alt subset from a configuration set. For each
// configuration {@code c} in {@code configs}:
//
// <pre>
// map[c.{@link ATNConfig//state state}] U= c.{@link ATNConfig//alt alt}
// </pre>
//
PredictionMode.getStateToAltMap = function (configs) {
    var m = new AltDict();
    configs.items.map(function (c) {
        var alts = m.get(c.state);
        if (alts === null) {
            alts = new BitSet();
            m.put(c.state, alts);
        }
        alts.add(c.alt);
    });
    return m;
};

PredictionMode.hasStateAssociatedWithOneAlt = function (configs) {
    var values = PredictionMode.getStateToAltMap(configs).values();
    for (var i = 0; i < values.length; i++) {
        if (values[i].length === 1) {
            return true;
        }
    }
    return false;
};

PredictionMode.getSingleViableAlt = function (altsets) {
    var result = null;
    for (var i = 0; i < altsets.length; i++) {
        var alts = altsets[i];
        var minAlt = alts.minValue();
        if (result === null) {
            result = minAlt;
        } else if (result !== minAlt) {
            // more than 1 viable alt
            return ATN.INVALID_ALT_NUMBER;
        }
    }
    return result;
};

exports.PredictionMode = PredictionMode;

/***/ }),

/***/ "./node_modules/antlr4/atn/SemanticContext.js":
/*!****************************************************!*\
  !*** ./node_modules/antlr4/atn/SemanticContext.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

// A tree structure used to record the semantic context in which
//  an ATN configuration is valid.  It's either a single predicate,
//  a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.
//
//  <p>I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of
//  {@link SemanticContext} within the scope of this outer class.</p>
//

var Set = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Set;
var Hash = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Hash;

function SemanticContext() {
	return this;
}

SemanticContext.prototype.hashCode = function () {
	var hash = new Hash();
	this.updateHashCode(hash);
	return hash.finish();
};

// For context independent predicates, we evaluate them without a local
// context (i.e., null context). That way, we can evaluate them without
// having to create proper rule-specific context during prediction (as
// opposed to the parser, which creates them naturally). In a practical
// sense, this avoids a cast exception from RuleContext to myruleContext.
//
// <p>For context dependent predicates, we must pass in a local context so that
// references such as $arg evaluate properly as _localctx.arg. We only
// capture context dependent predicates in the context in which we begin
// prediction, so we passed in the outer context here in case of context
// dependent predicate evaluation.</p>
//
SemanticContext.prototype.evaluate = function (parser, outerContext) {};

//
// Evaluate the precedence predicates for the context and reduce the result.
//
// @param parser The parser instance.
// @param outerContext The current parser context object.
// @return The simplified semantic context after precedence predicates are
// evaluated, which will be one of the following values.
// <ul>
// <li>{@link //NONE}: if the predicate simplifies to {@code true} after
// precedence predicates are evaluated.</li>
// <li>{@code null}: if the predicate simplifies to {@code false} after
// precedence predicates are evaluated.</li>
// <li>{@code this}: if the semantic context is not changed as a result of
// precedence predicate evaluation.</li>
// <li>A non-{@code null} {@link SemanticContext}: the new simplified
// semantic context after precedence predicates are evaluated.</li>
// </ul>
//
SemanticContext.prototype.evalPrecedence = function (parser, outerContext) {
	return this;
};

SemanticContext.andContext = function (a, b) {
	if (a === null || a === SemanticContext.NONE) {
		return b;
	}
	if (b === null || b === SemanticContext.NONE) {
		return a;
	}
	var result = new AND(a, b);
	if (result.opnds.length === 1) {
		return result.opnds[0];
	} else {
		return result;
	}
};

SemanticContext.orContext = function (a, b) {
	if (a === null) {
		return b;
	}
	if (b === null) {
		return a;
	}
	if (a === SemanticContext.NONE || b === SemanticContext.NONE) {
		return SemanticContext.NONE;
	}
	var result = new OR(a, b);
	if (result.opnds.length === 1) {
		return result.opnds[0];
	} else {
		return result;
	}
};

function Predicate(ruleIndex, predIndex, isCtxDependent) {
	SemanticContext.call(this);
	this.ruleIndex = ruleIndex === undefined ? -1 : ruleIndex;
	this.predIndex = predIndex === undefined ? -1 : predIndex;
	this.isCtxDependent = isCtxDependent === undefined ? false : isCtxDependent; // e.g., $i ref in pred
	return this;
}

Predicate.prototype = Object.create(SemanticContext.prototype);
Predicate.prototype.constructor = Predicate;

//The default {@link SemanticContext}, which is semantically equivalent to
//a predicate of the form {@code {true}?}.
//
SemanticContext.NONE = new Predicate();

Predicate.prototype.evaluate = function (parser, outerContext) {
	var localctx = this.isCtxDependent ? outerContext : null;
	return parser.sempred(localctx, this.ruleIndex, this.predIndex);
};

Predicate.prototype.updateHashCode = function (hash) {
	hash.update(this.ruleIndex, this.predIndex, this.isCtxDependent);
};

Predicate.prototype.equals = function (other) {
	if (this === other) {
		return true;
	} else if (!(other instanceof Predicate)) {
		return false;
	} else {
		return this.ruleIndex === other.ruleIndex && this.predIndex === other.predIndex && this.isCtxDependent === other.isCtxDependent;
	}
};

Predicate.prototype.toString = function () {
	return "{" + this.ruleIndex + ":" + this.predIndex + "}?";
};

function PrecedencePredicate(precedence) {
	SemanticContext.call(this);
	this.precedence = precedence === undefined ? 0 : precedence;
}

PrecedencePredicate.prototype = Object.create(SemanticContext.prototype);
PrecedencePredicate.prototype.constructor = PrecedencePredicate;

PrecedencePredicate.prototype.evaluate = function (parser, outerContext) {
	return parser.precpred(outerContext, this.precedence);
};

PrecedencePredicate.prototype.evalPrecedence = function (parser, outerContext) {
	if (parser.precpred(outerContext, this.precedence)) {
		return SemanticContext.NONE;
	} else {
		return null;
	}
};

PrecedencePredicate.prototype.compareTo = function (other) {
	return this.precedence - other.precedence;
};

PrecedencePredicate.prototype.updateHashCode = function (hash) {
	hash.update(31);
};

PrecedencePredicate.prototype.equals = function (other) {
	if (this === other) {
		return true;
	} else if (!(other instanceof PrecedencePredicate)) {
		return false;
	} else {
		return this.precedence === other.precedence;
	}
};

PrecedencePredicate.prototype.toString = function () {
	return "{" + this.precedence + ">=prec}?";
};

PrecedencePredicate.filterPrecedencePredicates = function (set) {
	var result = [];
	set.values().map(function (context) {
		if (context instanceof PrecedencePredicate) {
			result.push(context);
		}
	});
	return result;
};

// A semantic context which is true whenever none of the contained contexts
// is false.
//
function AND(a, b) {
	SemanticContext.call(this);
	var operands = new Set();
	if (a instanceof AND) {
		a.opnds.map(function (o) {
			operands.add(o);
		});
	} else {
		operands.add(a);
	}
	if (b instanceof AND) {
		b.opnds.map(function (o) {
			operands.add(o);
		});
	} else {
		operands.add(b);
	}
	var precedencePredicates = PrecedencePredicate.filterPrecedencePredicates(operands);
	if (precedencePredicates.length > 0) {
		// interested in the transition with the lowest precedence
		var reduced = null;
		precedencePredicates.map(function (p) {
			if (reduced === null || p.precedence < reduced.precedence) {
				reduced = p;
			}
		});
		operands.add(reduced);
	}
	this.opnds = operands.values();
	return this;
}

AND.prototype = Object.create(SemanticContext.prototype);
AND.prototype.constructor = AND;

AND.prototype.equals = function (other) {
	if (this === other) {
		return true;
	} else if (!(other instanceof AND)) {
		return false;
	} else {
		return this.opnds === other.opnds;
	}
};

AND.prototype.updateHashCode = function (hash) {
	hash.update(this.opnds, "AND");
};
//
// {@inheritDoc}
//
// <p>
// The evaluation of predicates by this context is short-circuiting, but
// unordered.</p>
//
AND.prototype.evaluate = function (parser, outerContext) {
	for (var i = 0; i < this.opnds.length; i++) {
		if (!this.opnds[i].evaluate(parser, outerContext)) {
			return false;
		}
	}
	return true;
};

AND.prototype.evalPrecedence = function (parser, outerContext) {
	var differs = false;
	var operands = [];
	for (var i = 0; i < this.opnds.length; i++) {
		var context = this.opnds[i];
		var evaluated = context.evalPrecedence(parser, outerContext);
		differs |= evaluated !== context;
		if (evaluated === null) {
			// The AND context is false if any element is false
			return null;
		} else if (evaluated !== SemanticContext.NONE) {
			// Reduce the result by skipping true elements
			operands.push(evaluated);
		}
	}
	if (!differs) {
		return this;
	}
	if (operands.length === 0) {
		// all elements were true, so the AND context is true
		return SemanticContext.NONE;
	}
	var result = null;
	operands.map(function (o) {
		result = result === null ? o : SemanticContext.andContext(result, o);
	});
	return result;
};

AND.prototype.toString = function () {
	var s = "";
	this.opnds.map(function (o) {
		s += "&& " + o.toString();
	});
	return s.length > 3 ? s.slice(3) : s;
};

//
// A semantic context which is true whenever at least one of the contained
// contexts is true.
//
function OR(a, b) {
	SemanticContext.call(this);
	var operands = new Set();
	if (a instanceof OR) {
		a.opnds.map(function (o) {
			operands.add(o);
		});
	} else {
		operands.add(a);
	}
	if (b instanceof OR) {
		b.opnds.map(function (o) {
			operands.add(o);
		});
	} else {
		operands.add(b);
	}

	var precedencePredicates = PrecedencePredicate.filterPrecedencePredicates(operands);
	if (precedencePredicates.length > 0) {
		// interested in the transition with the highest precedence
		var s = precedencePredicates.sort(function (a, b) {
			return a.compareTo(b);
		});
		var reduced = s[s.length - 1];
		operands.add(reduced);
	}
	this.opnds = operands.values();
	return this;
}

OR.prototype = Object.create(SemanticContext.prototype);
OR.prototype.constructor = OR;

OR.prototype.constructor = function (other) {
	if (this === other) {
		return true;
	} else if (!(other instanceof OR)) {
		return false;
	} else {
		return this.opnds === other.opnds;
	}
};

OR.prototype.updateHashCode = function (hash) {
	hash.update(this.opnds, "OR");
};

// <p>
// The evaluation of predicates by this context is short-circuiting, but
// unordered.</p>
//
OR.prototype.evaluate = function (parser, outerContext) {
	for (var i = 0; i < this.opnds.length; i++) {
		if (this.opnds[i].evaluate(parser, outerContext)) {
			return true;
		}
	}
	return false;
};

OR.prototype.evalPrecedence = function (parser, outerContext) {
	var differs = false;
	var operands = [];
	for (var i = 0; i < this.opnds.length; i++) {
		var context = this.opnds[i];
		var evaluated = context.evalPrecedence(parser, outerContext);
		differs |= evaluated !== context;
		if (evaluated === SemanticContext.NONE) {
			// The OR context is true if any element is true
			return SemanticContext.NONE;
		} else if (evaluated !== null) {
			// Reduce the result by skipping false elements
			operands.push(evaluated);
		}
	}
	if (!differs) {
		return this;
	}
	if (operands.length === 0) {
		// all elements were false, so the OR context is false
		return null;
	}
	var result = null;
	operands.map(function (o) {
		return result === null ? o : SemanticContext.orContext(result, o);
	});
	return result;
};

OR.prototype.toString = function () {
	var s = "";
	this.opnds.map(function (o) {
		s += "|| " + o.toString();
	});
	return s.length > 3 ? s.slice(3) : s;
};

exports.SemanticContext = SemanticContext;
exports.PrecedencePredicate = PrecedencePredicate;
exports.Predicate = Predicate;

/***/ }),

/***/ "./node_modules/antlr4/atn/Transition.js":
/*!***********************************************!*\
  !*** ./node_modules/antlr4/atn/Transition.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

//  An ATN transition between any two ATN states.  Subclasses define
//  atom, set, epsilon, action, predicate, rule transitions.
//
//  <p>This is a one way link.  It emanates from a state (usually via a list of
//  transitions) and has a target state.</p>
//
//  <p>Since we never have to change the ATN transitions once we construct it,
//  we can fix these transitions as specific classes. The DFA transitions
//  on the other hand need to update the labels as it adds transitions to
//  the states. We'll use the term Edge for the DFA to distinguish them from
//  ATN transitions.</p>

var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
var Predicate = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").Predicate;
var PrecedencePredicate = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").PrecedencePredicate;

function Transition(target) {
  // The target of this transition.
  if (target === undefined || target === null) {
    throw "target cannot be null.";
  }
  this.target = target;
  // Are we epsilon, action, sempred?
  this.isEpsilon = false;
  this.label = null;
  return this;
}
// constants for serialization
Transition.EPSILON = 1;
Transition.RANGE = 2;
Transition.RULE = 3;
Transition.PREDICATE = 4; // e.g., {isType(input.LT(1))}?
Transition.ATOM = 5;
Transition.ACTION = 6;
Transition.SET = 7; // ~(A|B) or ~atom, wildcard, which convert to next 2
Transition.NOT_SET = 8;
Transition.WILDCARD = 9;
Transition.PRECEDENCE = 10;

Transition.serializationNames = ["INVALID", "EPSILON", "RANGE", "RULE", "PREDICATE", "ATOM", "ACTION", "SET", "NOT_SET", "WILDCARD", "PRECEDENCE"];

Transition.serializationTypes = {
  EpsilonTransition: Transition.EPSILON,
  RangeTransition: Transition.RANGE,
  RuleTransition: Transition.RULE,
  PredicateTransition: Transition.PREDICATE,
  AtomTransition: Transition.ATOM,
  ActionTransition: Transition.ACTION,
  SetTransition: Transition.SET,
  NotSetTransition: Transition.NOT_SET,
  WildcardTransition: Transition.WILDCARD,
  PrecedencePredicateTransition: Transition.PRECEDENCE
};

// TODO: make all transitions sets? no, should remove set edges
function AtomTransition(target, label) {
  Transition.call(this, target);
  this.label_ = label; // The token type or character value; or, signifies special label.
  this.label = this.makeLabel();
  this.serializationType = Transition.ATOM;
  return this;
}

AtomTransition.prototype = Object.create(Transition.prototype);
AtomTransition.prototype.constructor = AtomTransition;

AtomTransition.prototype.makeLabel = function () {
  var s = new IntervalSet();
  s.addOne(this.label_);
  return s;
};

AtomTransition.prototype.matches = function (symbol, minVocabSymbol, maxVocabSymbol) {
  return this.label_ === symbol;
};

AtomTransition.prototype.toString = function () {
  return this.label_;
};

function RuleTransition(ruleStart, ruleIndex, precedence, followState) {
  Transition.call(this, ruleStart);
  this.ruleIndex = ruleIndex; // ptr to the rule definition object for this rule ref
  this.precedence = precedence;
  this.followState = followState; // what node to begin computations following ref to rule
  this.serializationType = Transition.RULE;
  this.isEpsilon = true;
  return this;
}

RuleTransition.prototype = Object.create(Transition.prototype);
RuleTransition.prototype.constructor = RuleTransition;

RuleTransition.prototype.matches = function (symbol, minVocabSymbol, maxVocabSymbol) {
  return false;
};

function EpsilonTransition(target, outermostPrecedenceReturn) {
  Transition.call(this, target);
  this.serializationType = Transition.EPSILON;
  this.isEpsilon = true;
  this.outermostPrecedenceReturn = outermostPrecedenceReturn;
  return this;
}

EpsilonTransition.prototype = Object.create(Transition.prototype);
EpsilonTransition.prototype.constructor = EpsilonTransition;

EpsilonTransition.prototype.matches = function (symbol, minVocabSymbol, maxVocabSymbol) {
  return false;
};

EpsilonTransition.prototype.toString = function () {
  return "epsilon";
};

function RangeTransition(target, start, stop) {
  Transition.call(this, target);
  this.serializationType = Transition.RANGE;
  this.start = start;
  this.stop = stop;
  this.label = this.makeLabel();
  return this;
}

RangeTransition.prototype = Object.create(Transition.prototype);
RangeTransition.prototype.constructor = RangeTransition;

RangeTransition.prototype.makeLabel = function () {
  var s = new IntervalSet();
  s.addRange(this.start, this.stop);
  return s;
};

RangeTransition.prototype.matches = function (symbol, minVocabSymbol, maxVocabSymbol) {
  return symbol >= this.start && symbol <= this.stop;
};

RangeTransition.prototype.toString = function () {
  return "'" + String.fromCharCode(this.start) + "'..'" + String.fromCharCode(this.stop) + "'";
};

function AbstractPredicateTransition(target) {
  Transition.call(this, target);
  return this;
}

AbstractPredicateTransition.prototype = Object.create(Transition.prototype);
AbstractPredicateTransition.prototype.constructor = AbstractPredicateTransition;

function PredicateTransition(target, ruleIndex, predIndex, isCtxDependent) {
  AbstractPredicateTransition.call(this, target);
  this.serializationType = Transition.PREDICATE;
  this.ruleIndex = ruleIndex;
  this.predIndex = predIndex;
  this.isCtxDependent = isCtxDependent; // e.g., $i ref in pred
  this.isEpsilon = true;
  return this;
}

PredicateTransition.prototype = Object.create(AbstractPredicateTransition.prototype);
PredicateTransition.prototype.constructor = PredicateTransition;

PredicateTransition.prototype.matches = function (symbol, minVocabSymbol, maxVocabSymbol) {
  return false;
};

PredicateTransition.prototype.getPredicate = function () {
  return new Predicate(this.ruleIndex, this.predIndex, this.isCtxDependent);
};

PredicateTransition.prototype.toString = function () {
  return "pred_" + this.ruleIndex + ":" + this.predIndex;
};

function ActionTransition(target, ruleIndex, actionIndex, isCtxDependent) {
  Transition.call(this, target);
  this.serializationType = Transition.ACTION;
  this.ruleIndex = ruleIndex;
  this.actionIndex = actionIndex === undefined ? -1 : actionIndex;
  this.isCtxDependent = isCtxDependent === undefined ? false : isCtxDependent; // e.g., $i ref in pred
  this.isEpsilon = true;
  return this;
}

ActionTransition.prototype = Object.create(Transition.prototype);
ActionTransition.prototype.constructor = ActionTransition;

ActionTransition.prototype.matches = function (symbol, minVocabSymbol, maxVocabSymbol) {
  return false;
};

ActionTransition.prototype.toString = function () {
  return "action_" + this.ruleIndex + ":" + this.actionIndex;
};

// A transition containing a set of values.
function SetTransition(target, set) {
  Transition.call(this, target);
  this.serializationType = Transition.SET;
  if (set !== undefined && set !== null) {
    this.label = set;
  } else {
    this.label = new IntervalSet();
    this.label.addOne(Token.INVALID_TYPE);
  }
  return this;
}

SetTransition.prototype = Object.create(Transition.prototype);
SetTransition.prototype.constructor = SetTransition;

SetTransition.prototype.matches = function (symbol, minVocabSymbol, maxVocabSymbol) {
  return this.label.contains(symbol);
};

SetTransition.prototype.toString = function () {
  return this.label.toString();
};

function NotSetTransition(target, set) {
  SetTransition.call(this, target, set);
  this.serializationType = Transition.NOT_SET;
  return this;
}

NotSetTransition.prototype = Object.create(SetTransition.prototype);
NotSetTransition.prototype.constructor = NotSetTransition;

NotSetTransition.prototype.matches = function (symbol, minVocabSymbol, maxVocabSymbol) {
  return symbol >= minVocabSymbol && symbol <= maxVocabSymbol && !SetTransition.prototype.matches.call(this, symbol, minVocabSymbol, maxVocabSymbol);
};

NotSetTransition.prototype.toString = function () {
  return '~' + SetTransition.prototype.toString.call(this);
};

function WildcardTransition(target) {
  Transition.call(this, target);
  this.serializationType = Transition.WILDCARD;
  return this;
}

WildcardTransition.prototype = Object.create(Transition.prototype);
WildcardTransition.prototype.constructor = WildcardTransition;

WildcardTransition.prototype.matches = function (symbol, minVocabSymbol, maxVocabSymbol) {
  return symbol >= minVocabSymbol && symbol <= maxVocabSymbol;
};

WildcardTransition.prototype.toString = function () {
  return ".";
};

function PrecedencePredicateTransition(target, precedence) {
  AbstractPredicateTransition.call(this, target);
  this.serializationType = Transition.PRECEDENCE;
  this.precedence = precedence;
  this.isEpsilon = true;
  return this;
}

PrecedencePredicateTransition.prototype = Object.create(AbstractPredicateTransition.prototype);
PrecedencePredicateTransition.prototype.constructor = PrecedencePredicateTransition;

PrecedencePredicateTransition.prototype.matches = function (symbol, minVocabSymbol, maxVocabSymbol) {
  return false;
};

PrecedencePredicateTransition.prototype.getPredicate = function () {
  return new PrecedencePredicate(this.precedence);
};

PrecedencePredicateTransition.prototype.toString = function () {
  return this.precedence + " >= _p";
};

exports.Transition = Transition;
exports.AtomTransition = AtomTransition;
exports.SetTransition = SetTransition;
exports.NotSetTransition = NotSetTransition;
exports.RuleTransition = RuleTransition;
exports.ActionTransition = ActionTransition;
exports.EpsilonTransition = EpsilonTransition;
exports.RangeTransition = RangeTransition;
exports.WildcardTransition = WildcardTransition;
exports.PredicateTransition = PredicateTransition;
exports.PrecedencePredicateTransition = PrecedencePredicateTransition;
exports.AbstractPredicateTransition = AbstractPredicateTransition;

/***/ }),

/***/ "./node_modules/antlr4/atn/index.js":
/*!******************************************!*\
  !*** ./node_modules/antlr4/atn/index.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

exports.ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
exports.ATNDeserializer = __webpack_require__(/*! ./ATNDeserializer */ "./node_modules/antlr4/atn/ATNDeserializer.js").ATNDeserializer;
exports.LexerATNSimulator = __webpack_require__(/*! ./LexerATNSimulator */ "./node_modules/antlr4/atn/LexerATNSimulator.js").LexerATNSimulator;
exports.ParserATNSimulator = __webpack_require__(/*! ./ParserATNSimulator */ "./node_modules/antlr4/atn/ParserATNSimulator.js").ParserATNSimulator;
exports.PredictionMode = __webpack_require__(/*! ./PredictionMode */ "./node_modules/antlr4/atn/PredictionMode.js").PredictionMode;

/***/ }),

/***/ "./node_modules/antlr4/dfa/DFA.js":
/*!****************************************!*\
  !*** ./node_modules/antlr4/dfa/DFA.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

var Set = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").Set;
var DFAState = __webpack_require__(/*! ./DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
var StarLoopEntryState = __webpack_require__(/*! ../atn/ATNState */ "./node_modules/antlr4/atn/ATNState.js").StarLoopEntryState;
var ATNConfigSet = __webpack_require__(/*! ./../atn/ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
var DFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").DFASerializer;
var LexerDFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").LexerDFASerializer;

function DFA(atnStartState, decision) {
	if (decision === undefined) {
		decision = 0;
	}
	// From which ATN state did we create this DFA?
	this.atnStartState = atnStartState;
	this.decision = decision;
	// A set of all DFA states. Use {@link Map} so we can get old state back
	// ({@link Set} only allows you to see if it's there).
	this._states = new Set();
	this.s0 = null;
	// {@code true} if this DFA is for a precedence decision; otherwise,
	// {@code false}. This is the backing field for {@link //isPrecedenceDfa},
	// {@link //setPrecedenceDfa}.
	this.precedenceDfa = false;
	if (atnStartState instanceof StarLoopEntryState) {
		if (atnStartState.isPrecedenceDecision) {
			this.precedenceDfa = true;
			var precedenceState = new DFAState(null, new ATNConfigSet());
			precedenceState.edges = [];
			precedenceState.isAcceptState = false;
			precedenceState.requiresFullContext = false;
			this.s0 = precedenceState;
		}
	}
	return this;
}

// Get the start state for a specific precedence value.
//
// @param precedence The current precedence.
// @return The start state corresponding to the specified precedence, or
// {@code null} if no start state exists for the specified precedence.
//
// @throws IllegalStateException if this is not a precedence DFA.
// @see //isPrecedenceDfa()

DFA.prototype.getPrecedenceStartState = function (precedence) {
	if (!this.precedenceDfa) {
		throw "Only precedence DFAs may contain a precedence start state.";
	}
	// s0.edges is never null for a precedence DFA
	if (precedence < 0 || precedence >= this.s0.edges.length) {
		return null;
	}
	return this.s0.edges[precedence] || null;
};

// Set the start state for a specific precedence value.
//
// @param precedence The current precedence.
// @param startState The start state corresponding to the specified
// precedence.
//
// @throws IllegalStateException if this is not a precedence DFA.
// @see //isPrecedenceDfa()
//
DFA.prototype.setPrecedenceStartState = function (precedence, startState) {
	if (!this.precedenceDfa) {
		throw "Only precedence DFAs may contain a precedence start state.";
	}
	if (precedence < 0) {
		return;
	}

	// synchronization on s0 here is ok. when the DFA is turned into a
	// precedence DFA, s0 will be initialized once and not updated again
	// s0.edges is never null for a precedence DFA
	this.s0.edges[precedence] = startState;
};

//
// Sets whether this is a precedence DFA. If the specified value differs
// from the current DFA configuration, the following actions are taken;
// otherwise no changes are made to the current DFA.
//
// <ul>
// <li>The {@link //states} map is cleared</li>
// <li>If {@code precedenceDfa} is {@code false}, the initial state
// {@link //s0} is set to {@code null}; otherwise, it is initialized to a new
// {@link DFAState} with an empty outgoing {@link DFAState//edges} array to
// store the start states for individual precedence values.</li>
// <li>The {@link //precedenceDfa} field is updated</li>
// </ul>
//
// @param precedenceDfa {@code true} if this is a precedence DFA; otherwise,
// {@code false}

DFA.prototype.setPrecedenceDfa = function (precedenceDfa) {
	if (this.precedenceDfa !== precedenceDfa) {
		this._states = new DFAStatesSet();
		if (precedenceDfa) {
			var precedenceState = new DFAState(null, new ATNConfigSet());
			precedenceState.edges = [];
			precedenceState.isAcceptState = false;
			precedenceState.requiresFullContext = false;
			this.s0 = precedenceState;
		} else {
			this.s0 = null;
		}
		this.precedenceDfa = precedenceDfa;
	}
};

Object.defineProperty(DFA.prototype, "states", {
	get: function get() {
		return this._states;
	}
});

// Return a list of all states in this DFA, ordered by state number.
DFA.prototype.sortedStates = function () {
	var list = this._states.values();
	return list.sort(function (a, b) {
		return a.stateNumber - b.stateNumber;
	});
};

DFA.prototype.toString = function (literalNames, symbolicNames) {
	literalNames = literalNames || null;
	symbolicNames = symbolicNames || null;
	if (this.s0 === null) {
		return "";
	}
	var serializer = new DFASerializer(this, literalNames, symbolicNames);
	return serializer.toString();
};

DFA.prototype.toLexerString = function () {
	if (this.s0 === null) {
		return "";
	}
	var serializer = new LexerDFASerializer(this);
	return serializer.toString();
};

exports.DFA = DFA;

/***/ }),

/***/ "./node_modules/antlr4/dfa/DFASerializer.js":
/*!**************************************************!*\
  !*** ./node_modules/antlr4/dfa/DFASerializer.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

// A DFA walker that knows how to dump them to serialized strings.#/


function DFASerializer(dfa, literalNames, symbolicNames) {
    this.dfa = dfa;
    this.literalNames = literalNames || [];
    this.symbolicNames = symbolicNames || [];
    return this;
}

DFASerializer.prototype.toString = function () {
    if (this.dfa.s0 === null) {
        return null;
    }
    var buf = "";
    var states = this.dfa.sortedStates();
    for (var i = 0; i < states.length; i++) {
        var s = states[i];
        if (s.edges !== null) {
            var n = s.edges.length;
            for (var j = 0; j < n; j++) {
                var t = s.edges[j] || null;
                if (t !== null && t.stateNumber !== 0x7FFFFFFF) {
                    buf = buf.concat(this.getStateString(s));
                    buf = buf.concat("-");
                    buf = buf.concat(this.getEdgeLabel(j));
                    buf = buf.concat("->");
                    buf = buf.concat(this.getStateString(t));
                    buf = buf.concat('\n');
                }
            }
        }
    }
    return buf.length === 0 ? null : buf;
};

DFASerializer.prototype.getEdgeLabel = function (i) {
    if (i === 0) {
        return "EOF";
    } else if (this.literalNames !== null || this.symbolicNames !== null) {
        return this.literalNames[i - 1] || this.symbolicNames[i - 1];
    } else {
        return String.fromCharCode(i - 1);
    }
};

DFASerializer.prototype.getStateString = function (s) {
    var baseStateStr = (s.isAcceptState ? ":" : "") + "s" + s.stateNumber + (s.requiresFullContext ? "^" : "");
    if (s.isAcceptState) {
        if (s.predicates !== null) {
            return baseStateStr + "=>" + s.predicates.toString();
        } else {
            return baseStateStr + "=>" + s.prediction.toString();
        }
    } else {
        return baseStateStr;
    }
};

function LexerDFASerializer(dfa) {
    DFASerializer.call(this, dfa, null);
    return this;
}

LexerDFASerializer.prototype = Object.create(DFASerializer.prototype);
LexerDFASerializer.prototype.constructor = LexerDFASerializer;

LexerDFASerializer.prototype.getEdgeLabel = function (i) {
    return "'" + String.fromCharCode(i) + "'";
};

exports.DFASerializer = DFASerializer;
exports.LexerDFASerializer = LexerDFASerializer;

/***/ }),

/***/ "./node_modules/antlr4/dfa/DFAState.js":
/*!*********************************************!*\
  !*** ./node_modules/antlr4/dfa/DFAState.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

var ATNConfigSet = __webpack_require__(/*! ./../atn/ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
var Hash = Utils.Hash;
var Set = Utils.Set;

// Map a predicate to a predicted alternative.///

function PredPrediction(pred, alt) {
	this.alt = alt;
	this.pred = pred;
	return this;
}

PredPrediction.prototype.toString = function () {
	return "(" + this.pred + ", " + this.alt + ")";
};

// A DFA state represents a set of possible ATN configurations.
// As Aho, Sethi, Ullman p. 117 says "The DFA uses its state
// to keep track of all possible states the ATN can be in after
// reading each input symbol. That is to say, after reading
// input a1a2..an, the DFA is in a state that represents the
// subset T of the states of the ATN that are reachable from the
// ATN's start state along some path labeled a1a2..an."
// In conventional NFA&rarr;DFA conversion, therefore, the subset T
// would be a bitset representing the set of states the
// ATN could be in. We need to track the alt predicted by each
// state as well, however. More importantly, we need to maintain
// a stack of states, tracking the closure operations as they
// jump from rule to rule, emulating rule invocations (method calls).
// I have to add a stack to simulate the proper lookahead sequences for
// the underlying LL grammar from which the ATN was derived.
//
// <p>I use a set of ATNConfig objects not simple states. An ATNConfig
// is both a state (ala normal conversion) and a RuleContext describing
// the chain of rules (if any) followed to arrive at that state.</p>
//
// <p>A DFA state may have multiple references to a particular state,
// but with different ATN contexts (with same or different alts)
// meaning that state was reached via a different set of rule invocations.</p>
// /

function DFAState(stateNumber, configs) {
	if (stateNumber === null) {
		stateNumber = -1;
	}
	if (configs === null) {
		configs = new ATNConfigSet();
	}
	this.stateNumber = stateNumber;
	this.configs = configs;
	// {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)
	// {@link Token//EOF} maps to {@code edges[0]}.
	this.edges = null;
	this.isAcceptState = false;
	// if accept state, what ttype do we match or alt do we predict?
	// This is set to {@link ATN//INVALID_ALT_NUMBER} when {@link
	// //predicates}{@code !=null} or
	// {@link //requiresFullContext}.
	this.prediction = 0;
	this.lexerActionExecutor = null;
	// Indicates that this state was created during SLL prediction that
	// discovered a conflict between the configurations in the state. Future
	// {@link ParserATNSimulator//execATN} invocations immediately jumped doing
	// full context prediction if this field is true.
	this.requiresFullContext = false;
	// During SLL parsing, this is a list of predicates associated with the
	// ATN configurations of the DFA state. When we have predicates,
	// {@link //requiresFullContext} is {@code false} since full context
	// prediction evaluates predicates
	// on-the-fly. If this is not null, then {@link //prediction} is
	// {@link ATN//INVALID_ALT_NUMBER}.
	//
	// <p>We only use these for non-{@link //requiresFullContext} but
	// conflicting states. That
	// means we know from the context (it's $ or we don't dip into outer
	// context) that it's an ambiguity not a conflict.</p>
	//
	// <p>This list is computed by {@link
	// ParserATNSimulator//predicateDFAState}.</p>
	this.predicates = null;
	return this;
}

// Get the set of all alts mentioned by all ATN configurations in this
// DFA state.
DFAState.prototype.getAltSet = function () {
	var alts = new Set();
	if (this.configs !== null) {
		for (var i = 0; i < this.configs.length; i++) {
			var c = this.configs[i];
			alts.add(c.alt);
		}
	}
	if (alts.length === 0) {
		return null;
	} else {
		return alts;
	}
};

// Two {@link DFAState} instances are equal if their ATN configuration sets
// are the same. This method is used to see if a state already exists.
//
// <p>Because the number of alternatives and number of ATN configurations are
// finite, there is a finite number of DFA states that can be processed.
// This is necessary to show that the algorithm terminates.</p>
//
// <p>Cannot test the DFA state numbers here because in
// {@link ParserATNSimulator//addDFAState} we need to know if any other state
// exists that has this exact set of ATN configurations. The
// {@link //stateNumber} is irrelevant.</p>
DFAState.prototype.equals = function (other) {
	// compare set of ATN configurations in this set with other
	return this === other || other instanceof DFAState && this.configs.equals(other.configs);
};

DFAState.prototype.toString = function () {
	var s = "" + this.stateNumber + ":" + this.configs;
	if (this.isAcceptState) {
		s = s + "=>";
		if (this.predicates !== null) s = s + this.predicates;else s = s + this.prediction;
	}
	return s;
};

DFAState.prototype.hashCode = function () {
	var hash = new Hash();
	hash.update(this.configs);
	if (this.isAcceptState) {
		if (this.predicates !== null) hash.update(this.predicates);else hash.update(this.prediction);
	}
	return hash.finish();
};

exports.DFAState = DFAState;
exports.PredPrediction = PredPrediction;

/***/ }),

/***/ "./node_modules/antlr4/dfa/index.js":
/*!******************************************!*\
  !*** ./node_modules/antlr4/dfa/index.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

exports.DFA = __webpack_require__(/*! ./DFA */ "./node_modules/antlr4/dfa/DFA.js").DFA;
exports.DFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").DFASerializer;
exports.LexerDFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").LexerDFASerializer;
exports.PredPrediction = __webpack_require__(/*! ./DFAState */ "./node_modules/antlr4/dfa/DFAState.js").PredPrediction;

/***/ }),

/***/ "./node_modules/antlr4/error/DiagnosticErrorListener.js":
/*!**************************************************************!*\
  !*** ./node_modules/antlr4/error/DiagnosticErrorListener.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

//
// This implementation of {@link ANTLRErrorListener} can be used to identify
// certain potential correctness and performance problems in grammars. "Reports"
// are made by calling {@link Parser//notifyErrorListeners} with the appropriate
// message.
//
// <ul>
// <li><b>Ambiguities</b>: These are cases where more than one path through the
// grammar can match the input.</li>
// <li><b>Weak context sensitivity</b>: These are cases where full-context
// prediction resolved an SLL conflict to a unique alternative which equaled the
// minimum alternative of the SLL conflict.</li>
// <li><b>Strong (forced) context sensitivity</b>: These are cases where the
// full-context prediction resolved an SLL conflict to a unique alternative,
// <em>and</em> the minimum alternative of the SLL conflict was found to not be
// a truly viable alternative. Two-stage parsing cannot be used for inputs where
// this situation occurs.</li>
// </ul>

var BitSet = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").BitSet;
var ErrorListener = __webpack_require__(/*! ./ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ErrorListener;
var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;

function DiagnosticErrorListener(exactOnly) {
	ErrorListener.call(this);
	exactOnly = exactOnly || true;
	// whether all ambiguities or only exact ambiguities are reported.
	this.exactOnly = exactOnly;
	return this;
}

DiagnosticErrorListener.prototype = Object.create(ErrorListener.prototype);
DiagnosticErrorListener.prototype.constructor = DiagnosticErrorListener;

DiagnosticErrorListener.prototype.reportAmbiguity = function (recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {
	if (this.exactOnly && !exact) {
		return;
	}
	var msg = "reportAmbiguity d=" + this.getDecisionDescription(recognizer, dfa) + ": ambigAlts=" + this.getConflictingAlts(ambigAlts, configs) + ", input='" + recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'";
	recognizer.notifyErrorListeners(msg);
};

DiagnosticErrorListener.prototype.reportAttemptingFullContext = function (recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
	var msg = "reportAttemptingFullContext d=" + this.getDecisionDescription(recognizer, dfa) + ", input='" + recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'";
	recognizer.notifyErrorListeners(msg);
};

DiagnosticErrorListener.prototype.reportContextSensitivity = function (recognizer, dfa, startIndex, stopIndex, prediction, configs) {
	var msg = "reportContextSensitivity d=" + this.getDecisionDescription(recognizer, dfa) + ", input='" + recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'";
	recognizer.notifyErrorListeners(msg);
};

DiagnosticErrorListener.prototype.getDecisionDescription = function (recognizer, dfa) {
	var decision = dfa.decision;
	var ruleIndex = dfa.atnStartState.ruleIndex;

	var ruleNames = recognizer.ruleNames;
	if (ruleIndex < 0 || ruleIndex >= ruleNames.length) {
		return "" + decision;
	}
	var ruleName = ruleNames[ruleIndex] || null;
	if (ruleName === null || ruleName.length === 0) {
		return "" + decision;
	}
	return "" + decision + " (" + ruleName + ")";
};

//
// Computes the set of conflicting or ambiguous alternatives from a
// configuration set, if that information was not already provided by the
// parser.
//
// @param reportedAlts The set of conflicting or ambiguous alternatives, as
// reported by the parser.
// @param configs The conflicting or ambiguous configuration set.
// @return Returns {@code reportedAlts} if it is not {@code null}, otherwise
// returns the set of alternatives represented in {@code configs}.
//
DiagnosticErrorListener.prototype.getConflictingAlts = function (reportedAlts, configs) {
	if (reportedAlts !== null) {
		return reportedAlts;
	}
	var result = new BitSet();
	for (var i = 0; i < configs.items.length; i++) {
		result.add(configs.items[i].alt);
	}
	return "{" + result.values().join(", ") + "}";
};

exports.DiagnosticErrorListener = DiagnosticErrorListener;

/***/ }),

/***/ "./node_modules/antlr4/error/ErrorListener.js":
/*!****************************************************!*\
  !*** ./node_modules/antlr4/error/ErrorListener.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

// Provides an empty default implementation of {@link ANTLRErrorListener}. The
// default implementation of each method does nothing, but can be overridden as
// necessary.

function ErrorListener() {
  return this;
}

ErrorListener.prototype.syntaxError = function (recognizer, offendingSymbol, line, column, msg, e) {};

ErrorListener.prototype.reportAmbiguity = function (recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {};

ErrorListener.prototype.reportAttemptingFullContext = function (recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {};

ErrorListener.prototype.reportContextSensitivity = function (recognizer, dfa, startIndex, stopIndex, prediction, configs) {};

function ConsoleErrorListener() {
  ErrorListener.call(this);
  return this;
}

ConsoleErrorListener.prototype = Object.create(ErrorListener.prototype);
ConsoleErrorListener.prototype.constructor = ConsoleErrorListener;

//
// Provides a default instance of {@link ConsoleErrorListener}.
//
ConsoleErrorListener.INSTANCE = new ConsoleErrorListener();

//
// {@inheritDoc}
//
// <p>
// This implementation prints messages to {@link System//err} containing the
// values of {@code line}, {@code charPositionInLine}, and {@code msg} using
// the following format.</p>
//
// <pre>
// line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>
// </pre>
//
ConsoleErrorListener.prototype.syntaxError = function (recognizer, offendingSymbol, line, column, msg, e) {
  console.error("line " + line + ":" + column + " " + msg);
};

function ProxyErrorListener(delegates) {
  ErrorListener.call(this);
  if (delegates === null) {
    throw "delegates";
  }
  this.delegates = delegates;
  return this;
}

ProxyErrorListener.prototype = Object.create(ErrorListener.prototype);
ProxyErrorListener.prototype.constructor = ProxyErrorListener;

ProxyErrorListener.prototype.syntaxError = function (recognizer, offendingSymbol, line, column, msg, e) {
  this.delegates.map(function (d) {
    d.syntaxError(recognizer, offendingSymbol, line, column, msg, e);
  });
};

ProxyErrorListener.prototype.reportAmbiguity = function (recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {
  this.delegates.map(function (d) {
    d.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs);
  });
};

ProxyErrorListener.prototype.reportAttemptingFullContext = function (recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
  this.delegates.map(function (d) {
    d.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs);
  });
};

ProxyErrorListener.prototype.reportContextSensitivity = function (recognizer, dfa, startIndex, stopIndex, prediction, configs) {
  this.delegates.map(function (d) {
    d.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs);
  });
};

exports.ErrorListener = ErrorListener;
exports.ConsoleErrorListener = ConsoleErrorListener;
exports.ProxyErrorListener = ProxyErrorListener;

/***/ }),

/***/ "./node_modules/antlr4/error/ErrorStrategy.js":
/*!****************************************************!*\
  !*** ./node_modules/antlr4/error/ErrorStrategy.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
//

var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
var Errors = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js");
var NoViableAltException = Errors.NoViableAltException;
var InputMismatchException = Errors.InputMismatchException;
var FailedPredicateException = Errors.FailedPredicateException;
var ParseCancellationException = Errors.ParseCancellationException;
var ATNState = __webpack_require__(/*! ./../atn/ATNState */ "./node_modules/antlr4/atn/ATNState.js").ATNState;
var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;

function ErrorStrategy() {}

ErrorStrategy.prototype.reset = function (recognizer) {};

ErrorStrategy.prototype.recoverInline = function (recognizer) {};

ErrorStrategy.prototype.recover = function (recognizer, e) {};

ErrorStrategy.prototype.sync = function (recognizer) {};

ErrorStrategy.prototype.inErrorRecoveryMode = function (recognizer) {};

ErrorStrategy.prototype.reportError = function (recognizer) {};

// This is the default implementation of {@link ANTLRErrorStrategy} used for
// error reporting and recovery in ANTLR parsers.
//
function DefaultErrorStrategy() {
    ErrorStrategy.call(this);
    // Indicates whether the error strategy is currently "recovering from an
    // error". This is used to suppress reporting multiple error messages while
    // attempting to recover from a detected syntax error.
    //
    // @see //inErrorRecoveryMode
    //
    this.errorRecoveryMode = false;

    // The index into the input stream where the last error occurred.
    // This is used to prevent infinite loops where an error is found
    // but no token is consumed during recovery...another error is found,
    // ad nauseum. This is a failsafe mechanism to guarantee that at least
    // one token/tree node is consumed for two errors.
    //
    this.lastErrorIndex = -1;
    this.lastErrorStates = null;
    return this;
}

DefaultErrorStrategy.prototype = Object.create(ErrorStrategy.prototype);
DefaultErrorStrategy.prototype.constructor = DefaultErrorStrategy;

// <p>The default implementation simply calls {@link //endErrorCondition} to
// ensure that the handler is not in error recovery mode.</p>
DefaultErrorStrategy.prototype.reset = function (recognizer) {
    this.endErrorCondition(recognizer);
};

//
// This method is called to enter error recovery mode when a recognition
// exception is reported.
//
// @param recognizer the parser instance
//
DefaultErrorStrategy.prototype.beginErrorCondition = function (recognizer) {
    this.errorRecoveryMode = true;
};

DefaultErrorStrategy.prototype.inErrorRecoveryMode = function (recognizer) {
    return this.errorRecoveryMode;
};

//
// This method is called to leave error recovery mode after recovering from
// a recognition exception.
//
// @param recognizer
//
DefaultErrorStrategy.prototype.endErrorCondition = function (recognizer) {
    this.errorRecoveryMode = false;
    this.lastErrorStates = null;
    this.lastErrorIndex = -1;
};

//
// {@inheritDoc}
//
// <p>The default implementation simply calls {@link //endErrorCondition}.</p>
//
DefaultErrorStrategy.prototype.reportMatch = function (recognizer) {
    this.endErrorCondition(recognizer);
};

//
// {@inheritDoc}
//
// <p>The default implementation returns immediately if the handler is already
// in error recovery mode. Otherwise, it calls {@link //beginErrorCondition}
// and dispatches the reporting task based on the runtime type of {@code e}
// according to the following table.</p>
//
// <ul>
// <li>{@link NoViableAltException}: Dispatches the call to
// {@link //reportNoViableAlternative}</li>
// <li>{@link InputMismatchException}: Dispatches the call to
// {@link //reportInputMismatch}</li>
// <li>{@link FailedPredicateException}: Dispatches the call to
// {@link //reportFailedPredicate}</li>
// <li>All other types: calls {@link Parser//notifyErrorListeners} to report
// the exception</li>
// </ul>
//
DefaultErrorStrategy.prototype.reportError = function (recognizer, e) {
    // if we've already reported an error and have not matched a token
    // yet successfully, don't report any errors.
    if (this.inErrorRecoveryMode(recognizer)) {
        return; // don't report spurious errors
    }
    this.beginErrorCondition(recognizer);
    if (e instanceof NoViableAltException) {
        this.reportNoViableAlternative(recognizer, e);
    } else if (e instanceof InputMismatchException) {
        this.reportInputMismatch(recognizer, e);
    } else if (e instanceof FailedPredicateException) {
        this.reportFailedPredicate(recognizer, e);
    } else {
        console.log("unknown recognition error type: " + e.constructor.name);
        console.log(e.stack);
        recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e);
    }
};
//
// {@inheritDoc}
//
// <p>The default implementation resynchronizes the parser by consuming tokens
// until we find one in the resynchronization set--loosely the set of tokens
// that can follow the current rule.</p>
//
DefaultErrorStrategy.prototype.recover = function (recognizer, e) {
    if (this.lastErrorIndex === recognizer.getInputStream().index && this.lastErrorStates !== null && this.lastErrorStates.indexOf(recognizer.state) >= 0) {
        // uh oh, another error at same token index and previously-visited
        // state in ATN; must be a case where LT(1) is in the recovery
        // token set so nothing got consumed. Consume a single token
        // at least to prevent an infinite loop; this is a failsafe.
        recognizer.consume();
    }
    this.lastErrorIndex = recognizer._input.index;
    if (this.lastErrorStates === null) {
        this.lastErrorStates = [];
    }
    this.lastErrorStates.push(recognizer.state);
    var followSet = this.getErrorRecoverySet(recognizer);
    this.consumeUntil(recognizer, followSet);
};

// The default implementation of {@link ANTLRErrorStrategy//sync} makes sure
// that the current lookahead symbol is consistent with what were expecting
// at this point in the ATN. You can call this anytime but ANTLR only
// generates code to check before subrules/loops and each iteration.
//
// <p>Implements Jim Idle's magic sync mechanism in closures and optional
// subrules. E.g.,</p>
//
// <pre>
// a : sync ( stuff sync )* ;
// sync : {consume to what can follow sync} ;
// </pre>
//
// At the start of a sub rule upon error, {@link //sync} performs single
// token deletion, if possible. If it can't do that, it bails on the current
// rule and uses the default error recovery, which consumes until the
// resynchronization set of the current rule.
//
// <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block
// with an empty alternative), then the expected set includes what follows
// the subrule.</p>
//
// <p>During loop iteration, it consumes until it sees a token that can start a
// sub rule or what follows loop. Yes, that is pretty aggressive. We opt to
// stay in the loop as long as possible.</p>
//
// <p><strong>ORIGINS</strong></p>
//
// <p>Previous versions of ANTLR did a poor job of their recovery within loops.
// A single mismatch token or missing token would force the parser to bail
// out of the entire rules surrounding the loop. So, for rule</p>
//
// <pre>
// classDef : 'class' ID '{' member* '}'
// </pre>
//
// input with an extra token between members would force the parser to
// consume until it found the next class definition rather than the next
// member definition of the current class.
//
// <p>This functionality cost a little bit of effort because the parser has to
// compare token set at the start of the loop and at each iteration. If for
// some reason speed is suffering for you, you can turn off this
// functionality by simply overriding this method as a blank { }.</p>
//
DefaultErrorStrategy.prototype.sync = function (recognizer) {
    // If already recovering, don't try to sync
    if (this.inErrorRecoveryMode(recognizer)) {
        return;
    }
    var s = recognizer._interp.atn.states[recognizer.state];
    var la = recognizer.getTokenStream().LA(1);
    // try cheaper subset first; might get lucky. seems to shave a wee bit off
    var nextTokens = recognizer.atn.nextTokens(s);
    if (nextTokens.contains(Token.EPSILON) || nextTokens.contains(la)) {
        return;
    }
    switch (s.stateType) {
        case ATNState.BLOCK_START:
        case ATNState.STAR_BLOCK_START:
        case ATNState.PLUS_BLOCK_START:
        case ATNState.STAR_LOOP_ENTRY:
            // report error and recover if possible
            if (this.singleTokenDeletion(recognizer) !== null) {
                return;
            } else {
                throw new InputMismatchException(recognizer);
            }
            break;
        case ATNState.PLUS_LOOP_BACK:
        case ATNState.STAR_LOOP_BACK:
            this.reportUnwantedToken(recognizer);
            var expecting = new IntervalSet();
            expecting.addSet(recognizer.getExpectedTokens());
            var whatFollowsLoopIterationOrRule = expecting.addSet(this.getErrorRecoverySet(recognizer));
            this.consumeUntil(recognizer, whatFollowsLoopIterationOrRule);
            break;
        default:
        // do nothing if we can't identify the exact kind of ATN state
    }
};

// This is called by {@link //reportError} when the exception is a
// {@link NoViableAltException}.
//
// @see //reportError
//
// @param recognizer the parser instance
// @param e the recognition exception
//
DefaultErrorStrategy.prototype.reportNoViableAlternative = function (recognizer, e) {
    var tokens = recognizer.getTokenStream();
    var input;
    if (tokens !== null) {
        if (e.startToken.type === Token.EOF) {
            input = "<EOF>";
        } else {
            input = tokens.getText(new Interval(e.startToken.tokenIndex, e.offendingToken.tokenIndex));
        }
    } else {
        input = "<unknown input>";
    }
    var msg = "no viable alternative at input " + this.escapeWSAndQuote(input);
    recognizer.notifyErrorListeners(msg, e.offendingToken, e);
};

//
// This is called by {@link //reportError} when the exception is an
// {@link InputMismatchException}.
//
// @see //reportError
//
// @param recognizer the parser instance
// @param e the recognition exception
//
DefaultErrorStrategy.prototype.reportInputMismatch = function (recognizer, e) {
    var msg = "mismatched input " + this.getTokenErrorDisplay(e.offendingToken) + " expecting " + e.getExpectedTokens().toString(recognizer.literalNames, recognizer.symbolicNames);
    recognizer.notifyErrorListeners(msg, e.offendingToken, e);
};

//
// This is called by {@link //reportError} when the exception is a
// {@link FailedPredicateException}.
//
// @see //reportError
//
// @param recognizer the parser instance
// @param e the recognition exception
//
DefaultErrorStrategy.prototype.reportFailedPredicate = function (recognizer, e) {
    var ruleName = recognizer.ruleNames[recognizer._ctx.ruleIndex];
    var msg = "rule " + ruleName + " " + e.message;
    recognizer.notifyErrorListeners(msg, e.offendingToken, e);
};

// This method is called to report a syntax error which requires the removal
// of a token from the input stream. At the time this method is called, the
// erroneous symbol is current {@code LT(1)} symbol and has not yet been
// removed from the input stream. When this method returns,
// {@code recognizer} is in error recovery mode.
//
// <p>This method is called when {@link //singleTokenDeletion} identifies
// single-token deletion as a viable recovery strategy for a mismatched
// input error.</p>
//
// <p>The default implementation simply returns if the handler is already in
// error recovery mode. Otherwise, it calls {@link //beginErrorCondition} to
// enter error recovery mode, followed by calling
// {@link Parser//notifyErrorListeners}.</p>
//
// @param recognizer the parser instance
//
DefaultErrorStrategy.prototype.reportUnwantedToken = function (recognizer) {
    if (this.inErrorRecoveryMode(recognizer)) {
        return;
    }
    this.beginErrorCondition(recognizer);
    var t = recognizer.getCurrentToken();
    var tokenName = this.getTokenErrorDisplay(t);
    var expecting = this.getExpectedTokens(recognizer);
    var msg = "extraneous input " + tokenName + " expecting " + expecting.toString(recognizer.literalNames, recognizer.symbolicNames);
    recognizer.notifyErrorListeners(msg, t, null);
};
// This method is called to report a syntax error which requires the
// insertion of a missing token into the input stream. At the time this
// method is called, the missing token has not yet been inserted. When this
// method returns, {@code recognizer} is in error recovery mode.
//
// <p>This method is called when {@link //singleTokenInsertion} identifies
// single-token insertion as a viable recovery strategy for a mismatched
// input error.</p>
//
// <p>The default implementation simply returns if the handler is already in
// error recovery mode. Otherwise, it calls {@link //beginErrorCondition} to
// enter error recovery mode, followed by calling
// {@link Parser//notifyErrorListeners}.</p>
//
// @param recognizer the parser instance
//
DefaultErrorStrategy.prototype.reportMissingToken = function (recognizer) {
    if (this.inErrorRecoveryMode(recognizer)) {
        return;
    }
    this.beginErrorCondition(recognizer);
    var t = recognizer.getCurrentToken();
    var expecting = this.getExpectedTokens(recognizer);
    var msg = "missing " + expecting.toString(recognizer.literalNames, recognizer.symbolicNames) + " at " + this.getTokenErrorDisplay(t);
    recognizer.notifyErrorListeners(msg, t, null);
};

// <p>The default implementation attempts to recover from the mismatched input
// by using single token insertion and deletion as described below. If the
// recovery attempt fails, this method throws an
// {@link InputMismatchException}.</p>
//
// <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>
//
// <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the
// right token, however, then assume {@code LA(1)} is some extra spurious
// token and delete it. Then consume and return the next token (which was
// the {@code LA(2)} token) as the successful result of the match operation.</p>
//
// <p>This recovery strategy is implemented by {@link
// //singleTokenDeletion}.</p>
//
// <p><strong>MISSING TOKEN</strong> (single token insertion)</p>
//
// <p>If current token (at {@code LA(1)}) is consistent with what could come
// after the expected {@code LA(1)} token, then assume the token is missing
// and use the parser's {@link TokenFactory} to create it on the fly. The
// "insertion" is performed by returning the created token as the successful
// result of the match operation.</p>
//
// <p>This recovery strategy is implemented by {@link
// //singleTokenInsertion}.</p>
//
// <p><strong>EXAMPLE</strong></p>
//
// <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When
// the parser returns from the nested call to {@code expr}, it will have
// call chain:</p>
//
// <pre>
// stat &rarr; expr &rarr; atom
// </pre>
//
// and it will be trying to match the {@code ')'} at this point in the
// derivation:
//
// <pre>
// =&gt; ID '=' '(' INT ')' ('+' atom)* ';'
// ^
// </pre>
//
// The attempt to match {@code ')'} will fail when it sees {@code ';'} and
// call {@link //recoverInline}. To recover, it sees that {@code LA(1)==';'}
// is in the set of tokens that can follow the {@code ')'} token reference
// in rule {@code atom}. It can assume that you forgot the {@code ')'}.
//
DefaultErrorStrategy.prototype.recoverInline = function (recognizer) {
    // SINGLE TOKEN DELETION
    var matchedSymbol = this.singleTokenDeletion(recognizer);
    if (matchedSymbol !== null) {
        // we have deleted the extra token.
        // now, move past ttype token as if all were ok
        recognizer.consume();
        return matchedSymbol;
    }
    // SINGLE TOKEN INSERTION
    if (this.singleTokenInsertion(recognizer)) {
        return this.getMissingSymbol(recognizer);
    }
    // even that didn't work; must throw the exception
    throw new InputMismatchException(recognizer);
};

//
// This method implements the single-token insertion inline error recovery
// strategy. It is called by {@link //recoverInline} if the single-token
// deletion strategy fails to recover from the mismatched input. If this
// method returns {@code true}, {@code recognizer} will be in error recovery
// mode.
//
// <p>This method determines whether or not single-token insertion is viable by
// checking if the {@code LA(1)} input symbol could be successfully matched
// if it were instead the {@code LA(2)} symbol. If this method returns
// {@code true}, the caller is responsible for creating and inserting a
// token with the correct type to produce this behavior.</p>
//
// @param recognizer the parser instance
// @return {@code true} if single-token insertion is a viable recovery
// strategy for the current mismatched input, otherwise {@code false}
//
DefaultErrorStrategy.prototype.singleTokenInsertion = function (recognizer) {
    var currentSymbolType = recognizer.getTokenStream().LA(1);
    // if current token is consistent with what could come after current
    // ATN state, then we know we're missing a token; error recovery
    // is free to conjure up and insert the missing token
    var atn = recognizer._interp.atn;
    var currentState = atn.states[recognizer.state];
    var next = currentState.transitions[0].target;
    var expectingAtLL2 = atn.nextTokens(next, recognizer._ctx);
    if (expectingAtLL2.contains(currentSymbolType)) {
        this.reportMissingToken(recognizer);
        return true;
    } else {
        return false;
    }
};

// This method implements the single-token deletion inline error recovery
// strategy. It is called by {@link //recoverInline} to attempt to recover
// from mismatched input. If this method returns null, the parser and error
// handler state will not have changed. If this method returns non-null,
// {@code recognizer} will <em>not</em> be in error recovery mode since the
// returned token was a successful match.
//
// <p>If the single-token deletion is successful, this method calls
// {@link //reportUnwantedToken} to report the error, followed by
// {@link Parser//consume} to actually "delete" the extraneous token. Then,
// before returning {@link //reportMatch} is called to signal a successful
// match.</p>
//
// @param recognizer the parser instance
// @return the successfully matched {@link Token} instance if single-token
// deletion successfully recovers from the mismatched input, otherwise
// {@code null}
//
DefaultErrorStrategy.prototype.singleTokenDeletion = function (recognizer) {
    var nextTokenType = recognizer.getTokenStream().LA(2);
    var expecting = this.getExpectedTokens(recognizer);
    if (expecting.contains(nextTokenType)) {
        this.reportUnwantedToken(recognizer);
        // print("recoverFromMismatchedToken deleting " \
        // + str(recognizer.getTokenStream().LT(1)) \
        // + " since " + str(recognizer.getTokenStream().LT(2)) \
        // + " is what we want", file=sys.stderr)
        recognizer.consume(); // simply delete extra token
        // we want to return the token we're actually matching
        var matchedSymbol = recognizer.getCurrentToken();
        this.reportMatch(recognizer); // we know current token is correct
        return matchedSymbol;
    } else {
        return null;
    }
};

// Conjure up a missing token during error recovery.
//
// The recognizer attempts to recover from single missing
// symbols. But, actions might refer to that missing symbol.
// For example, x=ID {f($x);}. The action clearly assumes
// that there has been an identifier matched previously and that
// $x points at that token. If that token is missing, but
// the next token in the stream is what we want we assume that
// this token is missing and we keep going. Because we
// have to return some token to replace the missing token,
// we have to conjure one up. This method gives the user control
// over the tokens returned for missing tokens. Mostly,
// you will want to create something special for identifier
// tokens. For literals such as '{' and ',', the default
// action in the parser or tree parser works. It simply creates
// a CommonToken of the appropriate type. The text will be the token.
// If you change what tokens must be created by the lexer,
// override this method to create the appropriate tokens.
//
DefaultErrorStrategy.prototype.getMissingSymbol = function (recognizer) {
    var currentSymbol = recognizer.getCurrentToken();
    var expecting = this.getExpectedTokens(recognizer);
    var expectedTokenType = expecting.first(); // get any element
    var tokenText;
    if (expectedTokenType === Token.EOF) {
        tokenText = "<missing EOF>";
    } else {
        tokenText = "<missing " + recognizer.literalNames[expectedTokenType] + ">";
    }
    var current = currentSymbol;
    var lookback = recognizer.getTokenStream().LT(-1);
    if (current.type === Token.EOF && lookback !== null) {
        current = lookback;
    }
    return recognizer.getTokenFactory().create(current.source, expectedTokenType, tokenText, Token.DEFAULT_CHANNEL, -1, -1, current.line, current.column);
};

DefaultErrorStrategy.prototype.getExpectedTokens = function (recognizer) {
    return recognizer.getExpectedTokens();
};

// How should a token be displayed in an error message? The default
// is to display just the text, but during development you might
// want to have a lot of information spit out. Override in that case
// to use t.toString() (which, for CommonToken, dumps everything about
// the token). This is better than forcing you to override a method in
// your token objects because you don't have to go modify your lexer
// so that it creates a new Java type.
//
DefaultErrorStrategy.prototype.getTokenErrorDisplay = function (t) {
    if (t === null) {
        return "<no token>";
    }
    var s = t.text;
    if (s === null) {
        if (t.type === Token.EOF) {
            s = "<EOF>";
        } else {
            s = "<" + t.type + ">";
        }
    }
    return this.escapeWSAndQuote(s);
};

DefaultErrorStrategy.prototype.escapeWSAndQuote = function (s) {
    s = s.replace(/\n/g, "\\n");
    s = s.replace(/\r/g, "\\r");
    s = s.replace(/\t/g, "\\t");
    return "'" + s + "'";
};

// Compute the error recovery set for the current rule. During
// rule invocation, the parser pushes the set of tokens that can
// follow that rule reference on the stack; this amounts to
// computing FIRST of what follows the rule reference in the
// enclosing rule. See LinearApproximator.FIRST().
// This local follow set only includes tokens
// from within the rule; i.e., the FIRST computation done by
// ANTLR stops at the end of a rule.
//
// EXAMPLE
//
// When you find a "no viable alt exception", the input is not
// consistent with any of the alternatives for rule r. The best
// thing to do is to consume tokens until you see something that
// can legally follow a call to r//or* any rule that called r.
// You don't want the exact set of viable next tokens because the
// input might just be missing a token--you might consume the
// rest of the input looking for one of the missing tokens.
//
// Consider grammar:
//
// a : '[' b ']'
// | '(' b ')'
// ;
// b : c '^' INT ;
// c : ID
// | INT
// ;
//
// At each rule invocation, the set of tokens that could follow
// that rule is pushed on a stack. Here are the various
// context-sensitive follow sets:
//
// FOLLOW(b1_in_a) = FIRST(']') = ']'
// FOLLOW(b2_in_a) = FIRST(')') = ')'
// FOLLOW(c_in_b) = FIRST('^') = '^'
//
// Upon erroneous input "[]", the call chain is
//
// a -> b -> c
//
// and, hence, the follow context stack is:
//
// depth follow set start of rule execution
// 0 <EOF> a (from main())
// 1 ']' b
// 2 '^' c
//
// Notice that ')' is not included, because b would have to have
// been called from a different context in rule a for ')' to be
// included.
//
// For error recovery, we cannot consider FOLLOW(c)
// (context-sensitive or otherwise). We need the combined set of
// all context-sensitive FOLLOW sets--the set of all tokens that
// could follow any reference in the call chain. We need to
// resync to one of those tokens. Note that FOLLOW(c)='^' and if
// we resync'd to that token, we'd consume until EOF. We need to
// sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.
// In this case, for input "[]", LA(1) is ']' and in the set, so we would
// not consume anything. After printing an error, rule c would
// return normally. Rule b would not find the required '^' though.
// At this point, it gets a mismatched token error and throws an
// exception (since LA(1) is not in the viable following token
// set). The rule exception handler tries to recover, but finds
// the same recovery set and doesn't consume anything. Rule b
// exits normally returning to rule a. Now it finds the ']' (and
// with the successful match exits errorRecovery mode).
//
// So, you can see that the parser walks up the call chain looking
// for the token that was a member of the recovery set.
//
// Errors are not generated in errorRecovery mode.
//
// ANTLR's error recovery mechanism is based upon original ideas:
//
// "Algorithms + Data Structures = Programs" by Niklaus Wirth
//
// and
//
// "A note on error recovery in recursive descent parsers":
// http://portal.acm.org/citation.cfm?id=947902.947905
//
// Later, Josef Grosch had some good ideas:
//
// "Efficient and Comfortable Error Recovery in Recursive Descent
// Parsers":
// ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip
//
// Like Grosch I implement context-sensitive FOLLOW sets that are combined
// at run-time upon error to avoid overhead during parsing.
//
DefaultErrorStrategy.prototype.getErrorRecoverySet = function (recognizer) {
    var atn = recognizer._interp.atn;
    var ctx = recognizer._ctx;
    var recoverSet = new IntervalSet();
    while (ctx !== null && ctx.invokingState >= 0) {
        // compute what follows who invoked us
        var invokingState = atn.states[ctx.invokingState];
        var rt = invokingState.transitions[0];
        var follow = atn.nextTokens(rt.followState);
        recoverSet.addSet(follow);
        ctx = ctx.parentCtx;
    }
    recoverSet.removeOne(Token.EPSILON);
    return recoverSet;
};

// Consume tokens until one matches the given token set.//
DefaultErrorStrategy.prototype.consumeUntil = function (recognizer, set) {
    var ttype = recognizer.getTokenStream().LA(1);
    while (ttype !== Token.EOF && !set.contains(ttype)) {
        recognizer.consume();
        ttype = recognizer.getTokenStream().LA(1);
    }
};

//
// This implementation of {@link ANTLRErrorStrategy} responds to syntax errors
// by immediately canceling the parse operation with a
// {@link ParseCancellationException}. The implementation ensures that the
// {@link ParserRuleContext//exception} field is set for all parse tree nodes
// that were not completed prior to encountering the error.
//
// <p>
// This error strategy is useful in the following scenarios.</p>
//
// <ul>
// <li><strong>Two-stage parsing:</strong> This error strategy allows the first
// stage of two-stage parsing to immediately terminate if an error is
// encountered, and immediately fall back to the second stage. In addition to
// avoiding wasted work by attempting to recover from errors here, the empty
// implementation of {@link BailErrorStrategy//sync} improves the performance of
// the first stage.</li>
// <li><strong>Silent validation:</strong> When syntax errors are not being
// reported or logged, and the parse result is simply ignored if errors occur,
// the {@link BailErrorStrategy} avoids wasting work on recovering from errors
// when the result will be ignored either way.</li>
// </ul>
//
// <p>
// {@code myparser.setErrorHandler(new BailErrorStrategy());}</p>
//
// @see Parser//setErrorHandler(ANTLRErrorStrategy)
//
function BailErrorStrategy() {
    DefaultErrorStrategy.call(this);
    return this;
}

BailErrorStrategy.prototype = Object.create(DefaultErrorStrategy.prototype);
BailErrorStrategy.prototype.constructor = BailErrorStrategy;

// Instead of recovering from exception {@code e}, re-throw it wrapped
// in a {@link ParseCancellationException} so it is not caught by the
// rule function catches. Use {@link Exception//getCause()} to get the
// original {@link RecognitionException}.
//
BailErrorStrategy.prototype.recover = function (recognizer, e) {
    var context = recognizer._ctx;
    while (context !== null) {
        context.exception = e;
        context = context.parentCtx;
    }
    throw new ParseCancellationException(e);
};

// Make sure we don't attempt to recover inline; if the parser
// successfully recovers, it won't throw an exception.
//
BailErrorStrategy.prototype.recoverInline = function (recognizer) {
    this.recover(recognizer, new InputMismatchException(recognizer));
};

// Make sure we don't attempt to recover from problems in subrules.//
BailErrorStrategy.prototype.sync = function (recognizer) {
    // pass
};

exports.BailErrorStrategy = BailErrorStrategy;
exports.DefaultErrorStrategy = DefaultErrorStrategy;

/***/ }),

/***/ "./node_modules/antlr4/error/Errors.js":
/*!*********************************************!*\
  !*** ./node_modules/antlr4/error/Errors.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

// The root of the ANTLR exception hierarchy. In general, ANTLR tracks just
//  3 kinds of errors: prediction errors, failed predicate errors, and
//  mismatched input errors. In each case, the parser knows where it is
//  in the input, where it is in the ATN, the rule invocation stack,
//  and what kind of problem occurred.

var PredicateTransition = __webpack_require__(/*! ./../atn/Transition */ "./node_modules/antlr4/atn/Transition.js").PredicateTransition;

function RecognitionException(params) {
    Error.call(this);
    if (!!Error.captureStackTrace) {
        Error.captureStackTrace(this, RecognitionException);
    } else {
        var stack = new Error().stack;
    }
    this.message = params.message;
    this.recognizer = params.recognizer;
    this.input = params.input;
    this.ctx = params.ctx;
    // The current {@link Token} when an error occurred. Since not all streams
    // support accessing symbols by index, we have to track the {@link Token}
    // instance itself.
    this.offendingToken = null;
    // Get the ATN state number the parser was in at the time the error
    // occurred. For {@link NoViableAltException} and
    // {@link LexerNoViableAltException} exceptions, this is the
    // {@link DecisionState} number. For others, it is the state whose outgoing
    // edge we couldn't match.
    this.offendingState = -1;
    if (this.recognizer !== null) {
        this.offendingState = this.recognizer.state;
    }
    return this;
}

RecognitionException.prototype = Object.create(Error.prototype);
RecognitionException.prototype.constructor = RecognitionException;

// <p>If the state number is not known, this method returns -1.</p>

//
// Gets the set of input symbols which could potentially follow the
// previously matched symbol at the time this exception was thrown.
//
// <p>If the set of expected tokens is not known and could not be computed,
// this method returns {@code null}.</p>
//
// @return The set of token types that could potentially follow the current
// state in the ATN, or {@code null} if the information is not available.
// /
RecognitionException.prototype.getExpectedTokens = function () {
    if (this.recognizer !== null) {
        return this.recognizer.atn.getExpectedTokens(this.offendingState, this.ctx);
    } else {
        return null;
    }
};

RecognitionException.prototype.toString = function () {
    return this.message;
};

function LexerNoViableAltException(lexer, input, startIndex, deadEndConfigs) {
    RecognitionException.call(this, { message: "", recognizer: lexer, input: input, ctx: null });
    this.startIndex = startIndex;
    this.deadEndConfigs = deadEndConfigs;
    return this;
}

LexerNoViableAltException.prototype = Object.create(RecognitionException.prototype);
LexerNoViableAltException.prototype.constructor = LexerNoViableAltException;

LexerNoViableAltException.prototype.toString = function () {
    var symbol = "";
    if (this.startIndex >= 0 && this.startIndex < this.input.size) {
        symbol = this.input.getText((this.startIndex, this.startIndex));
    }
    return "LexerNoViableAltException" + symbol;
};

// Indicates that the parser could not decide which of two or more paths
// to take based upon the remaining input. It tracks the starting token
// of the offending input and also knows where the parser was
// in the various paths when the error. Reported by reportNoViableAlternative()
//
function NoViableAltException(recognizer, input, startToken, offendingToken, deadEndConfigs, ctx) {
    ctx = ctx || recognizer._ctx;
    offendingToken = offendingToken || recognizer.getCurrentToken();
    startToken = startToken || recognizer.getCurrentToken();
    input = input || recognizer.getInputStream();
    RecognitionException.call(this, { message: "", recognizer: recognizer, input: input, ctx: ctx });
    // Which configurations did we try at input.index() that couldn't match
    // input.LT(1)?//
    this.deadEndConfigs = deadEndConfigs;
    // The token object at the start index; the input stream might
    // not be buffering tokens so get a reference to it. (At the
    // time the error occurred, of course the stream needs to keep a
    // buffer all of the tokens but later we might not have access to those.)
    this.startToken = startToken;
    this.offendingToken = offendingToken;
}

NoViableAltException.prototype = Object.create(RecognitionException.prototype);
NoViableAltException.prototype.constructor = NoViableAltException;

// This signifies any kind of mismatched input exceptions such as
// when the current input does not match the expected token.
//
function InputMismatchException(recognizer) {
    RecognitionException.call(this, { message: "", recognizer: recognizer, input: recognizer.getInputStream(), ctx: recognizer._ctx });
    this.offendingToken = recognizer.getCurrentToken();
}

InputMismatchException.prototype = Object.create(RecognitionException.prototype);
InputMismatchException.prototype.constructor = InputMismatchException;

// A semantic predicate failed during validation. Validation of predicates
// occurs when normally parsing the alternative just like matching a token.
// Disambiguating predicate evaluation occurs when we test a predicate during
// prediction.

function FailedPredicateException(recognizer, predicate, message) {
    RecognitionException.call(this, { message: this.formatMessage(predicate, message || null), recognizer: recognizer,
        input: recognizer.getInputStream(), ctx: recognizer._ctx });
    var s = recognizer._interp.atn.states[recognizer.state];
    var trans = s.transitions[0];
    if (trans instanceof PredicateTransition) {
        this.ruleIndex = trans.ruleIndex;
        this.predicateIndex = trans.predIndex;
    } else {
        this.ruleIndex = 0;
        this.predicateIndex = 0;
    }
    this.predicate = predicate;
    this.offendingToken = recognizer.getCurrentToken();
    return this;
}

FailedPredicateException.prototype = Object.create(RecognitionException.prototype);
FailedPredicateException.prototype.constructor = FailedPredicateException;

FailedPredicateException.prototype.formatMessage = function (predicate, message) {
    if (message !== null) {
        return message;
    } else {
        return "failed predicate: {" + predicate + "}?";
    }
};

function ParseCancellationException() {
    Error.call(this);
    Error.captureStackTrace(this, ParseCancellationException);
    return this;
}

ParseCancellationException.prototype = Object.create(Error.prototype);
ParseCancellationException.prototype.constructor = ParseCancellationException;

exports.RecognitionException = RecognitionException;
exports.NoViableAltException = NoViableAltException;
exports.LexerNoViableAltException = LexerNoViableAltException;
exports.InputMismatchException = InputMismatchException;
exports.FailedPredicateException = FailedPredicateException;
exports.ParseCancellationException = ParseCancellationException;

/***/ }),

/***/ "./node_modules/antlr4/error/index.js":
/*!********************************************!*\
  !*** ./node_modules/antlr4/error/index.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

exports.RecognitionException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").RecognitionException;
exports.NoViableAltException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").NoViableAltException;
exports.LexerNoViableAltException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").LexerNoViableAltException;
exports.InputMismatchException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").InputMismatchException;
exports.FailedPredicateException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").FailedPredicateException;
exports.DiagnosticErrorListener = __webpack_require__(/*! ./DiagnosticErrorListener */ "./node_modules/antlr4/error/DiagnosticErrorListener.js").DiagnosticErrorListener;
exports.BailErrorStrategy = __webpack_require__(/*! ./ErrorStrategy */ "./node_modules/antlr4/error/ErrorStrategy.js").BailErrorStrategy;
exports.ErrorListener = __webpack_require__(/*! ./ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ErrorListener;

/***/ }),

/***/ "./node_modules/antlr4/index.js":
/*!**************************************!*\
  !*** ./node_modules/antlr4/index.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
exports.atn = __webpack_require__(/*! ./atn/index */ "./node_modules/antlr4/atn/index.js");
exports.codepointat = __webpack_require__(/*! ./polyfills/codepointat */ "./node_modules/antlr4/polyfills/codepointat.js");
exports.dfa = __webpack_require__(/*! ./dfa/index */ "./node_modules/antlr4/dfa/index.js");
exports.fromcodepoint = __webpack_require__(/*! ./polyfills/fromcodepoint */ "./node_modules/antlr4/polyfills/fromcodepoint.js");
exports.tree = __webpack_require__(/*! ./tree/index */ "./node_modules/antlr4/tree/index.js");
exports.error = __webpack_require__(/*! ./error/index */ "./node_modules/antlr4/error/index.js");
exports.Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
exports.CharStreams = __webpack_require__(/*! ./CharStreams */ "./node_modules/antlr4/CharStreams.js").CharStreams;
exports.CommonToken = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").CommonToken;
exports.InputStream = __webpack_require__(/*! ./InputStream */ "./node_modules/antlr4/InputStream.js").InputStream;
exports.FileStream = __webpack_require__(/*! ./FileStream */ "./node_modules/antlr4/FileStream.js").FileStream;
exports.CommonTokenStream = __webpack_require__(/*! ./CommonTokenStream */ "./node_modules/antlr4/CommonTokenStream.js").CommonTokenStream;
exports.Lexer = __webpack_require__(/*! ./Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
exports.Parser = __webpack_require__(/*! ./Parser */ "./node_modules/antlr4/Parser.js").Parser;
var pc = __webpack_require__(/*! ./PredictionContext */ "./node_modules/antlr4/PredictionContext.js");
exports.PredictionContextCache = pc.PredictionContextCache;
exports.ParserRuleContext = __webpack_require__(/*! ./ParserRuleContext */ "./node_modules/antlr4/ParserRuleContext.js").ParserRuleContext;
exports.Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
exports.Utils = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js");

/***/ }),

/***/ "./node_modules/antlr4/polyfills/codepointat.js":
/*!******************************************************!*\
  !*** ./node_modules/antlr4/polyfills/codepointat.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/*! https://mths.be/codepointat v0.2.0 by @mathias */
if (!String.prototype.codePointAt) {
	(function () {
		'use strict'; // needed to support `apply`/`call` with `undefined`/`null`

		var defineProperty = function () {
			// IE 8 only supports `Object.defineProperty` on DOM elements
			try {
				var object = {};
				var $defineProperty = Object.defineProperty;
				var result = $defineProperty(object, object, object) && $defineProperty;
			} catch (error) {}
			return result;
		}();
		var codePointAt = function codePointAt(position) {
			if (this == null) {
				throw TypeError();
			}
			var string = String(this);
			var size = string.length;
			// `ToInteger`
			var index = position ? Number(position) : 0;
			if (index != index) {
				// better `isNaN`
				index = 0;
			}
			// Account for out-of-bounds indices:
			if (index < 0 || index >= size) {
				return undefined;
			}
			// Get the first code unit
			var first = string.charCodeAt(index);
			var second;
			if ( // check if it’s the start of a surrogate pair
			first >= 0xD800 && first <= 0xDBFF && // high surrogate
			size > index + 1 // there is a next code unit
			) {
					second = string.charCodeAt(index + 1);
					if (second >= 0xDC00 && second <= 0xDFFF) {
						// low surrogate
						// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
						return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
					}
				}
			return first;
		};
		if (defineProperty) {
			defineProperty(String.prototype, 'codePointAt', {
				'value': codePointAt,
				'configurable': true,
				'writable': true
			});
		} else {
			String.prototype.codePointAt = codePointAt;
		}
	})();
}

/***/ }),

/***/ "./node_modules/antlr4/polyfills/fromcodepoint.js":
/*!********************************************************!*\
  !*** ./node_modules/antlr4/polyfills/fromcodepoint.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/*! https://mths.be/fromcodepoint v0.2.1 by @mathias */
if (!String.fromCodePoint) {
	(function () {
		var defineProperty = function () {
			// IE 8 only supports `Object.defineProperty` on DOM elements
			try {
				var object = {};
				var $defineProperty = Object.defineProperty;
				var result = $defineProperty(object, object, object) && $defineProperty;
			} catch (error) {}
			return result;
		}();
		var stringFromCharCode = String.fromCharCode;
		var floor = Math.floor;
		var fromCodePoint = function fromCodePoint(_) {
			var MAX_SIZE = 0x4000;
			var codeUnits = [];
			var highSurrogate;
			var lowSurrogate;
			var index = -1;
			var length = arguments.length;
			if (!length) {
				return '';
			}
			var result = '';
			while (++index < length) {
				var codePoint = Number(arguments[index]);
				if (!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
				codePoint < 0 || // not a valid Unicode code point
				codePoint > 0x10FFFF || // not a valid Unicode code point
				floor(codePoint) != codePoint // not an integer
				) {
						throw RangeError('Invalid code point: ' + codePoint);
					}
				if (codePoint <= 0xFFFF) {
					// BMP code point
					codeUnits.push(codePoint);
				} else {
					// Astral code point; split in surrogate halves
					// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
					codePoint -= 0x10000;
					highSurrogate = (codePoint >> 10) + 0xD800;
					lowSurrogate = codePoint % 0x400 + 0xDC00;
					codeUnits.push(highSurrogate, lowSurrogate);
				}
				if (index + 1 == length || codeUnits.length > MAX_SIZE) {
					result += stringFromCharCode.apply(null, codeUnits);
					codeUnits.length = 0;
				}
			}
			return result;
		};
		if (defineProperty) {
			defineProperty(String, 'fromCodePoint', {
				'value': fromCodePoint,
				'configurable': true,
				'writable': true
			});
		} else {
			String.fromCodePoint = fromCodePoint;
		}
	})();
}

/***/ }),

/***/ "./node_modules/antlr4/tree/Tree.js":
/*!******************************************!*\
  !*** ./node_modules/antlr4/tree/Tree.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */
///

// The basic notion of a tree has a parent, a payload, and a list of children.
//  It is the most abstract interface for all the trees used by ANTLR.
///

var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
var INVALID_INTERVAL = new Interval(-1, -2);
var Utils = __webpack_require__(/*! ../Utils.js */ "./node_modules/antlr4/Utils.js");

function Tree() {
	return this;
}

function SyntaxTree() {
	Tree.call(this);
	return this;
}

SyntaxTree.prototype = Object.create(Tree.prototype);
SyntaxTree.prototype.constructor = SyntaxTree;

function ParseTree() {
	SyntaxTree.call(this);
	return this;
}

ParseTree.prototype = Object.create(SyntaxTree.prototype);
ParseTree.prototype.constructor = ParseTree;

function RuleNode() {
	ParseTree.call(this);
	return this;
}

RuleNode.prototype = Object.create(ParseTree.prototype);
RuleNode.prototype.constructor = RuleNode;

function TerminalNode() {
	ParseTree.call(this);
	return this;
}

TerminalNode.prototype = Object.create(ParseTree.prototype);
TerminalNode.prototype.constructor = TerminalNode;

function ErrorNode() {
	TerminalNode.call(this);
	return this;
}

ErrorNode.prototype = Object.create(TerminalNode.prototype);
ErrorNode.prototype.constructor = ErrorNode;

function ParseTreeVisitor() {
	return this;
}

ParseTreeVisitor.prototype.visit = function (ctx) {
	if (Array.isArray(ctx)) {
		return ctx.map(function (child) {
			return child.accept(this);
		}, this);
	} else {
		return ctx.accept(this);
	}
};

ParseTreeVisitor.prototype.visitChildren = function (ctx) {
	return this.visit(ctx.children);
};

ParseTreeVisitor.prototype.visitTerminal = function (node) {};

ParseTreeVisitor.prototype.visitErrorNode = function (node) {};

function ParseTreeListener() {
	return this;
}

ParseTreeListener.prototype.visitTerminal = function (node) {};

ParseTreeListener.prototype.visitErrorNode = function (node) {};

ParseTreeListener.prototype.enterEveryRule = function (node) {};

ParseTreeListener.prototype.exitEveryRule = function (node) {};

function TerminalNodeImpl(symbol) {
	TerminalNode.call(this);
	this.parentCtx = null;
	this.symbol = symbol;
	return this;
}

TerminalNodeImpl.prototype = Object.create(TerminalNode.prototype);
TerminalNodeImpl.prototype.constructor = TerminalNodeImpl;

TerminalNodeImpl.prototype.getChild = function (i) {
	return null;
};

TerminalNodeImpl.prototype.getSymbol = function () {
	return this.symbol;
};

TerminalNodeImpl.prototype.getParent = function () {
	return this.parentCtx;
};

TerminalNodeImpl.prototype.getPayload = function () {
	return this.symbol;
};

TerminalNodeImpl.prototype.getSourceInterval = function () {
	if (this.symbol === null) {
		return INVALID_INTERVAL;
	}
	var tokenIndex = this.symbol.tokenIndex;
	return new Interval(tokenIndex, tokenIndex);
};

TerminalNodeImpl.prototype.getChildCount = function () {
	return 0;
};

TerminalNodeImpl.prototype.accept = function (visitor) {
	return visitor.visitTerminal(this);
};

TerminalNodeImpl.prototype.getText = function () {
	return this.symbol.text;
};

TerminalNodeImpl.prototype.toString = function () {
	if (this.symbol.type === Token.EOF) {
		return "<EOF>";
	} else {
		return this.symbol.text;
	}
};

// Represents a token that was consumed during resynchronization
// rather than during a valid match operation. For example,
// we will create this kind of a node during single token insertion
// and deletion as well as during "consume until error recovery set"
// upon no viable alternative exceptions.

function ErrorNodeImpl(token) {
	TerminalNodeImpl.call(this, token);
	return this;
}

ErrorNodeImpl.prototype = Object.create(TerminalNodeImpl.prototype);
ErrorNodeImpl.prototype.constructor = ErrorNodeImpl;

ErrorNodeImpl.prototype.isErrorNode = function () {
	return true;
};

ErrorNodeImpl.prototype.accept = function (visitor) {
	return visitor.visitErrorNode(this);
};

function ParseTreeWalker() {
	return this;
}

ParseTreeWalker.prototype.walk = function (listener, t) {
	var errorNode = t instanceof ErrorNode || t.isErrorNode !== undefined && t.isErrorNode();
	if (errorNode) {
		listener.visitErrorNode(t);
	} else if (t instanceof TerminalNode) {
		listener.visitTerminal(t);
	} else {
		this.enterRule(listener, t);
		for (var i = 0; i < t.getChildCount(); i++) {
			var child = t.getChild(i);
			this.walk(listener, child);
		}
		this.exitRule(listener, t);
	}
};
//
// The discovery of a rule node, involves sending two events: the generic
// {@link ParseTreeListener//enterEveryRule} and a
// {@link RuleContext}-specific event. First we trigger the generic and then
// the rule specific. We to them in reverse order upon finishing the node.
//
ParseTreeWalker.prototype.enterRule = function (listener, r) {
	var ctx = r.getRuleContext();
	listener.enterEveryRule(ctx);
	ctx.enterRule(listener);
};

ParseTreeWalker.prototype.exitRule = function (listener, r) {
	var ctx = r.getRuleContext();
	ctx.exitRule(listener);
	listener.exitEveryRule(ctx);
};

ParseTreeWalker.DEFAULT = new ParseTreeWalker();

exports.RuleNode = RuleNode;
exports.ErrorNode = ErrorNode;
exports.TerminalNode = TerminalNode;
exports.ErrorNodeImpl = ErrorNodeImpl;
exports.TerminalNodeImpl = TerminalNodeImpl;
exports.ParseTreeListener = ParseTreeListener;
exports.ParseTreeVisitor = ParseTreeVisitor;
exports.ParseTreeWalker = ParseTreeWalker;
exports.INVALID_INTERVAL = INVALID_INTERVAL;

/***/ }),

/***/ "./node_modules/antlr4/tree/Trees.js":
/*!*******************************************!*\
  !*** ./node_modules/antlr4/tree/Trees.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
var RuleNode = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js").RuleNode;
var ErrorNode = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js").ErrorNode;
var TerminalNode = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js").TerminalNode;
var ParserRuleContext = __webpack_require__(/*! ./../ParserRuleContext */ "./node_modules/antlr4/ParserRuleContext.js").ParserRuleContext;
var RuleContext = __webpack_require__(/*! ./../RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
var INVALID_ALT_NUMBER = __webpack_require__(/*! ./../atn/ATN */ "./node_modules/antlr4/atn/ATN.js").INVALID_ALT_NUMBER;

/** A set of utility routines useful for all kinds of ANTLR trees. */
function Trees() {}

// Print out a whole tree in LISP form. {@link //getNodeText} is used on the
//  node payloads to get the text for the nodes.  Detect
//  parse trees and extract data appropriately.
Trees.toStringTree = function (tree, ruleNames, recog) {
    ruleNames = ruleNames || null;
    recog = recog || null;
    if (recog !== null) {
        ruleNames = recog.ruleNames;
    }
    var s = Trees.getNodeText(tree, ruleNames);
    s = Utils.escapeWhitespace(s, false);
    var c = tree.getChildCount();
    if (c === 0) {
        return s;
    }
    var res = "(" + s + ' ';
    if (c > 0) {
        s = Trees.toStringTree(tree.getChild(0), ruleNames);
        res = res.concat(s);
    }
    for (var i = 1; i < c; i++) {
        s = Trees.toStringTree(tree.getChild(i), ruleNames);
        res = res.concat(' ' + s);
    }
    res = res.concat(")");
    return res;
};

Trees.getNodeText = function (t, ruleNames, recog) {
    ruleNames = ruleNames || null;
    recog = recog || null;
    if (recog !== null) {
        ruleNames = recog.ruleNames;
    }
    if (ruleNames !== null) {
        if (t instanceof RuleContext) {
            var altNumber = t.getAltNumber();
            if (altNumber != INVALID_ALT_NUMBER) {
                return ruleNames[t.ruleIndex] + ":" + altNumber;
            }
            return ruleNames[t.ruleIndex];
        } else if (t instanceof ErrorNode) {
            return t.toString();
        } else if (t instanceof TerminalNode) {
            if (t.symbol !== null) {
                return t.symbol.text;
            }
        }
    }
    // no recog for rule names
    var payload = t.getPayload();
    if (payload instanceof Token) {
        return payload.text;
    }
    return t.getPayload().toString();
};

// Return ordered list of all children of this node
Trees.getChildren = function (t) {
    var list = [];
    for (var i = 0; i < t.getChildCount(); i++) {
        list.push(t.getChild(i));
    }
    return list;
};

// Return a list of all ancestors of this node.  The first node of
//  list is the root and the last is the parent of this node.
//
Trees.getAncestors = function (t) {
    var ancestors = [];
    t = t.getParent();
    while (t !== null) {
        ancestors = [t].concat(ancestors);
        t = t.getParent();
    }
    return ancestors;
};

Trees.findAllTokenNodes = function (t, ttype) {
    return Trees.findAllNodes(t, ttype, true);
};

Trees.findAllRuleNodes = function (t, ruleIndex) {
    return Trees.findAllNodes(t, ruleIndex, false);
};

Trees.findAllNodes = function (t, index, findTokens) {
    var nodes = [];
    Trees._findAllNodes(t, index, findTokens, nodes);
    return nodes;
};

Trees._findAllNodes = function (t, index, findTokens, nodes) {
    // check this node (the root) first
    if (findTokens && t instanceof TerminalNode) {
        if (t.symbol.type === index) {
            nodes.push(t);
        }
    } else if (!findTokens && t instanceof ParserRuleContext) {
        if (t.ruleIndex === index) {
            nodes.push(t);
        }
    }
    // check children
    for (var i = 0; i < t.getChildCount(); i++) {
        Trees._findAllNodes(t.getChild(i), index, findTokens, nodes);
    }
};

Trees.descendants = function (t) {
    var nodes = [t];
    for (var i = 0; i < t.getChildCount(); i++) {
        nodes = nodes.concat(Trees.descendants(t.getChild(i)));
    }
    return nodes;
};

exports.Trees = Trees;

/***/ }),

/***/ "./node_modules/antlr4/tree/index.js":
/*!*******************************************!*\
  !*** ./node_modules/antlr4/tree/index.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

var Tree = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js");
exports.Trees = __webpack_require__(/*! ./Trees */ "./node_modules/antlr4/tree/Trees.js").Trees;
exports.RuleNode = Tree.RuleNode;
exports.ParseTreeListener = Tree.ParseTreeListener;
exports.ParseTreeVisitor = Tree.ParseTreeVisitor;
exports.ParseTreeWalker = Tree.ParseTreeWalker;

/***/ }),

/***/ "./node_modules/decimal.js/decimal.js":
/*!********************************************!*\
  !*** ./node_modules/decimal.js/decimal.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
var __WEBPACK_AMD_DEFINE_RESULT__;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/*! decimal.js v10.0.1 https://github.com/MikeMcl/decimal.js/LICENCE */
;(function (globalScope) {
  'use strict';

  /*
   *  decimal.js v10.0.1
   *  An arbitrary-precision Decimal type for JavaScript.
   *  https://github.com/MikeMcl/decimal.js
   *  Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
   *  MIT Licence
   */

  // -----------------------------------  EDITABLE DEFAULTS  ------------------------------------ //


  // The maximum exponent magnitude.
  // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.

  var EXP_LIMIT = 9e15,
      // 0 to 9e15

  // The limit on the value of `precision`, and on the value of the first argument to
  // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
  MAX_DIGITS = 1e9,
      // 0 to 1e9

  // Base conversion alphabet.
  NUMERALS = '0123456789abcdef',


  // The natural logarithm of 10 (1025 digits).
  LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',


  // Pi (1025 digits).
  PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',


  // The initial configuration properties of the Decimal constructor.
  DEFAULTS = {

    // These values must be integers within the stated ranges (inclusive).
    // Most of these values can be changed at run-time using the `Decimal.config` method.

    // The maximum number of significant digits of the result of a calculation or base conversion.
    // E.g. `Decimal.config({ precision: 20 });`
    precision: 20, // 1 to MAX_DIGITS

    // The rounding mode used when rounding to `precision`.
    //
    // ROUND_UP         0 Away from zero.
    // ROUND_DOWN       1 Towards zero.
    // ROUND_CEIL       2 Towards +Infinity.
    // ROUND_FLOOR      3 Towards -Infinity.
    // ROUND_HALF_UP    4 Towards nearest neighbour. If equidistant, up.
    // ROUND_HALF_DOWN  5 Towards nearest neighbour. If equidistant, down.
    // ROUND_HALF_EVEN  6 Towards nearest neighbour. If equidistant, towards even neighbour.
    // ROUND_HALF_CEIL  7 Towards nearest neighbour. If equidistant, towards +Infinity.
    // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
    //
    // E.g.
    // `Decimal.rounding = 4;`
    // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
    rounding: 4, // 0 to 8

    // The modulo mode used when calculating the modulus: a mod n.
    // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
    // The remainder (r) is calculated as: r = a - n * q.
    //
    // UP         0 The remainder is positive if the dividend is negative, else is negative.
    // DOWN       1 The remainder has the same sign as the dividend (JavaScript %).
    // FLOOR      3 The remainder has the same sign as the divisor (Python %).
    // HALF_EVEN  6 The IEEE 754 remainder function.
    // EUCLID     9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
    //
    // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
    // division (9) are commonly used for the modulus operation. The other rounding modes can also
    // be used, but they may not give useful results.
    modulo: 1, // 0 to 9

    // The exponent value at and beneath which `toString` returns exponential notation.
    // JavaScript numbers: -7
    toExpNeg: -7, // 0 to -EXP_LIMIT

    // The exponent value at and above which `toString` returns exponential notation.
    // JavaScript numbers: 21
    toExpPos: 21, // 0 to EXP_LIMIT

    // The minimum exponent value, beneath which underflow to zero occurs.
    // JavaScript numbers: -324  (5e-324)
    minE: -EXP_LIMIT, // -1 to -EXP_LIMIT

    // The maximum exponent value, above which overflow to Infinity occurs.
    // JavaScript numbers: 308  (1.7976931348623157e+308)
    maxE: EXP_LIMIT, // 1 to EXP_LIMIT

    // Whether to use cryptographically-secure random number generation, if available.
    crypto: false // true/false
  },


  // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //


  Decimal,
      inexact,
      noConflict,
      quadrant,
      external = true,
      decimalError = '[DecimalError] ',
      invalidArgument = decimalError + 'Invalid argument: ',
      precisionLimitExceeded = decimalError + 'Precision limit exceeded',
      cryptoUnavailable = decimalError + 'crypto unavailable',
      mathfloor = Math.floor,
      mathpow = Math.pow,
      isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
      isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
      isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
      isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
      BASE = 1e7,
      LOG_BASE = 7,
      MAX_SAFE_INTEGER = 9007199254740991,
      LN10_PRECISION = LN10.length - 1,
      PI_PRECISION = PI.length - 1,


  // Decimal.prototype object
  P = { name: '[object Decimal]' };

  // Decimal prototype methods


  /*
   *  absoluteValue             abs
   *  ceil
   *  comparedTo                cmp
   *  cosine                    cos
   *  cubeRoot                  cbrt
   *  decimalPlaces             dp
   *  dividedBy                 div
   *  dividedToIntegerBy        divToInt
   *  equals                    eq
   *  floor
   *  greaterThan               gt
   *  greaterThanOrEqualTo      gte
   *  hyperbolicCosine          cosh
   *  hyperbolicSine            sinh
   *  hyperbolicTangent         tanh
   *  inverseCosine             acos
   *  inverseHyperbolicCosine   acosh
   *  inverseHyperbolicSine     asinh
   *  inverseHyperbolicTangent  atanh
   *  inverseSine               asin
   *  inverseTangent            atan
   *  isFinite
   *  isInteger                 isInt
   *  isNaN
   *  isNegative                isNeg
   *  isPositive                isPos
   *  isZero
   *  lessThan                  lt
   *  lessThanOrEqualTo         lte
   *  logarithm                 log
   *  [maximum]                 [max]
   *  [minimum]                 [min]
   *  minus                     sub
   *  modulo                    mod
   *  naturalExponential        exp
   *  naturalLogarithm          ln
   *  negated                   neg
   *  plus                      add
   *  precision                 sd
   *  round
   *  sine                      sin
   *  squareRoot                sqrt
   *  tangent                   tan
   *  times                     mul
   *  toBinary
   *  toDecimalPlaces           toDP
   *  toExponential
   *  toFixed
   *  toFraction
   *  toHexadecimal             toHex
   *  toNearest
   *  toNumber
   *  toOctal
   *  toPower                   pow
   *  toPrecision
   *  toSignificantDigits       toSD
   *  toString
   *  truncated                 trunc
   *  valueOf                   toJSON
   */

  /*
   * Return a new Decimal whose value is the absolute value of this Decimal.
   *
   */
  P.absoluteValue = P.abs = function () {
    var x = new this.constructor(this);
    if (x.s < 0) x.s = 1;
    return finalise(x);
  };

  /*
   * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
   * direction of positive Infinity.
   *
   */
  P.ceil = function () {
    return finalise(new this.constructor(this), this.e + 1, 2);
  };

  /*
   * Return
   *   1    if the value of this Decimal is greater than the value of `y`,
   *  -1    if the value of this Decimal is less than the value of `y`,
   *   0    if they have the same value,
   *   NaN  if the value of either Decimal is NaN.
   *
   */
  P.comparedTo = P.cmp = function (y) {
    var i,
        j,
        xdL,
        ydL,
        x = this,
        xd = x.d,
        yd = (y = new x.constructor(y)).d,
        xs = x.s,
        ys = y.s;

    // Either NaN or ±Infinity?
    if (!xd || !yd) {
      return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
    }

    // Either zero?
    if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;

    // Signs differ?
    if (xs !== ys) return xs;

    // Compare exponents.
    if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;

    xdL = xd.length;
    ydL = yd.length;

    // Compare digit by digit.
    for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
      if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
    }

    // Compare lengths.
    return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
  };

  /*
   * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
   *
   * Domain: [-Infinity, Infinity]
   * Range: [-1, 1]
   *
   * cos(0)         = 1
   * cos(-0)        = 1
   * cos(Infinity)  = NaN
   * cos(-Infinity) = NaN
   * cos(NaN)       = NaN
   *
   */
  P.cosine = P.cos = function () {
    var pr,
        rm,
        x = this,
        Ctor = x.constructor;

    if (!x.d) return new Ctor(NaN);

    // cos(0) = cos(-0) = 1
    if (!x.d[0]) return new Ctor(1);

    pr = Ctor.precision;
    rm = Ctor.rounding;
    Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
    Ctor.rounding = 1;

    x = cosine(Ctor, toLessThanHalfPi(Ctor, x));

    Ctor.precision = pr;
    Ctor.rounding = rm;

    return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
  };

  /*
   *
   * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
   * `precision` significant digits using rounding mode `rounding`.
   *
   *  cbrt(0)  =  0
   *  cbrt(-0) = -0
   *  cbrt(1)  =  1
   *  cbrt(-1) = -1
   *  cbrt(N)  =  N
   *  cbrt(-I) = -I
   *  cbrt(I)  =  I
   *
   * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
   *
   */
  P.cubeRoot = P.cbrt = function () {
    var e,
        m,
        n,
        r,
        rep,
        s,
        sd,
        t,
        t3,
        t3plusx,
        x = this,
        Ctor = x.constructor;

    if (!x.isFinite() || x.isZero()) return new Ctor(x);
    external = false;

    // Initial estimate.
    s = x.s * Math.pow(x.s * x, 1 / 3);

    // Math.cbrt underflow/overflow?
    // Pass x to Math.pow as integer, then adjust the exponent of the result.
    if (!s || Math.abs(s) == 1 / 0) {
      n = digitsToString(x.d);
      e = x.e;

      // Adjust n exponent so it is a multiple of 3 away from x exponent.
      if (s = (e - n.length + 1) % 3) n += s == 1 || s == -2 ? '0' : '00';
      s = Math.pow(n, 1 / 3);

      // Rarely, e may be one less than the result exponent value.
      e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));

      if (s == 1 / 0) {
        n = '5e' + e;
      } else {
        n = s.toExponential();
        n = n.slice(0, n.indexOf('e') + 1) + e;
      }

      r = new Ctor(n);
      r.s = x.s;
    } else {
      r = new Ctor(s.toString());
    }

    sd = (e = Ctor.precision) + 3;

    // Halley's method.
    // TODO? Compare Newton's method.
    for (;;) {
      t = r;
      t3 = t.times(t).times(t);
      t3plusx = t3.plus(x);
      r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);

      // TODO? Replace with for-loop and checkRoundingDigits.
      if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
        n = n.slice(sd - 3, sd + 1);

        // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
        // , i.e. approaching a rounding boundary, continue the iteration.
        if (n == '9999' || !rep && n == '4999') {

          // On the first iteration only, check to see if rounding up gives the exact result as the
          // nines may infinitely repeat.
          if (!rep) {
            finalise(t, e + 1, 0);

            if (t.times(t).times(t).eq(x)) {
              r = t;
              break;
            }
          }

          sd += 4;
          rep = 1;
        } else {

          // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
          // If not, then there are further digits and m will be truthy.
          if (!+n || !+n.slice(1) && n.charAt(0) == '5') {

            // Truncate to the first rounding digit.
            finalise(r, e + 1, 1);
            m = !r.times(r).times(r).eq(x);
          }

          break;
        }
      }
    }

    external = true;

    return finalise(r, e, Ctor.rounding, m);
  };

  /*
   * Return the number of decimal places of the value of this Decimal.
   *
   */
  P.decimalPlaces = P.dp = function () {
    var w,
        d = this.d,
        n = NaN;

    if (d) {
      w = d.length - 1;
      n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;

      // Subtract the number of trailing zeros of the last word.
      w = d[w];
      if (w) for (; w % 10 == 0; w /= 10) {
        n--;
      }if (n < 0) n = 0;
    }

    return n;
  };

  /*
   *  n / 0 = I
   *  n / N = N
   *  n / I = 0
   *  0 / n = 0
   *  0 / 0 = N
   *  0 / N = N
   *  0 / I = 0
   *  N / n = N
   *  N / 0 = N
   *  N / N = N
   *  N / I = N
   *  I / n = I
   *  I / 0 = I
   *  I / N = N
   *  I / I = N
   *
   * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
   * `precision` significant digits using rounding mode `rounding`.
   *
   */
  P.dividedBy = P.div = function (y) {
    return divide(this, new this.constructor(y));
  };

  /*
   * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
   * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
   *
   */
  P.dividedToIntegerBy = P.divToInt = function (y) {
    var x = this,
        Ctor = x.constructor;
    return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
  };

  /*
   * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
   *
   */
  P.equals = P.eq = function (y) {
    return this.cmp(y) === 0;
  };

  /*
   * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
   * direction of negative Infinity.
   *
   */
  P.floor = function () {
    return finalise(new this.constructor(this), this.e + 1, 3);
  };

  /*
   * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
   * false.
   *
   */
  P.greaterThan = P.gt = function (y) {
    return this.cmp(y) > 0;
  };

  /*
   * Return true if the value of this Decimal is greater than or equal to the value of `y`,
   * otherwise return false.
   *
   */
  P.greaterThanOrEqualTo = P.gte = function (y) {
    var k = this.cmp(y);
    return k == 1 || k === 0;
  };

  /*
   * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
   * Decimal.
   *
   * Domain: [-Infinity, Infinity]
   * Range: [1, Infinity]
   *
   * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
   *
   * cosh(0)         = 1
   * cosh(-0)        = 1
   * cosh(Infinity)  = Infinity
   * cosh(-Infinity) = Infinity
   * cosh(NaN)       = NaN
   *
   *  x        time taken (ms)   result
   * 1000      9                 9.8503555700852349694e+433
   * 10000     25                4.4034091128314607936e+4342
   * 100000    171               1.4033316802130615897e+43429
   * 1000000   3817              1.5166076984010437725e+434294
   * 10000000  abandoned after 2 minute wait
   *
   * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
   *
   */
  P.hyperbolicCosine = P.cosh = function () {
    var k,
        n,
        pr,
        rm,
        len,
        x = this,
        Ctor = x.constructor,
        one = new Ctor(1);

    if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
    if (x.isZero()) return one;

    pr = Ctor.precision;
    rm = Ctor.rounding;
    Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
    Ctor.rounding = 1;
    len = x.d.length;

    // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
    // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))

    // Estimate the optimum number of times to use the argument reduction.
    // TODO? Estimation reused from cosine() and may not be optimal here.
    if (len < 32) {
      k = Math.ceil(len / 3);
      n = Math.pow(4, -k).toString();
    } else {
      k = 16;
      n = '2.3283064365386962890625e-10';
    }

    x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);

    // Reverse argument reduction
    var cosh2_x,
        i = k,
        d8 = new Ctor(8);
    for (; i--;) {
      cosh2_x = x.times(x);
      x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
    }

    return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
  };

  /*
   * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
   * Decimal.
   *
   * Domain: [-Infinity, Infinity]
   * Range: [-Infinity, Infinity]
   *
   * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
   *
   * sinh(0)         = 0
   * sinh(-0)        = -0
   * sinh(Infinity)  = Infinity
   * sinh(-Infinity) = -Infinity
   * sinh(NaN)       = NaN
   *
   * x        time taken (ms)
   * 10       2 ms
   * 100      5 ms
   * 1000     14 ms
   * 10000    82 ms
   * 100000   886 ms            1.4033316802130615897e+43429
   * 200000   2613 ms
   * 300000   5407 ms
   * 400000   8824 ms
   * 500000   13026 ms          8.7080643612718084129e+217146
   * 1000000  48543 ms
   *
   * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
   *
   */
  P.hyperbolicSine = P.sinh = function () {
    var k,
        pr,
        rm,
        len,
        x = this,
        Ctor = x.constructor;

    if (!x.isFinite() || x.isZero()) return new Ctor(x);

    pr = Ctor.precision;
    rm = Ctor.rounding;
    Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
    Ctor.rounding = 1;
    len = x.d.length;

    if (len < 3) {
      x = taylorSeries(Ctor, 2, x, x, true);
    } else {

      // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
      // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
      // 3 multiplications and 1 addition

      // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
      // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
      // 4 multiplications and 2 additions

      // Estimate the optimum number of times to use the argument reduction.
      k = 1.4 * Math.sqrt(len);
      k = k > 16 ? 16 : k | 0;

      x = x.times(Math.pow(5, -k));

      x = taylorSeries(Ctor, 2, x, x, true);

      // Reverse argument reduction
      var sinh2_x,
          d5 = new Ctor(5),
          d16 = new Ctor(16),
          d20 = new Ctor(20);
      for (; k--;) {
        sinh2_x = x.times(x);
        x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
      }
    }

    Ctor.precision = pr;
    Ctor.rounding = rm;

    return finalise(x, pr, rm, true);
  };

  /*
   * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
   * Decimal.
   *
   * Domain: [-Infinity, Infinity]
   * Range: [-1, 1]
   *
   * tanh(x) = sinh(x) / cosh(x)
   *
   * tanh(0)         = 0
   * tanh(-0)        = -0
   * tanh(Infinity)  = 1
   * tanh(-Infinity) = -1
   * tanh(NaN)       = NaN
   *
   */
  P.hyperbolicTangent = P.tanh = function () {
    var pr,
        rm,
        x = this,
        Ctor = x.constructor;

    if (!x.isFinite()) return new Ctor(x.s);
    if (x.isZero()) return new Ctor(x);

    pr = Ctor.precision;
    rm = Ctor.rounding;
    Ctor.precision = pr + 7;
    Ctor.rounding = 1;

    return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
  };

  /*
   * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
   * this Decimal.
   *
   * Domain: [-1, 1]
   * Range: [0, pi]
   *
   * acos(x) = pi/2 - asin(x)
   *
   * acos(0)       = pi/2
   * acos(-0)      = pi/2
   * acos(1)       = 0
   * acos(-1)      = pi
   * acos(1/2)     = pi/3
   * acos(-1/2)    = 2*pi/3
   * acos(|x| > 1) = NaN
   * acos(NaN)     = NaN
   *
   */
  P.inverseCosine = P.acos = function () {
    var halfPi,
        x = this,
        Ctor = x.constructor,
        k = x.abs().cmp(1),
        pr = Ctor.precision,
        rm = Ctor.rounding;

    if (k !== -1) {
      return k === 0
      // |x| is 1
      ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
      // |x| > 1 or x is NaN
      : new Ctor(NaN);
    }

    if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);

    // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3

    Ctor.precision = pr + 6;
    Ctor.rounding = 1;

    x = x.asin();
    halfPi = getPi(Ctor, pr + 4, rm).times(0.5);

    Ctor.precision = pr;
    Ctor.rounding = rm;

    return halfPi.minus(x);
  };

  /*
   * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
   * value of this Decimal.
   *
   * Domain: [1, Infinity]
   * Range: [0, Infinity]
   *
   * acosh(x) = ln(x + sqrt(x^2 - 1))
   *
   * acosh(x < 1)     = NaN
   * acosh(NaN)       = NaN
   * acosh(Infinity)  = Infinity
   * acosh(-Infinity) = NaN
   * acosh(0)         = NaN
   * acosh(-0)        = NaN
   * acosh(1)         = 0
   * acosh(-1)        = NaN
   *
   */
  P.inverseHyperbolicCosine = P.acosh = function () {
    var pr,
        rm,
        x = this,
        Ctor = x.constructor;

    if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
    if (!x.isFinite()) return new Ctor(x);

    pr = Ctor.precision;
    rm = Ctor.rounding;
    Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
    Ctor.rounding = 1;
    external = false;

    x = x.times(x).minus(1).sqrt().plus(x);

    external = true;
    Ctor.precision = pr;
    Ctor.rounding = rm;

    return x.ln();
  };

  /*
   * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
   * of this Decimal.
   *
   * Domain: [-Infinity, Infinity]
   * Range: [-Infinity, Infinity]
   *
   * asinh(x) = ln(x + sqrt(x^2 + 1))
   *
   * asinh(NaN)       = NaN
   * asinh(Infinity)  = Infinity
   * asinh(-Infinity) = -Infinity
   * asinh(0)         = 0
   * asinh(-0)        = -0
   *
   */
  P.inverseHyperbolicSine = P.asinh = function () {
    var pr,
        rm,
        x = this,
        Ctor = x.constructor;

    if (!x.isFinite() || x.isZero()) return new Ctor(x);

    pr = Ctor.precision;
    rm = Ctor.rounding;
    Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
    Ctor.rounding = 1;
    external = false;

    x = x.times(x).plus(1).sqrt().plus(x);

    external = true;
    Ctor.precision = pr;
    Ctor.rounding = rm;

    return x.ln();
  };

  /*
   * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
   * value of this Decimal.
   *
   * Domain: [-1, 1]
   * Range: [-Infinity, Infinity]
   *
   * atanh(x) = 0.5 * ln((1 + x) / (1 - x))
   *
   * atanh(|x| > 1)   = NaN
   * atanh(NaN)       = NaN
   * atanh(Infinity)  = NaN
   * atanh(-Infinity) = NaN
   * atanh(0)         = 0
   * atanh(-0)        = -0
   * atanh(1)         = Infinity
   * atanh(-1)        = -Infinity
   *
   */
  P.inverseHyperbolicTangent = P.atanh = function () {
    var pr,
        rm,
        wpr,
        xsd,
        x = this,
        Ctor = x.constructor;

    if (!x.isFinite()) return new Ctor(NaN);
    if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);

    pr = Ctor.precision;
    rm = Ctor.rounding;
    xsd = x.sd();

    if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);

    Ctor.precision = wpr = xsd - x.e;

    x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);

    Ctor.precision = pr + 4;
    Ctor.rounding = 1;

    x = x.ln();

    Ctor.precision = pr;
    Ctor.rounding = rm;

    return x.times(0.5);
  };

  /*
   * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
   * Decimal.
   *
   * Domain: [-Infinity, Infinity]
   * Range: [-pi/2, pi/2]
   *
   * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
   *
   * asin(0)       = 0
   * asin(-0)      = -0
   * asin(1/2)     = pi/6
   * asin(-1/2)    = -pi/6
   * asin(1)       = pi/2
   * asin(-1)      = -pi/2
   * asin(|x| > 1) = NaN
   * asin(NaN)     = NaN
   *
   * TODO? Compare performance of Taylor series.
   *
   */
  P.inverseSine = P.asin = function () {
    var halfPi,
        k,
        pr,
        rm,
        x = this,
        Ctor = x.constructor;

    if (x.isZero()) return new Ctor(x);

    k = x.abs().cmp(1);
    pr = Ctor.precision;
    rm = Ctor.rounding;

    if (k !== -1) {

      // |x| is 1
      if (k === 0) {
        halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
        halfPi.s = x.s;
        return halfPi;
      }

      // |x| > 1 or x is NaN
      return new Ctor(NaN);
    }

    // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6

    Ctor.precision = pr + 6;
    Ctor.rounding = 1;

    x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();

    Ctor.precision = pr;
    Ctor.rounding = rm;

    return x.times(2);
  };

  /*
   * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
   * of this Decimal.
   *
   * Domain: [-Infinity, Infinity]
   * Range: [-pi/2, pi/2]
   *
   * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
   *
   * atan(0)         = 0
   * atan(-0)        = -0
   * atan(1)         = pi/4
   * atan(-1)        = -pi/4
   * atan(Infinity)  = pi/2
   * atan(-Infinity) = -pi/2
   * atan(NaN)       = NaN
   *
   */
  P.inverseTangent = P.atan = function () {
    var i,
        j,
        k,
        n,
        px,
        t,
        r,
        wpr,
        x2,
        x = this,
        Ctor = x.constructor,
        pr = Ctor.precision,
        rm = Ctor.rounding;

    if (!x.isFinite()) {
      if (!x.s) return new Ctor(NaN);
      if (pr + 4 <= PI_PRECISION) {
        r = getPi(Ctor, pr + 4, rm).times(0.5);
        r.s = x.s;
        return r;
      }
    } else if (x.isZero()) {
      return new Ctor(x);
    } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
      r = getPi(Ctor, pr + 4, rm).times(0.25);
      r.s = x.s;
      return r;
    }

    Ctor.precision = wpr = pr + 10;
    Ctor.rounding = 1;

    // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);

    // Argument reduction
    // Ensure |x| < 0.42
    // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))

    k = Math.min(28, wpr / LOG_BASE + 2 | 0);

    for (i = k; i; --i) {
      x = x.div(x.times(x).plus(1).sqrt().plus(1));
    }external = false;

    j = Math.ceil(wpr / LOG_BASE);
    n = 1;
    x2 = x.times(x);
    r = new Ctor(x);
    px = x;

    // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
    for (; i !== -1;) {
      px = px.times(x2);
      t = r.minus(px.div(n += 2));

      px = px.times(x2);
      r = t.plus(px.div(n += 2));

      if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;) {}
    }

    if (k) r = r.times(2 << k - 1);

    external = true;

    return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
  };

  /*
   * Return true if the value of this Decimal is a finite number, otherwise return false.
   *
   */
  P.isFinite = function () {
    return !!this.d;
  };

  /*
   * Return true if the value of this Decimal is an integer, otherwise return false.
   *
   */
  P.isInteger = P.isInt = function () {
    return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
  };

  /*
   * Return true if the value of this Decimal is NaN, otherwise return false.
   *
   */
  P.isNaN = function () {
    return !this.s;
  };

  /*
   * Return true if the value of this Decimal is negative, otherwise return false.
   *
   */
  P.isNegative = P.isNeg = function () {
    return this.s < 0;
  };

  /*
   * Return true if the value of this Decimal is positive, otherwise return false.
   *
   */
  P.isPositive = P.isPos = function () {
    return this.s > 0;
  };

  /*
   * Return true if the value of this Decimal is 0 or -0, otherwise return false.
   *
   */
  P.isZero = function () {
    return !!this.d && this.d[0] === 0;
  };

  /*
   * Return true if the value of this Decimal is less than `y`, otherwise return false.
   *
   */
  P.lessThan = P.lt = function (y) {
    return this.cmp(y) < 0;
  };

  /*
   * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
   *
   */
  P.lessThanOrEqualTo = P.lte = function (y) {
    return this.cmp(y) < 1;
  };

  /*
   * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   * If no base is specified, return log[10](arg).
   *
   * log[base](arg) = ln(arg) / ln(base)
   *
   * The result will always be correctly rounded if the base of the log is 10, and 'almost always'
   * otherwise:
   *
   * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
   * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
   * between the result and the correctly rounded result will be one ulp (unit in the last place).
   *
   * log[-b](a)       = NaN
   * log[0](a)        = NaN
   * log[1](a)        = NaN
   * log[NaN](a)      = NaN
   * log[Infinity](a) = NaN
   * log[b](0)        = -Infinity
   * log[b](-0)       = -Infinity
   * log[b](-a)       = NaN
   * log[b](1)        = 0
   * log[b](Infinity) = Infinity
   * log[b](NaN)      = NaN
   *
   * [base] {number|string|Decimal} The base of the logarithm.
   *
   */
  P.logarithm = P.log = function (base) {
    var isBase10,
        d,
        denominator,
        k,
        inf,
        num,
        sd,
        r,
        arg = this,
        Ctor = arg.constructor,
        pr = Ctor.precision,
        rm = Ctor.rounding,
        guard = 5;

    // Default base is 10.
    if (base == null) {
      base = new Ctor(10);
      isBase10 = true;
    } else {
      base = new Ctor(base);
      d = base.d;

      // Return NaN if base is negative, or non-finite, or is 0 or 1.
      if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);

      isBase10 = base.eq(10);
    }

    d = arg.d;

    // Is arg negative, non-finite, 0 or 1?
    if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
      return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
    }

    // The result will have a non-terminating decimal expansion if base is 10 and arg is not an
    // integer power of 10.
    if (isBase10) {
      if (d.length > 1) {
        inf = true;
      } else {
        for (k = d[0]; k % 10 === 0;) {
          k /= 10;
        }inf = k !== 1;
      }
    }

    external = false;
    sd = pr + guard;
    num = naturalLogarithm(arg, sd);
    denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);

    // The result will have 5 rounding digits.
    r = divide(num, denominator, sd, 1);

    // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
    // calculate 10 further digits.
    //
    // If the result is known to have an infinite decimal expansion, repeat this until it is clear
    // that the result is above or below the boundary. Otherwise, if after calculating the 10
    // further digits, the last 14 are nines, round up and assume the result is exact.
    // Also assume the result is exact if the last 14 are zero.
    //
    // Example of a result that will be incorrectly rounded:
    // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
    // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
    // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
    // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
    // place is still 2.6.
    if (checkRoundingDigits(r.d, k = pr, rm)) {

      do {
        sd += 10;
        num = naturalLogarithm(arg, sd);
        denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
        r = divide(num, denominator, sd, 1);

        if (!inf) {

          // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
          if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
            r = finalise(r, pr + 1, 0);
          }

          break;
        }
      } while (checkRoundingDigits(r.d, k += 10, rm));
    }

    external = true;

    return finalise(r, pr, rm);
  };

  /*
   * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
   *
   * arguments {number|string|Decimal}
   *
  P.max = function () {
    Array.prototype.push.call(arguments, this);
    return maxOrMin(this.constructor, arguments, 'lt');
  };
   */

  /*
   * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
   *
   * arguments {number|string|Decimal}
   *
  P.min = function () {
    Array.prototype.push.call(arguments, this);
    return maxOrMin(this.constructor, arguments, 'gt');
  };
   */

  /*
   *  n - 0 = n
   *  n - N = N
   *  n - I = -I
   *  0 - n = -n
   *  0 - 0 = 0
   *  0 - N = N
   *  0 - I = -I
   *  N - n = N
   *  N - 0 = N
   *  N - N = N
   *  N - I = N
   *  I - n = I
   *  I - 0 = I
   *  I - N = N
   *  I - I = N
   *
   * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   */
  P.minus = P.sub = function (y) {
    var d,
        e,
        i,
        j,
        k,
        len,
        pr,
        rm,
        xd,
        xe,
        xLTy,
        yd,
        x = this,
        Ctor = x.constructor;

    y = new Ctor(y);

    // If either is not finite...
    if (!x.d || !y.d) {

      // Return NaN if either is NaN.
      if (!x.s || !y.s) y = new Ctor(NaN);

      // Return y negated if x is finite and y is ±Infinity.
      else if (x.d) y.s = -y.s;

        // Return x if y is finite and x is ±Infinity.
        // Return x if both are ±Infinity with different signs.
        // Return NaN if both are ±Infinity with the same sign.
        else y = new Ctor(y.d || x.s !== y.s ? x : NaN);

      return y;
    }

    // If signs differ...
    if (x.s != y.s) {
      y.s = -y.s;
      return x.plus(y);
    }

    xd = x.d;
    yd = y.d;
    pr = Ctor.precision;
    rm = Ctor.rounding;

    // If either is zero...
    if (!xd[0] || !yd[0]) {

      // Return y negated if x is zero and y is non-zero.
      if (yd[0]) y.s = -y.s;

      // Return x if y is zero and x is non-zero.
      else if (xd[0]) y = new Ctor(x);

        // Return zero if both are zero.
        // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
        else return new Ctor(rm === 3 ? -0 : 0);

      return external ? finalise(y, pr, rm) : y;
    }

    // x and y are finite, non-zero numbers with the same sign.

    // Calculate base 1e7 exponents.
    e = mathfloor(y.e / LOG_BASE);
    xe = mathfloor(x.e / LOG_BASE);

    xd = xd.slice();
    k = xe - e;

    // If base 1e7 exponents differ...
    if (k) {
      xLTy = k < 0;

      if (xLTy) {
        d = xd;
        k = -k;
        len = yd.length;
      } else {
        d = yd;
        e = xe;
        len = xd.length;
      }

      // Numbers with massively different exponents would result in a very high number of
      // zeros needing to be prepended, but this can be avoided while still ensuring correct
      // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
      i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;

      if (k > i) {
        k = i;
        d.length = 1;
      }

      // Prepend zeros to equalise exponents.
      d.reverse();
      for (i = k; i--;) {
        d.push(0);
      }d.reverse();

      // Base 1e7 exponents equal.
    } else {

      // Check digits to determine which is the bigger number.

      i = xd.length;
      len = yd.length;
      xLTy = i < len;
      if (xLTy) len = i;

      for (i = 0; i < len; i++) {
        if (xd[i] != yd[i]) {
          xLTy = xd[i] < yd[i];
          break;
        }
      }

      k = 0;
    }

    if (xLTy) {
      d = xd;
      xd = yd;
      yd = d;
      y.s = -y.s;
    }

    len = xd.length;

    // Append zeros to `xd` if shorter.
    // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
    for (i = yd.length - len; i > 0; --i) {
      xd[len++] = 0;
    } // Subtract yd from xd.
    for (i = yd.length; i > k;) {

      if (xd[--i] < yd[i]) {
        for (j = i; j && xd[--j] === 0;) {
          xd[j] = BASE - 1;
        }--xd[j];
        xd[i] += BASE;
      }

      xd[i] -= yd[i];
    }

    // Remove trailing zeros.
    for (; xd[--len] === 0;) {
      xd.pop();
    } // Remove leading zeros and adjust exponent accordingly.
    for (; xd[0] === 0; xd.shift()) {
      --e;
    } // Zero?
    if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);

    y.d = xd;
    y.e = getBase10Exponent(xd, e);

    return external ? finalise(y, pr, rm) : y;
  };

  /*
   *   n % 0 =  N
   *   n % N =  N
   *   n % I =  n
   *   0 % n =  0
   *  -0 % n = -0
   *   0 % 0 =  N
   *   0 % N =  N
   *   0 % I =  0
   *   N % n =  N
   *   N % 0 =  N
   *   N % N =  N
   *   N % I =  N
   *   I % n =  N
   *   I % 0 =  N
   *   I % N =  N
   *   I % I =  N
   *
   * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
   * `precision` significant digits using rounding mode `rounding`.
   *
   * The result depends on the modulo mode.
   *
   */
  P.modulo = P.mod = function (y) {
    var q,
        x = this,
        Ctor = x.constructor;

    y = new Ctor(y);

    // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
    if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);

    // Return x if y is ±Infinity or x is ±0.
    if (!y.d || x.d && !x.d[0]) {
      return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
    }

    // Prevent rounding of intermediate calculations.
    external = false;

    if (Ctor.modulo == 9) {

      // Euclidian division: q = sign(y) * floor(x / abs(y))
      // result = x - q * y    where  0 <= result < abs(y)
      q = divide(x, y.abs(), 0, 3, 1);
      q.s *= y.s;
    } else {
      q = divide(x, y, 0, Ctor.modulo, 1);
    }

    q = q.times(y);

    external = true;

    return x.minus(q);
  };

  /*
   * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
   * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   */
  P.naturalExponential = P.exp = function () {
    return naturalExponential(this);
  };

  /*
   * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
   * rounded to `precision` significant digits using rounding mode `rounding`.
   *
   */
  P.naturalLogarithm = P.ln = function () {
    return naturalLogarithm(this);
  };

  /*
   * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
   * -1.
   *
   */
  P.negated = P.neg = function () {
    var x = new this.constructor(this);
    x.s = -x.s;
    return finalise(x);
  };

  /*
   *  n + 0 = n
   *  n + N = N
   *  n + I = I
   *  0 + n = n
   *  0 + 0 = 0
   *  0 + N = N
   *  0 + I = I
   *  N + n = N
   *  N + 0 = N
   *  N + N = N
   *  N + I = N
   *  I + n = I
   *  I + 0 = I
   *  I + N = N
   *  I + I = I
   *
   * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   */
  P.plus = P.add = function (y) {
    var carry,
        d,
        e,
        i,
        k,
        len,
        pr,
        rm,
        xd,
        yd,
        x = this,
        Ctor = x.constructor;

    y = new Ctor(y);

    // If either is not finite...
    if (!x.d || !y.d) {

      // Return NaN if either is NaN.
      if (!x.s || !y.s) y = new Ctor(NaN);

      // Return x if y is finite and x is ±Infinity.
      // Return x if both are ±Infinity with the same sign.
      // Return NaN if both are ±Infinity with different signs.
      // Return y if x is finite and y is ±Infinity.
      else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);

      return y;
    }

    // If signs differ...
    if (x.s != y.s) {
      y.s = -y.s;
      return x.minus(y);
    }

    xd = x.d;
    yd = y.d;
    pr = Ctor.precision;
    rm = Ctor.rounding;

    // If either is zero...
    if (!xd[0] || !yd[0]) {

      // Return x if y is zero.
      // Return y if y is non-zero.
      if (!yd[0]) y = new Ctor(x);

      return external ? finalise(y, pr, rm) : y;
    }

    // x and y are finite, non-zero numbers with the same sign.

    // Calculate base 1e7 exponents.
    k = mathfloor(x.e / LOG_BASE);
    e = mathfloor(y.e / LOG_BASE);

    xd = xd.slice();
    i = k - e;

    // If base 1e7 exponents differ...
    if (i) {

      if (i < 0) {
        d = xd;
        i = -i;
        len = yd.length;
      } else {
        d = yd;
        e = k;
        len = xd.length;
      }

      // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
      k = Math.ceil(pr / LOG_BASE);
      len = k > len ? k + 1 : len + 1;

      if (i > len) {
        i = len;
        d.length = 1;
      }

      // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
      d.reverse();
      for (; i--;) {
        d.push(0);
      }d.reverse();
    }

    len = xd.length;
    i = yd.length;

    // If yd is longer than xd, swap xd and yd so xd points to the longer array.
    if (len - i < 0) {
      i = len;
      d = yd;
      yd = xd;
      xd = d;
    }

    // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
    for (carry = 0; i;) {
      carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
      xd[i] %= BASE;
    }

    if (carry) {
      xd.unshift(carry);
      ++e;
    }

    // Remove trailing zeros.
    // No need to check for zero, as +x + +y != 0 && -x + -y != 0
    for (len = xd.length; xd[--len] == 0;) {
      xd.pop();
    }y.d = xd;
    y.e = getBase10Exponent(xd, e);

    return external ? finalise(y, pr, rm) : y;
  };

  /*
   * Return the number of significant digits of the value of this Decimal.
   *
   * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
   *
   */
  P.precision = P.sd = function (z) {
    var k,
        x = this;

    if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);

    if (x.d) {
      k = getPrecision(x.d);
      if (z && x.e + 1 > k) k = x.e + 1;
    } else {
      k = NaN;
    }

    return k;
  };

  /*
   * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
   * rounding mode `rounding`.
   *
   */
  P.round = function () {
    var x = this,
        Ctor = x.constructor;

    return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
  };

  /*
   * Return a new Decimal whose value is the sine of the value in radians of this Decimal.
   *
   * Domain: [-Infinity, Infinity]
   * Range: [-1, 1]
   *
   * sin(x) = x - x^3/3! + x^5/5! - ...
   *
   * sin(0)         = 0
   * sin(-0)        = -0
   * sin(Infinity)  = NaN
   * sin(-Infinity) = NaN
   * sin(NaN)       = NaN
   *
   */
  P.sine = P.sin = function () {
    var pr,
        rm,
        x = this,
        Ctor = x.constructor;

    if (!x.isFinite()) return new Ctor(NaN);
    if (x.isZero()) return new Ctor(x);

    pr = Ctor.precision;
    rm = Ctor.rounding;
    Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
    Ctor.rounding = 1;

    x = sine(Ctor, toLessThanHalfPi(Ctor, x));

    Ctor.precision = pr;
    Ctor.rounding = rm;

    return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
  };

  /*
   * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   *  sqrt(-n) =  N
   *  sqrt(N)  =  N
   *  sqrt(-I) =  N
   *  sqrt(I)  =  I
   *  sqrt(0)  =  0
   *  sqrt(-0) = -0
   *
   */
  P.squareRoot = P.sqrt = function () {
    var m,
        n,
        sd,
        r,
        rep,
        t,
        x = this,
        d = x.d,
        e = x.e,
        s = x.s,
        Ctor = x.constructor;

    // Negative/NaN/Infinity/zero?
    if (s !== 1 || !d || !d[0]) {
      return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
    }

    external = false;

    // Initial estimate.
    s = Math.sqrt(+x);

    // Math.sqrt underflow/overflow?
    // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
    if (s == 0 || s == 1 / 0) {
      n = digitsToString(d);

      if ((n.length + e) % 2 == 0) n += '0';
      s = Math.sqrt(n);
      e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);

      if (s == 1 / 0) {
        n = '1e' + e;
      } else {
        n = s.toExponential();
        n = n.slice(0, n.indexOf('e') + 1) + e;
      }

      r = new Ctor(n);
    } else {
      r = new Ctor(s.toString());
    }

    sd = (e = Ctor.precision) + 3;

    // Newton-Raphson iteration.
    for (;;) {
      t = r;
      r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);

      // TODO? Replace with for-loop and checkRoundingDigits.
      if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
        n = n.slice(sd - 3, sd + 1);

        // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
        // 4999, i.e. approaching a rounding boundary, continue the iteration.
        if (n == '9999' || !rep && n == '4999') {

          // On the first iteration only, check to see if rounding up gives the exact result as the
          // nines may infinitely repeat.
          if (!rep) {
            finalise(t, e + 1, 0);

            if (t.times(t).eq(x)) {
              r = t;
              break;
            }
          }

          sd += 4;
          rep = 1;
        } else {

          // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
          // If not, then there are further digits and m will be truthy.
          if (!+n || !+n.slice(1) && n.charAt(0) == '5') {

            // Truncate to the first rounding digit.
            finalise(r, e + 1, 1);
            m = !r.times(r).eq(x);
          }

          break;
        }
      }
    }

    external = true;

    return finalise(r, e, Ctor.rounding, m);
  };

  /*
   * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
   *
   * Domain: [-Infinity, Infinity]
   * Range: [-Infinity, Infinity]
   *
   * tan(0)         = 0
   * tan(-0)        = -0
   * tan(Infinity)  = NaN
   * tan(-Infinity) = NaN
   * tan(NaN)       = NaN
   *
   */
  P.tangent = P.tan = function () {
    var pr,
        rm,
        x = this,
        Ctor = x.constructor;

    if (!x.isFinite()) return new Ctor(NaN);
    if (x.isZero()) return new Ctor(x);

    pr = Ctor.precision;
    rm = Ctor.rounding;
    Ctor.precision = pr + 10;
    Ctor.rounding = 1;

    x = x.sin();
    x.s = 1;
    x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);

    Ctor.precision = pr;
    Ctor.rounding = rm;

    return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
  };

  /*
   *  n * 0 = 0
   *  n * N = N
   *  n * I = I
   *  0 * n = 0
   *  0 * 0 = 0
   *  0 * N = N
   *  0 * I = N
   *  N * n = N
   *  N * 0 = N
   *  N * N = N
   *  N * I = N
   *  I * n = I
   *  I * 0 = N
   *  I * N = N
   *  I * I = I
   *
   * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
   * digits using rounding mode `rounding`.
   *
   */
  P.times = P.mul = function (y) {
    var carry,
        e,
        i,
        k,
        r,
        rL,
        t,
        xdL,
        ydL,
        x = this,
        Ctor = x.constructor,
        xd = x.d,
        yd = (y = new Ctor(y)).d;

    y.s *= x.s;

    // If either is NaN, ±Infinity or ±0...
    if (!xd || !xd[0] || !yd || !yd[0]) {

      return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd

      // Return NaN if either is NaN.
      // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
      ? NaN

      // Return ±Infinity if either is ±Infinity.
      // Return ±0 if either is ±0.
      : !xd || !yd ? y.s / 0 : y.s * 0);
    }

    e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
    xdL = xd.length;
    ydL = yd.length;

    // Ensure xd points to the longer array.
    if (xdL < ydL) {
      r = xd;
      xd = yd;
      yd = r;
      rL = xdL;
      xdL = ydL;
      ydL = rL;
    }

    // Initialise the result array with zeros.
    r = [];
    rL = xdL + ydL;
    for (i = rL; i--;) {
      r.push(0);
    } // Multiply!
    for (i = ydL; --i >= 0;) {
      carry = 0;
      for (k = xdL + i; k > i;) {
        t = r[k] + yd[i] * xd[k - i - 1] + carry;
        r[k--] = t % BASE | 0;
        carry = t / BASE | 0;
      }

      r[k] = (r[k] + carry) % BASE | 0;
    }

    // Remove trailing zeros.
    for (; !r[--rL];) {
      r.pop();
    }if (carry) ++e;else r.shift();

    y.d = r;
    y.e = getBase10Exponent(r, e);

    return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
  };

  /*
   * Return a string representing the value of this Decimal in base 2, round to `sd` significant
   * digits using rounding mode `rm`.
   *
   * If the optional `sd` argument is present then return binary exponential notation.
   *
   * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
   * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   *
   */
  P.toBinary = function (sd, rm) {
    return toStringBinary(this, 2, sd, rm);
  };

  /*
   * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
   * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
   *
   * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
   *
   * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
   * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   *
   */
  P.toDecimalPlaces = P.toDP = function (dp, rm) {
    var x = this,
        Ctor = x.constructor;

    x = new Ctor(x);
    if (dp === void 0) return x;

    checkInt32(dp, 0, MAX_DIGITS);

    if (rm === void 0) rm = Ctor.rounding;else checkInt32(rm, 0, 8);

    return finalise(x, dp + x.e + 1, rm);
  };

  /*
   * Return a string representing the value of this Decimal in exponential notation rounded to
   * `dp` fixed decimal places using rounding mode `rounding`.
   *
   * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
   * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   *
   */
  P.toExponential = function (dp, rm) {
    var str,
        x = this,
        Ctor = x.constructor;

    if (dp === void 0) {
      str = finiteToString(x, true);
    } else {
      checkInt32(dp, 0, MAX_DIGITS);

      if (rm === void 0) rm = Ctor.rounding;else checkInt32(rm, 0, 8);

      x = finalise(new Ctor(x), dp + 1, rm);
      str = finiteToString(x, true, dp + 1);
    }

    return x.isNeg() && !x.isZero() ? '-' + str : str;
  };

  /*
   * Return a string representing the value of this Decimal in normal (fixed-point) notation to
   * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
   * omitted.
   *
   * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
   *
   * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
   * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   *
   * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
   * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
   * (-0).toFixed(3) is '0.000'.
   * (-0.5).toFixed(0) is '-0'.
   *
   */
  P.toFixed = function (dp, rm) {
    var str,
        y,
        x = this,
        Ctor = x.constructor;

    if (dp === void 0) {
      str = finiteToString(x);
    } else {
      checkInt32(dp, 0, MAX_DIGITS);

      if (rm === void 0) rm = Ctor.rounding;else checkInt32(rm, 0, 8);

      y = finalise(new Ctor(x), dp + x.e + 1, rm);
      str = finiteToString(y, false, dp + y.e + 1);
    }

    // To determine whether to add the minus sign look at the value before it was rounded,
    // i.e. look at `x` rather than `y`.
    return x.isNeg() && !x.isZero() ? '-' + str : str;
  };

  /*
   * Return an array representing the value of this Decimal as a simple fraction with an integer
   * numerator and an integer denominator.
   *
   * The denominator will be a positive non-zero value less than or equal to the specified maximum
   * denominator. If a maximum denominator is not specified, the denominator will be the lowest
   * value necessary to represent the number exactly.
   *
   * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
   *
   */
  P.toFraction = function (maxD) {
    var d,
        d0,
        d1,
        d2,
        e,
        k,
        n,
        n0,
        n1,
        pr,
        q,
        r,
        x = this,
        xd = x.d,
        Ctor = x.constructor;

    if (!xd) return new Ctor(x);

    n1 = d0 = new Ctor(1);
    d1 = n0 = new Ctor(0);

    d = new Ctor(d1);
    e = d.e = getPrecision(xd) - x.e - 1;
    k = e % LOG_BASE;
    d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);

    if (maxD == null) {

      // d is 10**e, the minimum max-denominator needed.
      maxD = e > 0 ? d : n1;
    } else {
      n = new Ctor(maxD);
      if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
      maxD = n.gt(d) ? e > 0 ? d : n1 : n;
    }

    external = false;
    n = new Ctor(digitsToString(xd));
    pr = Ctor.precision;
    Ctor.precision = e = xd.length * LOG_BASE * 2;

    for (;;) {
      q = divide(n, d, 0, 1, 1);
      d2 = d0.plus(q.times(d1));
      if (d2.cmp(maxD) == 1) break;
      d0 = d1;
      d1 = d2;
      d2 = n1;
      n1 = n0.plus(q.times(d2));
      n0 = d2;
      d2 = d;
      d = n.minus(q.times(d2));
      n = d2;
    }

    d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
    n0 = n0.plus(d2.times(n1));
    d0 = d0.plus(d2.times(d1));
    n0.s = n1.s = x.s;

    // Determine which fraction is closer to x, n0/d0 or n1/d1?
    r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];

    Ctor.precision = pr;
    external = true;

    return r;
  };

  /*
   * Return a string representing the value of this Decimal in base 16, round to `sd` significant
   * digits using rounding mode `rm`.
   *
   * If the optional `sd` argument is present then return binary exponential notation.
   *
   * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
   * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   *
   */
  P.toHexadecimal = P.toHex = function (sd, rm) {
    return toStringBinary(this, 16, sd, rm);
  };

  /*
   * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding
   * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.
   *
   * The return value will always have the same sign as this Decimal, unless either this Decimal
   * or `y` is NaN, in which case the return value will be also be NaN.
   *
   * The return value is not affected by the value of `precision`.
   *
   * y {number|string|Decimal} The magnitude to round to a multiple of.
   * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   *
   * 'toNearest() rounding mode not an integer: {rm}'
   * 'toNearest() rounding mode out of range: {rm}'
   *
   */
  P.toNearest = function (y, rm) {
    var x = this,
        Ctor = x.constructor;

    x = new Ctor(x);

    if (y == null) {

      // If x is not finite, return x.
      if (!x.d) return x;

      y = new Ctor(1);
      rm = Ctor.rounding;
    } else {
      y = new Ctor(y);
      if (rm === void 0) {
        rm = Ctor.rounding;
      } else {
        checkInt32(rm, 0, 8);
      }

      // If x is not finite, return x if y is not NaN, else NaN.
      if (!x.d) return y.s ? x : y;

      // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
      if (!y.d) {
        if (y.s) y.s = x.s;
        return y;
      }
    }

    // If y is not zero, calculate the nearest multiple of y to x.
    if (y.d[0]) {
      external = false;
      x = divide(x, y, 0, rm, 1).times(y);
      external = true;
      finalise(x);

      // If y is zero, return zero with the sign of x.
    } else {
      y.s = x.s;
      x = y;
    }

    return x;
  };

  /*
   * Return the value of this Decimal converted to a number primitive.
   * Zero keeps its sign.
   *
   */
  P.toNumber = function () {
    return +this;
  };

  /*
   * Return a string representing the value of this Decimal in base 8, round to `sd` significant
   * digits using rounding mode `rm`.
   *
   * If the optional `sd` argument is present then return binary exponential notation.
   *
   * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
   * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   *
   */
  P.toOctal = function (sd, rm) {
    return toStringBinary(this, 8, sd, rm);
  };

  /*
   * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
   * to `precision` significant digits using rounding mode `rounding`.
   *
   * ECMAScript compliant.
   *
   *   pow(x, NaN)                           = NaN
   *   pow(x, ±0)                            = 1
     *   pow(NaN, non-zero)                    = NaN
   *   pow(abs(x) > 1, +Infinity)            = +Infinity
   *   pow(abs(x) > 1, -Infinity)            = +0
   *   pow(abs(x) == 1, ±Infinity)           = NaN
   *   pow(abs(x) < 1, +Infinity)            = +0
   *   pow(abs(x) < 1, -Infinity)            = +Infinity
   *   pow(+Infinity, y > 0)                 = +Infinity
   *   pow(+Infinity, y < 0)                 = +0
   *   pow(-Infinity, odd integer > 0)       = -Infinity
   *   pow(-Infinity, even integer > 0)      = +Infinity
   *   pow(-Infinity, odd integer < 0)       = -0
   *   pow(-Infinity, even integer < 0)      = +0
   *   pow(+0, y > 0)                        = +0
   *   pow(+0, y < 0)                        = +Infinity
   *   pow(-0, odd integer > 0)              = -0
   *   pow(-0, even integer > 0)             = +0
   *   pow(-0, odd integer < 0)              = -Infinity
   *   pow(-0, even integer < 0)             = +Infinity
   *   pow(finite x < 0, finite non-integer) = NaN
   *
   * For non-integer or very large exponents pow(x, y) is calculated using
   *
   *   x^y = exp(y*ln(x))
   *
   * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
   * probability of an incorrectly rounded result
   * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
   * i.e. 1 in 250,000,000,000,000
   *
   * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
   *
   * y {number|string|Decimal} The power to which to raise this Decimal.
   *
   */
  P.toPower = P.pow = function (y) {
    var e,
        k,
        pr,
        r,
        rm,
        s,
        x = this,
        Ctor = x.constructor,
        yn = +(y = new Ctor(y));

    // Either ±Infinity, NaN or ±0?
    if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));

    x = new Ctor(x);

    if (x.eq(1)) return x;

    pr = Ctor.precision;
    rm = Ctor.rounding;

    if (y.eq(1)) return finalise(x, pr, rm);

    // y exponent
    e = mathfloor(y.e / LOG_BASE);

    // If y is a small integer use the 'exponentiation by squaring' algorithm.
    if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
      r = intPow(Ctor, x, k, pr);
      return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
    }

    s = x.s;

    // if x is negative
    if (s < 0) {

      // if y is not an integer
      if (e < y.d.length - 1) return new Ctor(NaN);

      // Result is positive if x is negative and the last digit of integer y is even.
      if ((y.d[e] & 1) == 0) s = 1;

      // if x.eq(-1)
      if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
        x.s = s;
        return x;
      }
    }

    // Estimate result exponent.
    // x^y = 10^e,  where e = y * log10(x)
    // log10(x) = log10(x_significand) + x_exponent
    // log10(x_significand) = ln(x_significand) / ln(10)
    k = mathpow(+x, yn);
    e = k == 0 || !isFinite(k) ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) : new Ctor(k + '').e;

    // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.

    // Overflow/underflow?
    if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);

    external = false;
    Ctor.rounding = x.s = 1;

    // Estimate the extra guard digits needed to ensure five correct rounding digits from
    // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
    // new Decimal(2.32456).pow('2087987436534566.46411')
    // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
    k = Math.min(12, (e + '').length);

    // r = x^y = exp(y*ln(x))
    r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);

    // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
    if (r.d) {

      // Truncate to the required precision plus five rounding digits.
      r = finalise(r, pr + 5, 1);

      // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
      // the result.
      if (checkRoundingDigits(r.d, pr, rm)) {
        e = pr + 10;

        // Truncate to the increased precision plus five rounding digits.
        r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);

        // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
        if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
          r = finalise(r, pr + 1, 0);
        }
      }
    }

    r.s = s;
    external = true;
    Ctor.rounding = rm;

    return finalise(r, pr, rm);
  };

  /*
   * Return a string representing the value of this Decimal rounded to `sd` significant digits
   * using rounding mode `rounding`.
   *
   * Return exponential notation if `sd` is less than the number of digits necessary to represent
   * the integer part of the value in normal notation.
   *
   * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
   * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   *
   */
  P.toPrecision = function (sd, rm) {
    var str,
        x = this,
        Ctor = x.constructor;

    if (sd === void 0) {
      str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
    } else {
      checkInt32(sd, 1, MAX_DIGITS);

      if (rm === void 0) rm = Ctor.rounding;else checkInt32(rm, 0, 8);

      x = finalise(new Ctor(x), sd, rm);
      str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
    }

    return x.isNeg() && !x.isZero() ? '-' + str : str;
  };

  /*
   * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
   * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
   * omitted.
   *
   * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
   * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   *
   * 'toSD() digits out of range: {sd}'
   * 'toSD() digits not an integer: {sd}'
   * 'toSD() rounding mode not an integer: {rm}'
   * 'toSD() rounding mode out of range: {rm}'
   *
   */
  P.toSignificantDigits = P.toSD = function (sd, rm) {
    var x = this,
        Ctor = x.constructor;

    if (sd === void 0) {
      sd = Ctor.precision;
      rm = Ctor.rounding;
    } else {
      checkInt32(sd, 1, MAX_DIGITS);

      if (rm === void 0) rm = Ctor.rounding;else checkInt32(rm, 0, 8);
    }

    return finalise(new Ctor(x), sd, rm);
  };

  /*
   * Return a string representing the value of this Decimal.
   *
   * Return exponential notation if this Decimal has a positive exponent equal to or greater than
   * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
   *
   */
  P.toString = function () {
    var x = this,
        Ctor = x.constructor,
        str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);

    return x.isNeg() && !x.isZero() ? '-' + str : str;
  };

  /*
   * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
   *
   */
  P.truncated = P.trunc = function () {
    return finalise(new this.constructor(this), this.e + 1, 1);
  };

  /*
   * Return a string representing the value of this Decimal.
   * Unlike `toString`, negative zero will include the minus sign.
   *
   */
  P.valueOf = P.toJSON = function () {
    var x = this,
        Ctor = x.constructor,
        str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);

    return x.isNeg() ? '-' + str : str;
  };

  /*
  // Add aliases to match BigDecimal method names.
  // P.add = P.plus;
  P.subtract = P.minus;
  P.multiply = P.times;
  P.divide = P.div;
  P.remainder = P.mod;
  P.compareTo = P.cmp;
  P.negate = P.neg;
   */

  // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.


  /*
   *  digitsToString           P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
   *                           finiteToString, naturalExponential, naturalLogarithm
   *  checkInt32               P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
   *                           P.toPrecision, P.toSignificantDigits, toStringBinary, random
   *  checkRoundingDigits      P.logarithm, P.toPower, naturalExponential, naturalLogarithm
   *  convertBase              toStringBinary, parseOther
   *  cos                      P.cos
   *  divide                   P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
   *                           P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
   *                           P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
   *                           taylorSeries, atan2, parseOther
   *  finalise                 P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
   *                           P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
   *                           P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
   *                           P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
   *                           P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
   *                           P.truncated, divide, getLn10, getPi, naturalExponential,
   *                           naturalLogarithm, ceil, floor, round, trunc
   *  finiteToString           P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
   *                           toStringBinary
   *  getBase10Exponent        P.minus, P.plus, P.times, parseOther
   *  getLn10                  P.logarithm, naturalLogarithm
   *  getPi                    P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
   *  getPrecision             P.precision, P.toFraction
   *  getZeroString            digitsToString, finiteToString
   *  intPow                   P.toPower, parseOther
   *  isOdd                    toLessThanHalfPi
   *  maxOrMin                 max, min
   *  naturalExponential       P.naturalExponential, P.toPower
   *  naturalLogarithm         P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
   *                           P.toPower, naturalExponential
   *  nonFiniteToString        finiteToString, toStringBinary
   *  parseDecimal             Decimal
   *  parseOther               Decimal
   *  sin                      P.sin
   *  taylorSeries             P.cosh, P.sinh, cos, sin
   *  toLessThanHalfPi         P.cos, P.sin
   *  toStringBinary           P.toBinary, P.toHexadecimal, P.toOctal
   *  truncate                 intPow
   *
   *  Throws:                  P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
   *                           naturalLogarithm, config, parseOther, random, Decimal
   */

  function digitsToString(d) {
    var i,
        k,
        ws,
        indexOfLastWord = d.length - 1,
        str = '',
        w = d[0];

    if (indexOfLastWord > 0) {
      str += w;
      for (i = 1; i < indexOfLastWord; i++) {
        ws = d[i] + '';
        k = LOG_BASE - ws.length;
        if (k) str += getZeroString(k);
        str += ws;
      }

      w = d[i];
      ws = w + '';
      k = LOG_BASE - ws.length;
      if (k) str += getZeroString(k);
    } else if (w === 0) {
      return '0';
    }

    // Remove trailing zeros of last w.
    for (; w % 10 === 0;) {
      w /= 10;
    }return str + w;
  }

  function checkInt32(i, min, max) {
    if (i !== ~~i || i < min || i > max) {
      throw Error(invalidArgument + i);
    }
  }

  /*
   * Check 5 rounding digits if `repeating` is null, 4 otherwise.
   * `repeating == null` if caller is `log` or `pow`,
   * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
   */
  function checkRoundingDigits(d, i, rm, repeating) {
    var di, k, r, rd;

    // Get the length of the first word of the array d.
    for (k = d[0]; k >= 10; k /= 10) {
      --i;
    } // Is the rounding digit in the first word of d?
    if (--i < 0) {
      i += LOG_BASE;
      di = 0;
    } else {
      di = Math.ceil((i + 1) / LOG_BASE);
      i %= LOG_BASE;
    }

    // i is the index (0 - 6) of the rounding digit.
    // E.g. if within the word 3487563 the first rounding digit is 5,
    // then i = 4, k = 1000, rd = 3487563 % 1000 = 563
    k = mathpow(10, LOG_BASE - i);
    rd = d[di] % k | 0;

    if (repeating == null) {
      if (i < 3) {
        if (i == 0) rd = rd / 100 | 0;else if (i == 1) rd = rd / 10 | 0;
        r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
      } else {
        r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
      }
    } else {
      if (i < 4) {
        if (i == 0) rd = rd / 1000 | 0;else if (i == 1) rd = rd / 100 | 0;else if (i == 2) rd = rd / 10 | 0;
        r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
      } else {
        r = ((repeating || rm < 4) && rd + 1 == k || !repeating && rm > 3 && rd + 1 == k / 2) && (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
      }
    }

    return r;
  }

  // Convert string of `baseIn` to an array of numbers of `baseOut`.
  // Eg. convertBase('255', 10, 16) returns [15, 15].
  // Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
  function convertBase(str, baseIn, baseOut) {
    var j,
        arr = [0],
        arrL,
        i = 0,
        strL = str.length;

    for (; i < strL;) {
      for (arrL = arr.length; arrL--;) {
        arr[arrL] *= baseIn;
      }arr[0] += NUMERALS.indexOf(str.charAt(i++));
      for (j = 0; j < arr.length; j++) {
        if (arr[j] > baseOut - 1) {
          if (arr[j + 1] === void 0) arr[j + 1] = 0;
          arr[j + 1] += arr[j] / baseOut | 0;
          arr[j] %= baseOut;
        }
      }
    }

    return arr.reverse();
  }

  /*
   * cos(x) = 1 - x^2/2! + x^4/4! - ...
   * |x| < pi/2
   *
   */
  function cosine(Ctor, x) {
    var k,
        y,
        len = x.d.length;

    // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
    // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1

    // Estimate the optimum number of times to use the argument reduction.
    if (len < 32) {
      k = Math.ceil(len / 3);
      y = Math.pow(4, -k).toString();
    } else {
      k = 16;
      y = '2.3283064365386962890625e-10';
    }

    Ctor.precision += k;

    x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));

    // Reverse argument reduction
    for (var i = k; i--;) {
      var cos2x = x.times(x);
      x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
    }

    Ctor.precision -= k;

    return x;
  }

  /*
   * Perform division in the specified base.
   */
  var divide = function () {

    // Assumes non-zero x and k, and hence non-zero result.
    function multiplyInteger(x, k, base) {
      var temp,
          carry = 0,
          i = x.length;

      for (x = x.slice(); i--;) {
        temp = x[i] * k + carry;
        x[i] = temp % base | 0;
        carry = temp / base | 0;
      }

      if (carry) x.unshift(carry);

      return x;
    }

    function compare(a, b, aL, bL) {
      var i, r;

      if (aL != bL) {
        r = aL > bL ? 1 : -1;
      } else {
        for (i = r = 0; i < aL; i++) {
          if (a[i] != b[i]) {
            r = a[i] > b[i] ? 1 : -1;
            break;
          }
        }
      }

      return r;
    }

    function subtract(a, b, aL, base) {
      var i = 0;

      // Subtract b from a.
      for (; aL--;) {
        a[aL] -= i;
        i = a[aL] < b[aL] ? 1 : 0;
        a[aL] = i * base + a[aL] - b[aL];
      }

      // Remove leading zeros.
      for (; !a[0] && a.length > 1;) {
        a.shift();
      }
    }

    return function (x, y, pr, rm, dp, base) {
      var cmp,
          e,
          i,
          k,
          logBase,
          more,
          prod,
          prodL,
          q,
          qd,
          rem,
          remL,
          rem0,
          sd,
          t,
          xi,
          xL,
          yd0,
          yL,
          yz,
          Ctor = x.constructor,
          sign = x.s == y.s ? 1 : -1,
          xd = x.d,
          yd = y.d;

      // Either NaN, Infinity or 0?
      if (!xd || !xd[0] || !yd || !yd[0]) {

        return new Ctor( // Return NaN if either NaN, or both Infinity or 0.
        !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :

        // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
        xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
      }

      if (base) {
        logBase = 1;
        e = x.e - y.e;
      } else {
        base = BASE;
        logBase = LOG_BASE;
        e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
      }

      yL = yd.length;
      xL = xd.length;
      q = new Ctor(sign);
      qd = q.d = [];

      // Result exponent may be one less than e.
      // The digit array of a Decimal from toStringBinary may have trailing zeros.
      for (i = 0; yd[i] == (xd[i] || 0); i++) {}

      if (yd[i] > (xd[i] || 0)) e--;

      if (pr == null) {
        sd = pr = Ctor.precision;
        rm = Ctor.rounding;
      } else if (dp) {
        sd = pr + (x.e - y.e) + 1;
      } else {
        sd = pr;
      }

      if (sd < 0) {
        qd.push(1);
        more = true;
      } else {

        // Convert precision in number of base 10 digits to base 1e7 digits.
        sd = sd / logBase + 2 | 0;
        i = 0;

        // divisor < 1e7
        if (yL == 1) {
          k = 0;
          yd = yd[0];
          sd++;

          // k is the carry.
          for (; (i < xL || k) && sd--; i++) {
            t = k * base + (xd[i] || 0);
            qd[i] = t / yd | 0;
            k = t % yd | 0;
          }

          more = k || i < xL;

          // divisor >= 1e7
        } else {

          // Normalise xd and yd so highest order digit of yd is >= base/2
          k = base / (yd[0] + 1) | 0;

          if (k > 1) {
            yd = multiplyInteger(yd, k, base);
            xd = multiplyInteger(xd, k, base);
            yL = yd.length;
            xL = xd.length;
          }

          xi = yL;
          rem = xd.slice(0, yL);
          remL = rem.length;

          // Add zeros to make remainder as long as divisor.
          for (; remL < yL;) {
            rem[remL++] = 0;
          }yz = yd.slice();
          yz.unshift(0);
          yd0 = yd[0];

          if (yd[1] >= base / 2) ++yd0;

          do {
            k = 0;

            // Compare divisor and remainder.
            cmp = compare(yd, rem, yL, remL);

            // If divisor < remainder.
            if (cmp < 0) {

              // Calculate trial digit, k.
              rem0 = rem[0];
              if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);

              // k will be how many times the divisor goes into the current remainder.
              k = rem0 / yd0 | 0;

              //  Algorithm:
              //  1. product = divisor * trial digit (k)
              //  2. if product > remainder: product -= divisor, k--
              //  3. remainder -= product
              //  4. if product was < remainder at 2:
              //    5. compare new remainder and divisor
              //    6. If remainder > divisor: remainder -= divisor, k++

              if (k > 1) {
                if (k >= base) k = base - 1;

                // product = divisor * trial digit.
                prod = multiplyInteger(yd, k, base);
                prodL = prod.length;
                remL = rem.length;

                // Compare product and remainder.
                cmp = compare(prod, rem, prodL, remL);

                // product > remainder.
                if (cmp == 1) {
                  k--;

                  // Subtract divisor from product.
                  subtract(prod, yL < prodL ? yz : yd, prodL, base);
                }
              } else {

                // cmp is -1.
                // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
                // to avoid it. If k is 1 there is a need to compare yd and rem again below.
                if (k == 0) cmp = k = 1;
                prod = yd.slice();
              }

              prodL = prod.length;
              if (prodL < remL) prod.unshift(0);

              // Subtract product from remainder.
              subtract(rem, prod, remL, base);

              // If product was < previous remainder.
              if (cmp == -1) {
                remL = rem.length;

                // Compare divisor and new remainder.
                cmp = compare(yd, rem, yL, remL);

                // If divisor < new remainder, subtract divisor from remainder.
                if (cmp < 1) {
                  k++;

                  // Subtract divisor from remainder.
                  subtract(rem, yL < remL ? yz : yd, remL, base);
                }
              }

              remL = rem.length;
            } else if (cmp === 0) {
              k++;
              rem = [0];
            } // if cmp === 1, k will be 0

            // Add the next digit, k, to the result array.
            qd[i++] = k;

            // Update the remainder.
            if (cmp && rem[0]) {
              rem[remL++] = xd[xi] || 0;
            } else {
              rem = [xd[xi]];
              remL = 1;
            }
          } while ((xi++ < xL || rem[0] !== void 0) && sd--);

          more = rem[0] !== void 0;
        }

        // Leading zero?
        if (!qd[0]) qd.shift();
      }

      // logBase is 1 when divide is being used for base conversion.
      if (logBase == 1) {
        q.e = e;
        inexact = more;
      } else {

        // To calculate q.e, first get the number of digits of qd[0].
        for (i = 1, k = qd[0]; k >= 10; k /= 10) {
          i++;
        }q.e = i + e * logBase - 1;

        finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
      }

      return q;
    };
  }();

  /*
   * Round `x` to `sd` significant digits using rounding mode `rm`.
   * Check for over/under-flow.
   */
  function finalise(x, sd, rm, isTruncated) {
    var digits,
        i,
        j,
        k,
        rd,
        roundUp,
        w,
        xd,
        xdi,
        Ctor = x.constructor;

    // Don't round if sd is null or undefined.
    out: if (sd != null) {
      xd = x.d;

      // Infinity/NaN.
      if (!xd) return x;

      // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
      // w: the word of xd containing rd, a base 1e7 number.
      // xdi: the index of w within xd.
      // digits: the number of digits of w.
      // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
      // they had leading zeros)
      // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).

      // Get the length of the first word of the digits array xd.
      for (digits = 1, k = xd[0]; k >= 10; k /= 10) {
        digits++;
      }i = sd - digits;

      // Is the rounding digit in the first word of xd?
      if (i < 0) {
        i += LOG_BASE;
        j = sd;
        w = xd[xdi = 0];

        // Get the rounding digit at index j of w.
        rd = w / mathpow(10, digits - j - 1) % 10 | 0;
      } else {
        xdi = Math.ceil((i + 1) / LOG_BASE);
        k = xd.length;
        if (xdi >= k) {
          if (isTruncated) {

            // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
            for (; k++ <= xdi;) {
              xd.push(0);
            }w = rd = 0;
            digits = 1;
            i %= LOG_BASE;
            j = i - LOG_BASE + 1;
          } else {
            break out;
          }
        } else {
          w = k = xd[xdi];

          // Get the number of digits of w.
          for (digits = 1; k >= 10; k /= 10) {
            digits++;
          } // Get the index of rd within w.
          i %= LOG_BASE;

          // Get the index of rd within w, adjusted for leading zeros.
          // The number of leading zeros of w is given by LOG_BASE - digits.
          j = i - LOG_BASE + digits;

          // Get the rounding digit at index j of w.
          rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
        }
      }

      // Are there any non-zero digits after the rounding digit?
      isTruncated = isTruncated || sd < 0 || xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));

      // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
      // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
      // will give 714.

      roundUp = rm < 4 ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&

      // Check whether the digit to the left of the rounding digit is odd.
      (i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7));

      if (sd < 1 || !xd[0]) {
        xd.length = 0;
        if (roundUp) {

          // Convert sd to decimal places.
          sd -= x.e + 1;

          // 1, 0.1, 0.01, 0.001, 0.0001 etc.
          xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
          x.e = -sd || 0;
        } else {

          // Zero.
          xd[0] = x.e = 0;
        }

        return x;
      }

      // Remove excess digits.
      if (i == 0) {
        xd.length = xdi;
        k = 1;
        xdi--;
      } else {
        xd.length = xdi + 1;
        k = mathpow(10, LOG_BASE - i);

        // E.g. 56700 becomes 56000 if 7 is the rounding digit.
        // j > 0 means i > number of leading zeros of w.
        xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
      }

      if (roundUp) {
        for (;;) {

          // Is the digit to be rounded up in the first word of xd?
          if (xdi == 0) {

            // i will be the length of xd[0] before k is added.
            for (i = 1, j = xd[0]; j >= 10; j /= 10) {
              i++;
            }j = xd[0] += k;
            for (k = 1; j >= 10; j /= 10) {
              k++;
            } // if i != k the length has increased.
            if (i != k) {
              x.e++;
              if (xd[0] == BASE) xd[0] = 1;
            }

            break;
          } else {
            xd[xdi] += k;
            if (xd[xdi] != BASE) break;
            xd[xdi--] = 0;
            k = 1;
          }
        }
      }

      // Remove trailing zeros.
      for (i = xd.length; xd[--i] === 0;) {
        xd.pop();
      }
    }

    if (external) {

      // Overflow?
      if (x.e > Ctor.maxE) {

        // Infinity.
        x.d = null;
        x.e = NaN;

        // Underflow?
      } else if (x.e < Ctor.minE) {

        // Zero.
        x.e = 0;
        x.d = [0];
        // Ctor.underflow = true;
      } // else Ctor.underflow = false;
    }

    return x;
  }

  function finiteToString(x, isExp, sd) {
    if (!x.isFinite()) return nonFiniteToString(x);
    var k,
        e = x.e,
        str = digitsToString(x.d),
        len = str.length;

    if (isExp) {
      if (sd && (k = sd - len) > 0) {
        str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
      } else if (len > 1) {
        str = str.charAt(0) + '.' + str.slice(1);
      }

      str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
    } else if (e < 0) {
      str = '0.' + getZeroString(-e - 1) + str;
      if (sd && (k = sd - len) > 0) str += getZeroString(k);
    } else if (e >= len) {
      str += getZeroString(e + 1 - len);
      if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
    } else {
      if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
      if (sd && (k = sd - len) > 0) {
        if (e + 1 === len) str += '.';
        str += getZeroString(k);
      }
    }

    return str;
  }

  // Calculate the base 10 exponent from the base 1e7 exponent.
  function getBase10Exponent(digits, e) {
    var w = digits[0];

    // Add the number of digits of the first word of the digits array.
    for (e *= LOG_BASE; w >= 10; w /= 10) {
      e++;
    }return e;
  }

  function getLn10(Ctor, sd, pr) {
    if (sd > LN10_PRECISION) {

      // Reset global state in case the exception is caught.
      external = true;
      if (pr) Ctor.precision = pr;
      throw Error(precisionLimitExceeded);
    }
    return finalise(new Ctor(LN10), sd, 1, true);
  }

  function getPi(Ctor, sd, rm) {
    if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
    return finalise(new Ctor(PI), sd, rm, true);
  }

  function getPrecision(digits) {
    var w = digits.length - 1,
        len = w * LOG_BASE + 1;

    w = digits[w];

    // If non-zero...
    if (w) {

      // Subtract the number of trailing zeros of the last word.
      for (; w % 10 == 0; w /= 10) {
        len--;
      } // Add the number of digits of the first word.
      for (w = digits[0]; w >= 10; w /= 10) {
        len++;
      }
    }

    return len;
  }

  function getZeroString(k) {
    var zs = '';
    for (; k--;) {
      zs += '0';
    }return zs;
  }

  /*
   * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
   * integer of type number.
   *
   * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
   *
   */
  function intPow(Ctor, x, n, pr) {
    var isTruncated,
        r = new Ctor(1),


    // Max n of 9007199254740991 takes 53 loop iterations.
    // Maximum digits array length; leaves [28, 34] guard digits.
    k = Math.ceil(pr / LOG_BASE + 4);

    external = false;

    for (;;) {
      if (n % 2) {
        r = r.times(x);
        if (truncate(r.d, k)) isTruncated = true;
      }

      n = mathfloor(n / 2);
      if (n === 0) {

        // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
        n = r.d.length - 1;
        if (isTruncated && r.d[n] === 0) ++r.d[n];
        break;
      }

      x = x.times(x);
      truncate(x.d, k);
    }

    external = true;

    return r;
  }

  function isOdd(n) {
    return n.d[n.d.length - 1] & 1;
  }

  /*
   * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
   */
  function maxOrMin(Ctor, args, ltgt) {
    var y,
        x = new Ctor(args[0]),
        i = 0;

    for (; ++i < args.length;) {
      y = new Ctor(args[i]);
      if (!y.s) {
        x = y;
        break;
      } else if (x[ltgt](y)) {
        x = y;
      }
    }

    return x;
  }

  /*
   * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
   * digits.
   *
   * Taylor/Maclaurin series.
   *
   * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
   *
   * Argument reduction:
   *   Repeat x = x / 32, k += 5, until |x| < 0.1
   *   exp(x) = exp(x / 2^k)^(2^k)
   *
   * Previously, the argument was initially reduced by
   * exp(x) = exp(r) * 10^k  where r = x - k * ln10, k = floor(x / ln10)
   * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
   * found to be slower than just dividing repeatedly by 32 as above.
   *
   * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
   * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
   * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
   *
   *  exp(Infinity)  = Infinity
   *  exp(-Infinity) = 0
   *  exp(NaN)       = NaN
   *  exp(±0)        = 1
   *
   *  exp(x) is non-terminating for any finite, non-zero x.
   *
   *  The result will always be correctly rounded.
   *
   */
  function naturalExponential(x, sd) {
    var denominator,
        guard,
        j,
        pow,
        sum,
        t,
        wpr,
        rep = 0,
        i = 0,
        k = 0,
        Ctor = x.constructor,
        rm = Ctor.rounding,
        pr = Ctor.precision;

    // 0/NaN/Infinity?
    if (!x.d || !x.d[0] || x.e > 17) {

      return new Ctor(x.d ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 : x.s ? x.s < 0 ? 0 : x : 0 / 0);
    }

    if (sd == null) {
      external = false;
      wpr = pr;
    } else {
      wpr = sd;
    }

    t = new Ctor(0.03125);

    // while abs(x) >= 0.1
    while (x.e > -2) {

      // x = x / 2^5
      x = x.times(t);
      k += 5;
    }

    // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
    // necessary to ensure the first 4 rounding digits are correct.
    guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
    wpr += guard;
    denominator = pow = sum = new Ctor(1);
    Ctor.precision = wpr;

    for (;;) {
      pow = finalise(pow.times(x), wpr, 1);
      denominator = denominator.times(++i);
      t = sum.plus(divide(pow, denominator, wpr, 1));

      if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
        j = k;
        while (j--) {
          sum = finalise(sum.times(sum), wpr, 1);
        } // Check to see if the first 4 rounding digits are [49]999.
        // If so, repeat the summation with a higher precision, otherwise
        // e.g. with precision: 18, rounding: 1
        // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
        // `wpr - guard` is the index of first rounding digit.
        if (sd == null) {

          if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
            Ctor.precision = wpr += 10;
            denominator = pow = t = new Ctor(1);
            i = 0;
            rep++;
          } else {
            return finalise(sum, Ctor.precision = pr, rm, external = true);
          }
        } else {
          Ctor.precision = pr;
          return sum;
        }
      }

      sum = t;
    }
  }

  /*
   * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
   * digits.
   *
   *  ln(-n)        = NaN
   *  ln(0)         = -Infinity
   *  ln(-0)        = -Infinity
   *  ln(1)         = 0
   *  ln(Infinity)  = Infinity
   *  ln(-Infinity) = NaN
   *  ln(NaN)       = NaN
   *
   *  ln(n) (n != 1) is non-terminating.
   *
   */
  function naturalLogarithm(y, sd) {
    var c,
        c0,
        denominator,
        e,
        numerator,
        rep,
        sum,
        t,
        wpr,
        x1,
        x2,
        n = 1,
        guard = 10,
        x = y,
        xd = x.d,
        Ctor = x.constructor,
        rm = Ctor.rounding,
        pr = Ctor.precision;

    // Is x negative or Infinity, NaN, 0 or 1?
    if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
      return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
    }

    if (sd == null) {
      external = false;
      wpr = pr;
    } else {
      wpr = sd;
    }

    Ctor.precision = wpr += guard;
    c = digitsToString(xd);
    c0 = c.charAt(0);

    if (Math.abs(e = x.e) < 1.5e15) {

      // Argument reduction.
      // The series converges faster the closer the argument is to 1, so using
      // ln(a^b) = b * ln(a),   ln(a) = ln(a^b) / b
      // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
      // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
      // later be divided by this number, then separate out the power of 10 using
      // ln(a*10^b) = ln(a) + b*ln(10).

      // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
      //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
      // max n is 6 (gives 0.7 - 1.3)
      while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
        x = x.times(y);
        c = digitsToString(x.d);
        c0 = c.charAt(0);
        n++;
      }

      e = x.e;

      if (c0 > 1) {
        x = new Ctor('0.' + c);
        e++;
      } else {
        x = new Ctor(c0 + '.' + c.slice(1));
      }
    } else {

      // The argument reduction method above may result in overflow if the argument y is a massive
      // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
      // function using ln(x*10^e) = ln(x) + e*ln(10).
      t = getLn10(Ctor, wpr + 2, pr).times(e + '');
      x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
      Ctor.precision = pr;

      return sd == null ? finalise(x, pr, rm, external = true) : x;
    }

    // x1 is x reduced to a value near 1.
    x1 = x;

    // Taylor series.
    // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
    // where x = (y - 1)/(y + 1)    (|x| < 1)
    sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
    x2 = finalise(x.times(x), wpr, 1);
    denominator = 3;

    for (;;) {
      numerator = finalise(numerator.times(x2), wpr, 1);
      t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));

      if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
        sum = sum.times(2);

        // Reverse the argument reduction. Check that e is not 0 because, besides preventing an
        // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
        if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
        sum = divide(sum, new Ctor(n), wpr, 1);

        // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
        // been repeated previously) and the first 4 rounding digits 9999?
        // If so, restart the summation with a higher precision, otherwise
        // e.g. with precision: 12, rounding: 1
        // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
        // `wpr - guard` is the index of first rounding digit.
        if (sd == null) {
          if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
            Ctor.precision = wpr += guard;
            t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
            x2 = finalise(x.times(x), wpr, 1);
            denominator = rep = 1;
          } else {
            return finalise(sum, Ctor.precision = pr, rm, external = true);
          }
        } else {
          Ctor.precision = pr;
          return sum;
        }
      }

      sum = t;
      denominator += 2;
    }
  }

  // ±Infinity, NaN.
  function nonFiniteToString(x) {
    // Unsigned.
    return String(x.s * x.s / 0);
  }

  /*
   * Parse the value of a new Decimal `x` from string `str`.
   */
  function parseDecimal(x, str) {
    var e, i, len;

    // Decimal point?
    if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');

    // Exponential form?
    if ((i = str.search(/e/i)) > 0) {

      // Determine exponent.
      if (e < 0) e = i;
      e += +str.slice(i + 1);
      str = str.substring(0, i);
    } else if (e < 0) {

      // Integer.
      e = str.length;
    }

    // Determine leading zeros.
    for (i = 0; str.charCodeAt(i) === 48; i++) {}

    // Determine trailing zeros.
    for (len = str.length; str.charCodeAt(len - 1) === 48; --len) {}
    str = str.slice(i, len);

    if (str) {
      len -= i;
      x.e = e = e - i - 1;
      x.d = [];

      // Transform base

      // e is the base 10 exponent.
      // i is where to slice str to get the first word of the digits array.
      i = (e + 1) % LOG_BASE;
      if (e < 0) i += LOG_BASE;

      if (i < len) {
        if (i) x.d.push(+str.slice(0, i));
        for (len -= LOG_BASE; i < len;) {
          x.d.push(+str.slice(i, i += LOG_BASE));
        }str = str.slice(i);
        i = LOG_BASE - str.length;
      } else {
        i -= len;
      }

      for (; i--;) {
        str += '0';
      }x.d.push(+str);

      if (external) {

        // Overflow?
        if (x.e > x.constructor.maxE) {

          // Infinity.
          x.d = null;
          x.e = NaN;

          // Underflow?
        } else if (x.e < x.constructor.minE) {

          // Zero.
          x.e = 0;
          x.d = [0];
          // x.constructor.underflow = true;
        } // else x.constructor.underflow = false;
      }
    } else {

      // Zero.
      x.e = 0;
      x.d = [0];
    }

    return x;
  }

  /*
   * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
   */
  function parseOther(x, str) {
    var base, Ctor, divisor, i, isFloat, len, p, xd, xe;

    if (str === 'Infinity' || str === 'NaN') {
      if (!+str) x.s = NaN;
      x.e = NaN;
      x.d = null;
      return x;
    }

    if (isHex.test(str)) {
      base = 16;
      str = str.toLowerCase();
    } else if (isBinary.test(str)) {
      base = 2;
    } else if (isOctal.test(str)) {
      base = 8;
    } else {
      throw Error(invalidArgument + str);
    }

    // Is there a binary exponent part?
    i = str.search(/p/i);

    if (i > 0) {
      p = +str.slice(i + 1);
      str = str.substring(2, i);
    } else {
      str = str.slice(2);
    }

    // Convert `str` as an integer then divide the result by `base` raised to a power such that the
    // fraction part will be restored.
    i = str.indexOf('.');
    isFloat = i >= 0;
    Ctor = x.constructor;

    if (isFloat) {
      str = str.replace('.', '');
      len = str.length;
      i = len - i;

      // log[10](16) = 1.2041... , log[10](88) = 1.9444....
      divisor = intPow(Ctor, new Ctor(base), i, i * 2);
    }

    xd = convertBase(str, base, BASE);
    xe = xd.length - 1;

    // Remove trailing zeros.
    for (i = xe; xd[i] === 0; --i) {
      xd.pop();
    }if (i < 0) return new Ctor(x.s * 0);
    x.e = getBase10Exponent(xd, xe);
    x.d = xd;
    external = false;

    // At what precision to perform the division to ensure exact conversion?
    // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
    // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
    // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
    // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
    // Therefore using 4 * the number of digits of str will always be enough.
    if (isFloat) x = divide(x, divisor, len * 4);

    // Multiply by the binary exponent part if present.
    if (p) x = x.times(Math.abs(p) < 54 ? Math.pow(2, p) : Decimal.pow(2, p));
    external = true;

    return x;
  }

  /*
   * sin(x) = x - x^3/3! + x^5/5! - ...
   * |x| < pi/2
   *
   */
  function sine(Ctor, x) {
    var k,
        len = x.d.length;

    if (len < 3) return taylorSeries(Ctor, 2, x, x);

    // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
    // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
    // and  sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))

    // Estimate the optimum number of times to use the argument reduction.
    k = 1.4 * Math.sqrt(len);
    k = k > 16 ? 16 : k | 0;

    // Max k before Math.pow precision loss is 22
    x = x.times(Math.pow(5, -k));
    x = taylorSeries(Ctor, 2, x, x);

    // Reverse argument reduction
    var sin2_x,
        d5 = new Ctor(5),
        d16 = new Ctor(16),
        d20 = new Ctor(20);
    for (; k--;) {
      sin2_x = x.times(x);
      x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
    }

    return x;
  }

  // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
  function taylorSeries(Ctor, n, x, y, isHyperbolic) {
    var j,
        t,
        u,
        x2,
        i = 1,
        pr = Ctor.precision,
        k = Math.ceil(pr / LOG_BASE);

    external = false;
    x2 = x.times(x);
    u = new Ctor(y);

    for (;;) {
      t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
      u = isHyperbolic ? y.plus(t) : y.minus(t);
      y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
      t = u.plus(y);

      if (t.d[k] !== void 0) {
        for (j = k; t.d[j] === u.d[j] && j--;) {}
        if (j == -1) break;
      }

      j = u;
      u = y;
      y = t;
      t = j;
      i++;
    }

    external = true;
    t.d.length = k + 1;

    return t;
  }

  // Return the absolute value of `x` reduced to less than or equal to half pi.
  function toLessThanHalfPi(Ctor, x) {
    var t,
        isNeg = x.s < 0,
        pi = getPi(Ctor, Ctor.precision, 1),
        halfPi = pi.times(0.5);

    x = x.abs();

    if (x.lte(halfPi)) {
      quadrant = isNeg ? 4 : 1;
      return x;
    }

    t = x.divToInt(pi);

    if (t.isZero()) {
      quadrant = isNeg ? 3 : 2;
    } else {
      x = x.minus(t.times(pi));

      // 0 <= x < pi
      if (x.lte(halfPi)) {
        quadrant = isOdd(t) ? isNeg ? 2 : 3 : isNeg ? 4 : 1;
        return x;
      }

      quadrant = isOdd(t) ? isNeg ? 1 : 4 : isNeg ? 3 : 2;
    }

    return x.minus(pi).abs();
  }

  /*
   * Return the value of Decimal `x` as a string in base `baseOut`.
   *
   * If the optional `sd` argument is present include a binary exponent suffix.
   */
  function toStringBinary(x, baseOut, sd, rm) {
    var base,
        e,
        i,
        k,
        len,
        roundUp,
        str,
        xd,
        y,
        Ctor = x.constructor,
        isExp = sd !== void 0;

    if (isExp) {
      checkInt32(sd, 1, MAX_DIGITS);
      if (rm === void 0) rm = Ctor.rounding;else checkInt32(rm, 0, 8);
    } else {
      sd = Ctor.precision;
      rm = Ctor.rounding;
    }

    if (!x.isFinite()) {
      str = nonFiniteToString(x);
    } else {
      str = finiteToString(x);
      i = str.indexOf('.');

      // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
      // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
      // minBinaryExponent = floor(decimalExponent * log[2](10))
      // log[2](10) = 3.321928094887362347870319429489390175864

      if (isExp) {
        base = 2;
        if (baseOut == 16) {
          sd = sd * 4 - 3;
        } else if (baseOut == 8) {
          sd = sd * 3 - 2;
        }
      } else {
        base = baseOut;
      }

      // Convert the number as an integer then divide the result by its base raised to a power such
      // that the fraction part will be restored.

      // Non-integer.
      if (i >= 0) {
        str = str.replace('.', '');
        y = new Ctor(1);
        y.e = str.length - i;
        y.d = convertBase(finiteToString(y), 10, base);
        y.e = y.d.length;
      }

      xd = convertBase(str, 10, base);
      e = len = xd.length;

      // Remove trailing zeros.
      for (; xd[--len] == 0;) {
        xd.pop();
      }if (!xd[0]) {
        str = isExp ? '0p+0' : '0';
      } else {
        if (i < 0) {
          e--;
        } else {
          x = new Ctor(x);
          x.d = xd;
          x.e = e;
          x = divide(x, y, sd, rm, 0, base);
          xd = x.d;
          e = x.e;
          roundUp = inexact;
        }

        // The rounding digit, i.e. the digit after the digit that may be rounded up.
        i = xd[sd];
        k = base / 2;
        roundUp = roundUp || xd[sd + 1] !== void 0;

        roundUp = rm < 4 ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || rm === (x.s < 0 ? 8 : 7));

        xd.length = sd;

        if (roundUp) {

          // Rounding up may mean the previous digit has to be rounded up and so on.
          for (; ++xd[--sd] > base - 1;) {
            xd[sd] = 0;
            if (!sd) {
              ++e;
              xd.unshift(1);
            }
          }
        }

        // Determine trailing zeros.
        for (len = xd.length; !xd[len - 1]; --len) {}

        // E.g. [4, 11, 15] becomes 4bf.
        for (i = 0, str = ''; i < len; i++) {
          str += NUMERALS.charAt(xd[i]);
        } // Add binary exponent suffix?
        if (isExp) {
          if (len > 1) {
            if (baseOut == 16 || baseOut == 8) {
              i = baseOut == 16 ? 4 : 3;
              for (--len; len % i; len++) {
                str += '0';
              }xd = convertBase(str, base, baseOut);
              for (len = xd.length; !xd[len - 1]; --len) {}

              // xd[0] will always be be 1
              for (i = 1, str = '1.'; i < len; i++) {
                str += NUMERALS.charAt(xd[i]);
              }
            } else {
              str = str.charAt(0) + '.' + str.slice(1);
            }
          }

          str = str + (e < 0 ? 'p' : 'p+') + e;
        } else if (e < 0) {
          for (; ++e;) {
            str = '0' + str;
          }str = '0.' + str;
        } else {
          if (++e > len) for (e -= len; e--;) {
            str += '0';
          } else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
        }
      }

      str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
    }

    return x.s < 0 ? '-' + str : str;
  }

  // Does not strip trailing zeros.
  function truncate(arr, len) {
    if (arr.length > len) {
      arr.length = len;
      return true;
    }
  }

  // Decimal methods


  /*
   *  abs
   *  acos
   *  acosh
   *  add
   *  asin
   *  asinh
   *  atan
   *  atanh
   *  atan2
   *  cbrt
   *  ceil
   *  clone
   *  config
   *  cos
   *  cosh
   *  div
   *  exp
   *  floor
   *  hypot
   *  ln
   *  log
   *  log2
   *  log10
   *  max
   *  min
   *  mod
   *  mul
   *  pow
   *  random
   *  round
   *  set
   *  sign
   *  sin
   *  sinh
   *  sqrt
   *  sub
   *  tan
   *  tanh
   *  trunc
   */

  /*
   * Return a new Decimal whose value is the absolute value of `x`.
   *
   * x {number|string|Decimal}
   *
   */
  function abs(x) {
    return new this(x).abs();
  }

  /*
   * Return a new Decimal whose value is the arccosine in radians of `x`.
   *
   * x {number|string|Decimal}
   *
   */
  function acos(x) {
    return new this(x).acos();
  }

  /*
   * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
   * `precision` significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal} A value in radians.
   *
   */
  function acosh(x) {
    return new this(x).acosh();
  }

  /*
   * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
   * digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   * y {number|string|Decimal}
   *
   */
  function add(x, y) {
    return new this(x).plus(y);
  }

  /*
   * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   *
   */
  function asin(x) {
    return new this(x).asin();
  }

  /*
   * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
   * `precision` significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal} A value in radians.
   *
   */
  function asinh(x) {
    return new this(x).asinh();
  }

  /*
   * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   *
   */
  function atan(x) {
    return new this(x).atan();
  }

  /*
   * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
   * `precision` significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal} A value in radians.
   *
   */
  function atanh(x) {
    return new this(x).atanh();
  }

  /*
   * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
   * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
   *
   * Domain: [-Infinity, Infinity]
   * Range: [-pi, pi]
   *
   * y {number|string|Decimal} The y-coordinate.
   * x {number|string|Decimal} The x-coordinate.
   *
   * atan2(±0, -0)               = ±pi
   * atan2(±0, +0)               = ±0
   * atan2(±0, -x)               = ±pi for x > 0
   * atan2(±0, x)                = ±0 for x > 0
   * atan2(-y, ±0)               = -pi/2 for y > 0
   * atan2(y, ±0)                = pi/2 for y > 0
   * atan2(±y, -Infinity)        = ±pi for finite y > 0
   * atan2(±y, +Infinity)        = ±0 for finite y > 0
   * atan2(±Infinity, x)         = ±pi/2 for finite x
   * atan2(±Infinity, -Infinity) = ±3*pi/4
   * atan2(±Infinity, +Infinity) = ±pi/4
   * atan2(NaN, x) = NaN
   * atan2(y, NaN) = NaN
   *
   */
  function atan2(y, x) {
    y = new this(y);
    x = new this(x);
    var r,
        pr = this.precision,
        rm = this.rounding,
        wpr = pr + 4;

    // Either NaN
    if (!y.s || !x.s) {
      r = new this(NaN);

      // Both ±Infinity
    } else if (!y.d && !x.d) {
      r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
      r.s = y.s;

      // x is ±Infinity or y is ±0
    } else if (!x.d || y.isZero()) {
      r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
      r.s = y.s;

      // y is ±Infinity or x is ±0
    } else if (!y.d || x.isZero()) {
      r = getPi(this, wpr, 1).times(0.5);
      r.s = y.s;

      // Both non-zero and finite
    } else if (x.s < 0) {
      this.precision = wpr;
      this.rounding = 1;
      r = this.atan(divide(y, x, wpr, 1));
      x = getPi(this, wpr, 1);
      this.precision = pr;
      this.rounding = rm;
      r = y.s < 0 ? r.minus(x) : r.plus(x);
    } else {
      r = this.atan(divide(y, x, wpr, 1));
    }

    return r;
  }

  /*
   * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
   * digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   *
   */
  function cbrt(x) {
    return new this(x).cbrt();
  }

  /*
   * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
   *
   * x {number|string|Decimal}
   *
   */
  function ceil(x) {
    return finalise(x = new this(x), x.e + 1, 2);
  }

  /*
   * Configure global settings for a Decimal constructor.
   *
   * `obj` is an object with one or more of the following properties,
   *
   *   precision  {number}
   *   rounding   {number}
   *   toExpNeg   {number}
   *   toExpPos   {number}
   *   maxE       {number}
   *   minE       {number}
   *   modulo     {number}
   *   crypto     {boolean|number}
   *   defaults   {true}
   *
   * E.g. Decimal.config({ precision: 20, rounding: 4 })
   *
   */
  function config(obj) {
    if (!obj || (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object') throw Error(decimalError + 'Object expected');
    var i,
        p,
        v,
        useDefaults = obj.defaults === true,
        ps = ['precision', 1, MAX_DIGITS, 'rounding', 0, 8, 'toExpNeg', -EXP_LIMIT, 0, 'toExpPos', 0, EXP_LIMIT, 'maxE', 0, EXP_LIMIT, 'minE', -EXP_LIMIT, 0, 'modulo', 0, 9];

    for (i = 0; i < ps.length; i += 3) {
      if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];
      if ((v = obj[p]) !== void 0) {
        if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;else throw Error(invalidArgument + p + ': ' + v);
      }
    }

    if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];
    if ((v = obj[p]) !== void 0) {
      if (v === true || v === false || v === 0 || v === 1) {
        if (v) {
          if (typeof crypto != 'undefined' && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
            this[p] = true;
          } else {
            throw Error(cryptoUnavailable);
          }
        } else {
          this[p] = false;
        }
      } else {
        throw Error(invalidArgument + p + ': ' + v);
      }
    }

    return this;
  }

  /*
   * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
   * digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal} A value in radians.
   *
   */
  function cos(x) {
    return new this(x).cos();
  }

  /*
   * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
   * significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal} A value in radians.
   *
   */
  function cosh(x) {
    return new this(x).cosh();
  }

  /*
   * Create and return a Decimal constructor with the same configuration properties as this Decimal
   * constructor.
   *
   */
  function clone(obj) {
    var i, p, ps;

    /*
     * The Decimal constructor and exported function.
     * Return a new Decimal instance.
     *
     * v {number|string|Decimal} A numeric value.
     *
     */
    function Decimal(v) {
      var e,
          i,
          t,
          x = this;

      // Decimal called without new.
      if (!(x instanceof Decimal)) return new Decimal(v);

      // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
      // which points to Object.
      x.constructor = Decimal;

      // Duplicate.
      if (v instanceof Decimal) {
        x.s = v.s;
        x.e = v.e;
        x.d = (v = v.d) ? v.slice() : v;
        return;
      }

      t = typeof v === 'undefined' ? 'undefined' : _typeof(v);

      if (t === 'number') {
        if (v === 0) {
          x.s = 1 / v < 0 ? -1 : 1;
          x.e = 0;
          x.d = [0];
          return;
        }

        if (v < 0) {
          v = -v;
          x.s = -1;
        } else {
          x.s = 1;
        }

        // Fast path for small integers.
        if (v === ~~v && v < 1e7) {
          for (e = 0, i = v; i >= 10; i /= 10) {
            e++;
          }x.e = e;
          x.d = [v];
          return;

          // Infinity, NaN.
        } else if (v * 0 !== 0) {
          if (!v) x.s = NaN;
          x.e = NaN;
          x.d = null;
          return;
        }

        return parseDecimal(x, v.toString());
      } else if (t !== 'string') {
        throw Error(invalidArgument + v);
      }

      // Minus sign?
      if (v.charCodeAt(0) === 45) {
        v = v.slice(1);
        x.s = -1;
      } else {
        x.s = 1;
      }

      return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
    }

    Decimal.prototype = P;

    Decimal.ROUND_UP = 0;
    Decimal.ROUND_DOWN = 1;
    Decimal.ROUND_CEIL = 2;
    Decimal.ROUND_FLOOR = 3;
    Decimal.ROUND_HALF_UP = 4;
    Decimal.ROUND_HALF_DOWN = 5;
    Decimal.ROUND_HALF_EVEN = 6;
    Decimal.ROUND_HALF_CEIL = 7;
    Decimal.ROUND_HALF_FLOOR = 8;
    Decimal.EUCLID = 9;

    Decimal.config = Decimal.set = config;
    Decimal.clone = clone;
    Decimal.isDecimal = isDecimalInstance;

    Decimal.abs = abs;
    Decimal.acos = acos;
    Decimal.acosh = acosh; // ES6
    Decimal.add = add;
    Decimal.asin = asin;
    Decimal.asinh = asinh; // ES6
    Decimal.atan = atan;
    Decimal.atanh = atanh; // ES6
    Decimal.atan2 = atan2;
    Decimal.cbrt = cbrt; // ES6
    Decimal.ceil = ceil;
    Decimal.cos = cos;
    Decimal.cosh = cosh; // ES6
    Decimal.div = div;
    Decimal.exp = exp;
    Decimal.floor = floor;
    Decimal.hypot = hypot; // ES6
    Decimal.ln = ln;
    Decimal.log = log;
    Decimal.log10 = log10; // ES6
    Decimal.log2 = log2; // ES6
    Decimal.max = max;
    Decimal.min = min;
    Decimal.mod = mod;
    Decimal.mul = mul;
    Decimal.pow = pow;
    Decimal.random = random;
    Decimal.round = round;
    Decimal.sign = sign; // ES6
    Decimal.sin = sin;
    Decimal.sinh = sinh; // ES6
    Decimal.sqrt = sqrt;
    Decimal.sub = sub;
    Decimal.tan = tan;
    Decimal.tanh = tanh; // ES6
    Decimal.trunc = trunc; // ES6

    if (obj === void 0) obj = {};
    if (obj) {
      if (obj.defaults !== true) {
        ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
        for (i = 0; i < ps.length;) {
          if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
        }
      }
    }

    Decimal.config(obj);

    return Decimal;
  }

  /*
   * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
   * digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   * y {number|string|Decimal}
   *
   */
  function div(x, y) {
    return new this(x).div(y);
  }

  /*
   * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal} The power to which to raise the base of the natural log.
   *
   */
  function exp(x) {
    return new this(x).exp();
  }

  /*
   * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
   *
   * x {number|string|Decimal}
   *
   */
  function floor(x) {
    return finalise(x = new this(x), x.e + 1, 3);
  }

  /*
   * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
   * rounded to `precision` significant digits using rounding mode `rounding`.
   *
   * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
   *
   */
  function hypot() {
    var i,
        n,
        t = new this(0);

    external = false;

    for (i = 0; i < arguments.length;) {
      n = new this(arguments[i++]);
      if (!n.d) {
        if (n.s) {
          external = true;
          return new this(1 / 0);
        }
        t = n;
      } else if (t.d) {
        t = t.plus(n.times(n));
      }
    }

    external = true;

    return t.sqrt();
  }

  /*
   * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),
   * otherwise return false.
   *
   */
  function isDecimalInstance(obj) {
    return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false;
  }

  /*
   * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   *
   */
  function ln(x) {
    return new this(x).ln();
  }

  /*
   * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
   * is specified, rounded to `precision` significant digits using rounding mode `rounding`.
   *
   * log[y](x)
   *
   * x {number|string|Decimal} The argument of the logarithm.
   * y {number|string|Decimal} The base of the logarithm.
   *
   */
  function log(x, y) {
    return new this(x).log(y);
  }

  /*
   * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   *
   */
  function log2(x) {
    return new this(x).log(2);
  }

  /*
   * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   *
   */
  function log10(x) {
    return new this(x).log(10);
  }

  /*
   * Return a new Decimal whose value is the maximum of the arguments.
   *
   * arguments {number|string|Decimal}
   *
   */
  function max() {
    return maxOrMin(this, arguments, 'lt');
  }

  /*
   * Return a new Decimal whose value is the minimum of the arguments.
   *
   * arguments {number|string|Decimal}
   *
   */
  function min() {
    return maxOrMin(this, arguments, 'gt');
  }

  /*
   * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
   * using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   * y {number|string|Decimal}
   *
   */
  function mod(x, y) {
    return new this(x).mod(y);
  }

  /*
   * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
   * digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   * y {number|string|Decimal}
   *
   */
  function mul(x, y) {
    return new this(x).mul(y);
  }

  /*
   * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
   * significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal} The base.
   * y {number|string|Decimal} The exponent.
   *
   */
  function pow(x, y) {
    return new this(x).pow(y);
  }

  /*
   * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
   * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
   * are produced).
   *
   * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
   *
   */
  function random(sd) {
    var d,
        e,
        k,
        n,
        i = 0,
        r = new this(1),
        rd = [];

    if (sd === void 0) sd = this.precision;else checkInt32(sd, 1, MAX_DIGITS);

    k = Math.ceil(sd / LOG_BASE);

    if (!this.crypto) {
      for (; i < k;) {
        rd[i++] = Math.random() * 1e7 | 0;
      } // Browsers supporting crypto.getRandomValues.
    } else if (crypto.getRandomValues) {
      d = crypto.getRandomValues(new Uint32Array(k));

      for (; i < k;) {
        n = d[i];

        // 0 <= n < 4294967296
        // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
        if (n >= 4.29e9) {
          d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
        } else {

          // 0 <= n <= 4289999999
          // 0 <= (n % 1e7) <= 9999999
          rd[i++] = n % 1e7;
        }
      }

      // Node.js supporting crypto.randomBytes.
    } else if (crypto.randomBytes) {

      // buffer
      d = crypto.randomBytes(k *= 4);

      for (; i < k;) {

        // 0 <= n < 2147483648
        n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);

        // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
        if (n >= 2.14e9) {
          crypto.randomBytes(4).copy(d, i);
        } else {

          // 0 <= n <= 2139999999
          // 0 <= (n % 1e7) <= 9999999
          rd.push(n % 1e7);
          i += 4;
        }
      }

      i = k / 4;
    } else {
      throw Error(cryptoUnavailable);
    }

    k = rd[--i];
    sd %= LOG_BASE;

    // Convert trailing digits to zeros according to sd.
    if (k && sd) {
      n = mathpow(10, LOG_BASE - sd);
      rd[i] = (k / n | 0) * n;
    }

    // Remove trailing words which are zero.
    for (; rd[i] === 0; i--) {
      rd.pop();
    } // Zero?
    if (i < 0) {
      e = 0;
      rd = [0];
    } else {
      e = -1;

      // Remove leading words which are zero and adjust exponent accordingly.
      for (; rd[0] === 0; e -= LOG_BASE) {
        rd.shift();
      } // Count the digits of the first word of rd to determine leading zeros.
      for (k = 1, n = rd[0]; n >= 10; n /= 10) {
        k++;
      } // Adjust the exponent for leading zeros of the first word of rd.
      if (k < LOG_BASE) e -= LOG_BASE - k;
    }

    r.e = e;
    r.d = rd;

    return r;
  }

  /*
   * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
   *
   * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
   *
   * x {number|string|Decimal}
   *
   */
  function round(x) {
    return finalise(x = new this(x), x.e + 1, this.rounding);
  }

  /*
   * Return
   *   1    if x > 0,
   *  -1    if x < 0,
   *   0    if x is 0,
   *  -0    if x is -0,
   *   NaN  otherwise
   *
   */
  function sign(x) {
    x = new this(x);
    return x.d ? x.d[0] ? x.s : 0 * x.s : x.s || NaN;
  }

  /*
   * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
   * using rounding mode `rounding`.
   *
   * x {number|string|Decimal} A value in radians.
   *
   */
  function sin(x) {
    return new this(x).sin();
  }

  /*
   * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal} A value in radians.
   *
   */
  function sinh(x) {
    return new this(x).sinh();
  }

  /*
   * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
   * digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   *
   */
  function sqrt(x) {
    return new this(x).sqrt();
  }

  /*
   * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
   * using rounding mode `rounding`.
   *
   * x {number|string|Decimal}
   * y {number|string|Decimal}
   *
   */
  function sub(x, y) {
    return new this(x).sub(y);
  }

  /*
   * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
   * digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal} A value in radians.
   *
   */
  function tan(x) {
    return new this(x).tan();
  }

  /*
   * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
   * significant digits using rounding mode `rounding`.
   *
   * x {number|string|Decimal} A value in radians.
   *
   */
  function tanh(x) {
    return new this(x).tanh();
  }

  /*
   * Return a new Decimal whose value is `x` truncated to an integer.
   *
   * x {number|string|Decimal}
   *
   */
  function trunc(x) {
    return finalise(x = new this(x), x.e + 1, 1);
  }

  // Create and configure initial Decimal constructor.
  Decimal = clone(DEFAULTS);

  Decimal['default'] = Decimal.Decimal = Decimal;

  // Create the internal constants from their string values.
  LN10 = new Decimal(LN10);
  PI = new Decimal(PI);

  // Export.


  // AMD.
  if (true) {
    !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
      return Decimal;
    }).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));

    // Node and other environments that support module.exports.
  } else {}
})(undefined);

/***/ }),

/***/ "./node_modules/jquery/dist/jquery.js":
/*!********************************************!*\
  !*** ./node_modules/jquery/dist/jquery.js ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/*!
 * jQuery JavaScript Library v3.3.1
 * https://jquery.com/
 *
 * Includes Sizzle.js
 * https://sizzlejs.com/
 *
 * Copyright JS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2018-01-20T17:24Z
 */
(function (global, factory) {

	"use strict";

	if (( false ? undefined : _typeof(module)) === "object" && _typeof(module.exports) === "object") {

		// For CommonJS and CommonJS-like environments where a proper `window`
		// is present, execute the factory and get jQuery.
		// For environments that do not have a `window` with a `document`
		// (such as Node.js), expose a factory as module.exports.
		// This accentuates the need for the creation of a real `window`.
		// e.g. var jQuery = require("jquery")(window);
		// See ticket #14549 for more info.
		module.exports = global.document ? factory(global, true) : function (w) {
			if (!w.document) {
				throw new Error("jQuery requires a window with a document");
			}
			return factory(w);
		};
	} else {
		factory(global);
	}

	// Pass this if window is not defined yet
})(typeof window !== "undefined" ? window : undefined, function (window, noGlobal) {

	// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
	// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
	// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
	// enough that all such attempts are guarded in a try block.
	"use strict";

	var arr = [];

	var document = window.document;

	var getProto = Object.getPrototypeOf;

	var _slice = arr.slice;

	var concat = arr.concat;

	var push = arr.push;

	var indexOf = arr.indexOf;

	var class2type = {};

	var toString = class2type.toString;

	var hasOwn = class2type.hasOwnProperty;

	var fnToString = hasOwn.toString;

	var ObjectFunctionString = fnToString.call(Object);

	var support = {};

	var isFunction = function isFunction(obj) {

		// Support: Chrome <=57, Firefox <=52
		// In some browsers, typeof returns "function" for HTML <object> elements
		// (i.e., `typeof document.createElement( "object" ) === "function"`).
		// We don't want to classify *any* DOM node as a function.
		return typeof obj === "function" && typeof obj.nodeType !== "number";
	};

	var isWindow = function isWindow(obj) {
		return obj != null && obj === obj.window;
	};

	var preservedScriptAttributes = {
		type: true,
		src: true,
		noModule: true
	};

	function DOMEval(code, doc, node) {
		doc = doc || document;

		var i,
		    script = doc.createElement("script");

		script.text = code;
		if (node) {
			for (i in preservedScriptAttributes) {
				if (node[i]) {
					script[i] = node[i];
				}
			}
		}
		doc.head.appendChild(script).parentNode.removeChild(script);
	}

	function toType(obj) {
		if (obj == null) {
			return obj + "";
		}

		// Support: Android <=2.3 only (functionish RegExp)
		return (typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object" || typeof obj === "function" ? class2type[toString.call(obj)] || "object" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
	}
	/* global Symbol */
	// Defining this global in .eslintrc.json would create a danger of using the global
	// unguarded in another place, it seems safer to define global only for this module


	var version = "3.3.1",


	// Define a local copy of jQuery
	jQuery = function jQuery(selector, context) {

		// The jQuery object is actually just the init constructor 'enhanced'
		// Need init if jQuery is called (just allow error to be thrown if not included)
		return new jQuery.fn.init(selector, context);
	},


	// Support: Android <=4.0 only
	// Make sure we trim BOM and NBSP
	rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

	jQuery.fn = jQuery.prototype = {

		// The current version of jQuery being used
		jquery: version,

		constructor: jQuery,

		// The default length of a jQuery object is 0
		length: 0,

		toArray: function toArray() {
			return _slice.call(this);
		},

		// Get the Nth element in the matched element set OR
		// Get the whole matched element set as a clean array
		get: function get(num) {

			// Return all the elements in a clean array
			if (num == null) {
				return _slice.call(this);
			}

			// Return just the one element from the set
			return num < 0 ? this[num + this.length] : this[num];
		},

		// Take an array of elements and push it onto the stack
		// (returning the new matched element set)
		pushStack: function pushStack(elems) {

			// Build a new jQuery matched element set
			var ret = jQuery.merge(this.constructor(), elems);

			// Add the old object onto the stack (as a reference)
			ret.prevObject = this;

			// Return the newly-formed element set
			return ret;
		},

		// Execute a callback for every element in the matched set.
		each: function each(callback) {
			return jQuery.each(this, callback);
		},

		map: function map(callback) {
			return this.pushStack(jQuery.map(this, function (elem, i) {
				return callback.call(elem, i, elem);
			}));
		},

		slice: function slice() {
			return this.pushStack(_slice.apply(this, arguments));
		},

		first: function first() {
			return this.eq(0);
		},

		last: function last() {
			return this.eq(-1);
		},

		eq: function eq(i) {
			var len = this.length,
			    j = +i + (i < 0 ? len : 0);
			return this.pushStack(j >= 0 && j < len ? [this[j]] : []);
		},

		end: function end() {
			return this.prevObject || this.constructor();
		},

		// For internal use only.
		// Behaves like an Array's method, not like a jQuery method.
		push: push,
		sort: arr.sort,
		splice: arr.splice
	};

	jQuery.extend = jQuery.fn.extend = function () {
		var options,
		    name,
		    src,
		    copy,
		    copyIsArray,
		    clone,
		    target = arguments[0] || {},
		    i = 1,
		    length = arguments.length,
		    deep = false;

		// Handle a deep copy situation
		if (typeof target === "boolean") {
			deep = target;

			// Skip the boolean and the target
			target = arguments[i] || {};
			i++;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if ((typeof target === "undefined" ? "undefined" : _typeof(target)) !== "object" && !isFunction(target)) {
			target = {};
		}

		// Extend jQuery itself if only one argument is passed
		if (i === length) {
			target = this;
			i--;
		}

		for (; i < length; i++) {

			// Only deal with non-null/undefined values
			if ((options = arguments[i]) != null) {

				// Extend the base object
				for (name in options) {
					src = target[name];
					copy = options[name];

					// Prevent never-ending loop
					if (target === copy) {
						continue;
					}

					// Recurse if we're merging plain objects or arrays
					if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {

						if (copyIsArray) {
							copyIsArray = false;
							clone = src && Array.isArray(src) ? src : [];
						} else {
							clone = src && jQuery.isPlainObject(src) ? src : {};
						}

						// Never move original objects, clone them
						target[name] = jQuery.extend(deep, clone, copy);

						// Don't bring in undefined values
					} else if (copy !== undefined) {
						target[name] = copy;
					}
				}
			}
		}

		// Return the modified object
		return target;
	};

	jQuery.extend({

		// Unique for each copy of jQuery on the page
		expando: "jQuery" + (version + Math.random()).replace(/\D/g, ""),

		// Assume jQuery is ready without the ready module
		isReady: true,

		error: function error(msg) {
			throw new Error(msg);
		},

		noop: function noop() {},

		isPlainObject: function isPlainObject(obj) {
			var proto, Ctor;

			// Detect obvious negatives
			// Use toString instead of jQuery.type to catch host objects
			if (!obj || toString.call(obj) !== "[object Object]") {
				return false;
			}

			proto = getProto(obj);

			// Objects with no prototype (e.g., `Object.create( null )`) are plain
			if (!proto) {
				return true;
			}

			// Objects with prototype are plain iff they were constructed by a global Object function
			Ctor = hasOwn.call(proto, "constructor") && proto.constructor;
			return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString;
		},

		isEmptyObject: function isEmptyObject(obj) {

			/* eslint-disable no-unused-vars */
			// See https://github.com/eslint/eslint/issues/6125
			var name;

			for (name in obj) {
				return false;
			}
			return true;
		},

		// Evaluates a script in a global context
		globalEval: function globalEval(code) {
			DOMEval(code);
		},

		each: function each(obj, callback) {
			var length,
			    i = 0;

			if (isArrayLike(obj)) {
				length = obj.length;
				for (; i < length; i++) {
					if (callback.call(obj[i], i, obj[i]) === false) {
						break;
					}
				}
			} else {
				for (i in obj) {
					if (callback.call(obj[i], i, obj[i]) === false) {
						break;
					}
				}
			}

			return obj;
		},

		// Support: Android <=4.0 only
		trim: function trim(text) {
			return text == null ? "" : (text + "").replace(rtrim, "");
		},

		// results is for internal usage only
		makeArray: function makeArray(arr, results) {
			var ret = results || [];

			if (arr != null) {
				if (isArrayLike(Object(arr))) {
					jQuery.merge(ret, typeof arr === "string" ? [arr] : arr);
				} else {
					push.call(ret, arr);
				}
			}

			return ret;
		},

		inArray: function inArray(elem, arr, i) {
			return arr == null ? -1 : indexOf.call(arr, elem, i);
		},

		// Support: Android <=4.0 only, PhantomJS 1 only
		// push.apply(_, arraylike) throws on ancient WebKit
		merge: function merge(first, second) {
			var len = +second.length,
			    j = 0,
			    i = first.length;

			for (; j < len; j++) {
				first[i++] = second[j];
			}

			first.length = i;

			return first;
		},

		grep: function grep(elems, callback, invert) {
			var callbackInverse,
			    matches = [],
			    i = 0,
			    length = elems.length,
			    callbackExpect = !invert;

			// Go through the array, only saving the items
			// that pass the validator function
			for (; i < length; i++) {
				callbackInverse = !callback(elems[i], i);
				if (callbackInverse !== callbackExpect) {
					matches.push(elems[i]);
				}
			}

			return matches;
		},

		// arg is for internal usage only
		map: function map(elems, callback, arg) {
			var length,
			    value,
			    i = 0,
			    ret = [];

			// Go through the array, translating each of the items to their new values
			if (isArrayLike(elems)) {
				length = elems.length;
				for (; i < length; i++) {
					value = callback(elems[i], i, arg);

					if (value != null) {
						ret.push(value);
					}
				}

				// Go through every key on the object,
			} else {
				for (i in elems) {
					value = callback(elems[i], i, arg);

					if (value != null) {
						ret.push(value);
					}
				}
			}

			// Flatten any nested arrays
			return concat.apply([], ret);
		},

		// A global GUID counter for objects
		guid: 1,

		// jQuery.support is not used in Core but other projects attach their
		// properties to it so it needs to exist.
		support: support
	});

	if (typeof Symbol === "function") {
		jQuery.fn[Symbol.iterator] = arr[Symbol.iterator];
	}

	// Populate the class2type map
	jQuery.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "), function (i, name) {
		class2type["[object " + name + "]"] = name.toLowerCase();
	});

	function isArrayLike(obj) {

		// Support: real iOS 8.2 only (not reproducible in simulator)
		// `in` check used to prevent JIT error (gh-2145)
		// hasOwn isn't used here due to false negatives
		// regarding Nodelist length in IE
		var length = !!obj && "length" in obj && obj.length,
		    type = toType(obj);

		if (isFunction(obj) || isWindow(obj)) {
			return false;
		}

		return type === "array" || length === 0 || typeof length === "number" && length > 0 && length - 1 in obj;
	}
	var Sizzle =
	/*!
  * Sizzle CSS Selector Engine v2.3.3
  * https://sizzlejs.com/
  *
  * Copyright jQuery Foundation and other contributors
  * Released under the MIT license
  * http://jquery.org/license
  *
  * Date: 2016-08-08
  */
	function (window) {

		var i,
		    support,
		    Expr,
		    getText,
		    isXML,
		    tokenize,
		    compile,
		    select,
		    outermostContext,
		    sortInput,
		    hasDuplicate,


		// Local document vars
		setDocument,
		    document,
		    docElem,
		    documentIsHTML,
		    rbuggyQSA,
		    rbuggyMatches,
		    matches,
		    contains,


		// Instance-specific data
		expando = "sizzle" + 1 * new Date(),
		    preferredDoc = window.document,
		    dirruns = 0,
		    done = 0,
		    classCache = createCache(),
		    tokenCache = createCache(),
		    compilerCache = createCache(),
		    sortOrder = function sortOrder(a, b) {
			if (a === b) {
				hasDuplicate = true;
			}
			return 0;
		},


		// Instance methods
		hasOwn = {}.hasOwnProperty,
		    arr = [],
		    pop = arr.pop,
		    push_native = arr.push,
		    push = arr.push,
		    slice = arr.slice,

		// Use a stripped-down indexOf as it's faster than native
		// https://jsperf.com/thor-indexof-vs-for/5
		indexOf = function indexOf(list, elem) {
			var i = 0,
			    len = list.length;
			for (; i < len; i++) {
				if (list[i] === elem) {
					return i;
				}
			}
			return -1;
		},
		    booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",


		// Regular expressions

		// http://www.w3.org/TR/css3-selectors/#whitespace
		whitespace = "[\\x20\\t\\r\\n\\f]",


		// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
		identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",


		// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
		attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
		// Operator (capture 2)
		"*([*^$|!~]?=)" + whitespace +
		// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
		"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]",
		    pseudos = ":(" + identifier + ")(?:\\((" +
		// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
		// 1. quoted (capture 3; capture 4 or capture 5)
		"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
		// 2. simple (capture 6)
		"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
		// 3. anything else (capture 2)
		".*" + ")\\)|)",


		// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
		rwhitespace = new RegExp(whitespace + "+", "g"),
		    rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"),
		    rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),
		    rcombinators = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"),
		    rattributeQuotes = new RegExp("=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g"),
		    rpseudo = new RegExp(pseudos),
		    ridentifier = new RegExp("^" + identifier + "$"),
		    matchExpr = {
			"ID": new RegExp("^#(" + identifier + ")"),
			"CLASS": new RegExp("^\\.(" + identifier + ")"),
			"TAG": new RegExp("^(" + identifier + "|[*])"),
			"ATTR": new RegExp("^" + attributes),
			"PSEUDO": new RegExp("^" + pseudos),
			"CHILD": new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
			"bool": new RegExp("^(?:" + booleans + ")$", "i"),
			// For use in libraries implementing .is()
			// We use this for POS matching in `select`
			"needsContext": new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
		},
		    rinputs = /^(?:input|select|textarea|button)$/i,
		    rheader = /^h\d$/i,
		    rnative = /^[^{]+\{\s*\[native \w/,


		// Easily-parseable/retrievable ID or TAG or CLASS selectors
		rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
		    rsibling = /[+~]/,


		// CSS escapes
		// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
		runescape = new RegExp("\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig"),
		    funescape = function funescape(_, escaped, escapedWhitespace) {
			var high = "0x" + escaped - 0x10000;
			// NaN means non-codepoint
			// Support: Firefox<24
			// Workaround erroneous numeric interpretation of +"0x"
			return high !== high || escapedWhitespace ? escaped : high < 0 ?
			// BMP codepoint
			String.fromCharCode(high + 0x10000) :
			// Supplemental Plane codepoint (surrogate pair)
			String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00);
		},


		// CSS string/identifier serialization
		// https://drafts.csswg.org/cssom/#common-serializing-idioms
		rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
		    fcssescape = function fcssescape(ch, asCodePoint) {
			if (asCodePoint) {

				// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
				if (ch === "\0") {
					return "\uFFFD";
				}

				// Control characters and (dependent upon position) numbers get escaped as code points
				return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " ";
			}

			// Other potentially-special ASCII characters get backslash-escaped
			return "\\" + ch;
		},


		// Used for iframes
		// See setDocument()
		// Removing the function wrapper causes a "Permission Denied"
		// error in IE
		unloadHandler = function unloadHandler() {
			setDocument();
		},
		    disabledAncestor = addCombinator(function (elem) {
			return elem.disabled === true && ("form" in elem || "label" in elem);
		}, { dir: "parentNode", next: "legend" });

		// Optimize for push.apply( _, NodeList )
		try {
			push.apply(arr = slice.call(preferredDoc.childNodes), preferredDoc.childNodes);
			// Support: Android<4.0
			// Detect silently failing push.apply
			arr[preferredDoc.childNodes.length].nodeType;
		} catch (e) {
			push = { apply: arr.length ?

				// Leverage slice if possible
				function (target, els) {
					push_native.apply(target, slice.call(els));
				} :

				// Support: IE<9
				// Otherwise append directly
				function (target, els) {
					var j = target.length,
					    i = 0;
					// Can't trust NodeList.length
					while (target[j++] = els[i++]) {}
					target.length = j - 1;
				}
			};
		}

		function Sizzle(selector, context, results, seed) {
			var m,
			    i,
			    elem,
			    nid,
			    match,
			    groups,
			    newSelector,
			    newContext = context && context.ownerDocument,


			// nodeType defaults to 9, since context defaults to document
			nodeType = context ? context.nodeType : 9;

			results = results || [];

			// Return early from calls with invalid selector or context
			if (typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11) {

				return results;
			}

			// Try to shortcut find operations (as opposed to filters) in HTML documents
			if (!seed) {

				if ((context ? context.ownerDocument || context : preferredDoc) !== document) {
					setDocument(context);
				}
				context = context || document;

				if (documentIsHTML) {

					// If the selector is sufficiently simple, try using a "get*By*" DOM method
					// (excepting DocumentFragment context, where the methods don't exist)
					if (nodeType !== 11 && (match = rquickExpr.exec(selector))) {

						// ID selector
						if (m = match[1]) {

							// Document context
							if (nodeType === 9) {
								if (elem = context.getElementById(m)) {

									// Support: IE, Opera, Webkit
									// TODO: identify versions
									// getElementById can match elements by name instead of ID
									if (elem.id === m) {
										results.push(elem);
										return results;
									}
								} else {
									return results;
								}

								// Element context
							} else {

								// Support: IE, Opera, Webkit
								// TODO: identify versions
								// getElementById can match elements by name instead of ID
								if (newContext && (elem = newContext.getElementById(m)) && contains(context, elem) && elem.id === m) {

									results.push(elem);
									return results;
								}
							}

							// Type selector
						} else if (match[2]) {
							push.apply(results, context.getElementsByTagName(selector));
							return results;

							// Class selector
						} else if ((m = match[3]) && support.getElementsByClassName && context.getElementsByClassName) {

							push.apply(results, context.getElementsByClassName(m));
							return results;
						}
					}

					// Take advantage of querySelectorAll
					if (support.qsa && !compilerCache[selector + " "] && (!rbuggyQSA || !rbuggyQSA.test(selector))) {

						if (nodeType !== 1) {
							newContext = context;
							newSelector = selector;

							// qSA looks outside Element context, which is not what we want
							// Thanks to Andrew Dupont for this workaround technique
							// Support: IE <=8
							// Exclude object elements
						} else if (context.nodeName.toLowerCase() !== "object") {

							// Capture the context ID, setting it first if necessary
							if (nid = context.getAttribute("id")) {
								nid = nid.replace(rcssescape, fcssescape);
							} else {
								context.setAttribute("id", nid = expando);
							}

							// Prefix every selector in the list
							groups = tokenize(selector);
							i = groups.length;
							while (i--) {
								groups[i] = "#" + nid + " " + toSelector(groups[i]);
							}
							newSelector = groups.join(",");

							// Expand context for sibling selectors
							newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
						}

						if (newSelector) {
							try {
								push.apply(results, newContext.querySelectorAll(newSelector));
								return results;
							} catch (qsaError) {} finally {
								if (nid === expando) {
									context.removeAttribute("id");
								}
							}
						}
					}
				}
			}

			// All others
			return select(selector.replace(rtrim, "$1"), context, results, seed);
		}

		/**
   * Create key-value caches of limited size
   * @returns {function(string, object)} Returns the Object data after storing it on itself with
   *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
   *	deleting the oldest entry
   */
		function createCache() {
			var keys = [];

			function cache(key, value) {
				// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
				if (keys.push(key + " ") > Expr.cacheLength) {
					// Only keep the most recent entries
					delete cache[keys.shift()];
				}
				return cache[key + " "] = value;
			}
			return cache;
		}

		/**
   * Mark a function for special use by Sizzle
   * @param {Function} fn The function to mark
   */
		function markFunction(fn) {
			fn[expando] = true;
			return fn;
		}

		/**
   * Support testing using an element
   * @param {Function} fn Passed the created element and returns a boolean result
   */
		function assert(fn) {
			var el = document.createElement("fieldset");

			try {
				return !!fn(el);
			} catch (e) {
				return false;
			} finally {
				// Remove from its parent by default
				if (el.parentNode) {
					el.parentNode.removeChild(el);
				}
				// release memory in IE
				el = null;
			}
		}

		/**
   * Adds the same handler for all of the specified attrs
   * @param {String} attrs Pipe-separated list of attributes
   * @param {Function} handler The method that will be applied
   */
		function addHandle(attrs, handler) {
			var arr = attrs.split("|"),
			    i = arr.length;

			while (i--) {
				Expr.attrHandle[arr[i]] = handler;
			}
		}

		/**
   * Checks document order of two siblings
   * @param {Element} a
   * @param {Element} b
   * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
   */
		function siblingCheck(a, b) {
			var cur = b && a,
			    diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex;

			// Use IE sourceIndex if available on both nodes
			if (diff) {
				return diff;
			}

			// Check if b follows a
			if (cur) {
				while (cur = cur.nextSibling) {
					if (cur === b) {
						return -1;
					}
				}
			}

			return a ? 1 : -1;
		}

		/**
   * Returns a function to use in pseudos for input types
   * @param {String} type
   */
		function createInputPseudo(type) {
			return function (elem) {
				var name = elem.nodeName.toLowerCase();
				return name === "input" && elem.type === type;
			};
		}

		/**
   * Returns a function to use in pseudos for buttons
   * @param {String} type
   */
		function createButtonPseudo(type) {
			return function (elem) {
				var name = elem.nodeName.toLowerCase();
				return (name === "input" || name === "button") && elem.type === type;
			};
		}

		/**
   * Returns a function to use in pseudos for :enabled/:disabled
   * @param {Boolean} disabled true for :disabled; false for :enabled
   */
		function createDisabledPseudo(disabled) {

			// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
			return function (elem) {

				// Only certain elements can match :enabled or :disabled
				// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
				// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
				if ("form" in elem) {

					// Check for inherited disabledness on relevant non-disabled elements:
					// * listed form-associated elements in a disabled fieldset
					//   https://html.spec.whatwg.org/multipage/forms.html#category-listed
					//   https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
					// * option elements in a disabled optgroup
					//   https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
					// All such elements have a "form" property.
					if (elem.parentNode && elem.disabled === false) {

						// Option elements defer to a parent optgroup if present
						if ("label" in elem) {
							if ("label" in elem.parentNode) {
								return elem.parentNode.disabled === disabled;
							} else {
								return elem.disabled === disabled;
							}
						}

						// Support: IE 6 - 11
						// Use the isDisabled shortcut property to check for disabled fieldset ancestors
						return elem.isDisabled === disabled ||

						// Where there is no isDisabled, check manually
						/* jshint -W018 */
						elem.isDisabled !== !disabled && disabledAncestor(elem) === disabled;
					}

					return elem.disabled === disabled;

					// Try to winnow out elements that can't be disabled before trusting the disabled property.
					// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
					// even exist on them, let alone have a boolean value.
				} else if ("label" in elem) {
					return elem.disabled === disabled;
				}

				// Remaining elements are neither :enabled nor :disabled
				return false;
			};
		}

		/**
   * Returns a function to use in pseudos for positionals
   * @param {Function} fn
   */
		function createPositionalPseudo(fn) {
			return markFunction(function (argument) {
				argument = +argument;
				return markFunction(function (seed, matches) {
					var j,
					    matchIndexes = fn([], seed.length, argument),
					    i = matchIndexes.length;

					// Match elements found at the specified indexes
					while (i--) {
						if (seed[j = matchIndexes[i]]) {
							seed[j] = !(matches[j] = seed[j]);
						}
					}
				});
			});
		}

		/**
   * Checks a node for validity as a Sizzle context
   * @param {Element|Object=} context
   * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
   */
		function testContext(context) {
			return context && typeof context.getElementsByTagName !== "undefined" && context;
		}

		// Expose support vars for convenience
		support = Sizzle.support = {};

		/**
   * Detects XML nodes
   * @param {Element|Object} elem An element or a document
   * @returns {Boolean} True iff elem is a non-HTML XML node
   */
		isXML = Sizzle.isXML = function (elem) {
			// documentElement is verified for cases where it doesn't yet exist
			// (such as loading iframes in IE - #4833)
			var documentElement = elem && (elem.ownerDocument || elem).documentElement;
			return documentElement ? documentElement.nodeName !== "HTML" : false;
		};

		/**
   * Sets document-related variables once based on the current document
   * @param {Element|Object} [doc] An element or document object to use to set the document
   * @returns {Object} Returns the current document
   */
		setDocument = Sizzle.setDocument = function (node) {
			var hasCompare,
			    subWindow,
			    doc = node ? node.ownerDocument || node : preferredDoc;

			// Return early if doc is invalid or already selected
			if (doc === document || doc.nodeType !== 9 || !doc.documentElement) {
				return document;
			}

			// Update global variables
			document = doc;
			docElem = document.documentElement;
			documentIsHTML = !isXML(document);

			// Support: IE 9-11, Edge
			// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
			if (preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow) {

				// Support: IE 11, Edge
				if (subWindow.addEventListener) {
					subWindow.addEventListener("unload", unloadHandler, false);

					// Support: IE 9 - 10 only
				} else if (subWindow.attachEvent) {
					subWindow.attachEvent("onunload", unloadHandler);
				}
			}

			/* Attributes
   ---------------------------------------------------------------------- */

			// Support: IE<8
			// Verify that getAttribute really returns attributes and not properties
			// (excepting IE8 booleans)
			support.attributes = assert(function (el) {
				el.className = "i";
				return !el.getAttribute("className");
			});

			/* getElement(s)By*
   ---------------------------------------------------------------------- */

			// Check if getElementsByTagName("*") returns only elements
			support.getElementsByTagName = assert(function (el) {
				el.appendChild(document.createComment(""));
				return !el.getElementsByTagName("*").length;
			});

			// Support: IE<9
			support.getElementsByClassName = rnative.test(document.getElementsByClassName);

			// Support: IE<10
			// Check if getElementById returns elements by name
			// The broken getElementById methods don't pick up programmatically-set names,
			// so use a roundabout getElementsByName test
			support.getById = assert(function (el) {
				docElem.appendChild(el).id = expando;
				return !document.getElementsByName || !document.getElementsByName(expando).length;
			});

			// ID filter and find
			if (support.getById) {
				Expr.filter["ID"] = function (id) {
					var attrId = id.replace(runescape, funescape);
					return function (elem) {
						return elem.getAttribute("id") === attrId;
					};
				};
				Expr.find["ID"] = function (id, context) {
					if (typeof context.getElementById !== "undefined" && documentIsHTML) {
						var elem = context.getElementById(id);
						return elem ? [elem] : [];
					}
				};
			} else {
				Expr.filter["ID"] = function (id) {
					var attrId = id.replace(runescape, funescape);
					return function (elem) {
						var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
						return node && node.value === attrId;
					};
				};

				// Support: IE 6 - 7 only
				// getElementById is not reliable as a find shortcut
				Expr.find["ID"] = function (id, context) {
					if (typeof context.getElementById !== "undefined" && documentIsHTML) {
						var node,
						    i,
						    elems,
						    elem = context.getElementById(id);

						if (elem) {

							// Verify the id attribute
							node = elem.getAttributeNode("id");
							if (node && node.value === id) {
								return [elem];
							}

							// Fall back on getElementsByName
							elems = context.getElementsByName(id);
							i = 0;
							while (elem = elems[i++]) {
								node = elem.getAttributeNode("id");
								if (node && node.value === id) {
									return [elem];
								}
							}
						}

						return [];
					}
				};
			}

			// Tag
			Expr.find["TAG"] = support.getElementsByTagName ? function (tag, context) {
				if (typeof context.getElementsByTagName !== "undefined") {
					return context.getElementsByTagName(tag);

					// DocumentFragment nodes don't have gEBTN
				} else if (support.qsa) {
					return context.querySelectorAll(tag);
				}
			} : function (tag, context) {
				var elem,
				    tmp = [],
				    i = 0,

				// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
				results = context.getElementsByTagName(tag);

				// Filter out possible comments
				if (tag === "*") {
					while (elem = results[i++]) {
						if (elem.nodeType === 1) {
							tmp.push(elem);
						}
					}

					return tmp;
				}
				return results;
			};

			// Class
			Expr.find["CLASS"] = support.getElementsByClassName && function (className, context) {
				if (typeof context.getElementsByClassName !== "undefined" && documentIsHTML) {
					return context.getElementsByClassName(className);
				}
			};

			/* QSA/matchesSelector
   ---------------------------------------------------------------------- */

			// QSA and matchesSelector support

			// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
			rbuggyMatches = [];

			// qSa(:focus) reports false when true (Chrome 21)
			// We allow this because of a bug in IE8/9 that throws an error
			// whenever `document.activeElement` is accessed on an iframe
			// So, we allow :focus to pass through QSA all the time to avoid the IE error
			// See https://bugs.jquery.com/ticket/13378
			rbuggyQSA = [];

			if (support.qsa = rnative.test(document.querySelectorAll)) {
				// Build QSA regex
				// Regex strategy adopted from Diego Perini
				assert(function (el) {
					// Select is set to empty string on purpose
					// This is to test IE's treatment of not explicitly
					// setting a boolean content attribute,
					// since its presence should be enough
					// https://bugs.jquery.com/ticket/12359
					docElem.appendChild(el).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>";

					// Support: IE8, Opera 11-12.16
					// Nothing should be selected when empty strings follow ^= or $= or *=
					// The test attribute must be unknown in Opera but "safe" for WinRT
					// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
					if (el.querySelectorAll("[msallowcapture^='']").length) {
						rbuggyQSA.push("[*^$]=" + whitespace + "*(?:''|\"\")");
					}

					// Support: IE8
					// Boolean attributes and "value" are not treated correctly
					if (!el.querySelectorAll("[selected]").length) {
						rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")");
					}

					// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
					if (!el.querySelectorAll("[id~=" + expando + "-]").length) {
						rbuggyQSA.push("~=");
					}

					// Webkit/Opera - :checked should return selected option elements
					// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
					// IE8 throws error here and will not see later tests
					if (!el.querySelectorAll(":checked").length) {
						rbuggyQSA.push(":checked");
					}

					// Support: Safari 8+, iOS 8+
					// https://bugs.webkit.org/show_bug.cgi?id=136851
					// In-page `selector#id sibling-combinator selector` fails
					if (!el.querySelectorAll("a#" + expando + "+*").length) {
						rbuggyQSA.push(".#.+[+~]");
					}
				});

				assert(function (el) {
					el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>";

					// Support: Windows 8 Native Apps
					// The type and name attributes are restricted during .innerHTML assignment
					var input = document.createElement("input");
					input.setAttribute("type", "hidden");
					el.appendChild(input).setAttribute("name", "D");

					// Support: IE8
					// Enforce case-sensitivity of name attribute
					if (el.querySelectorAll("[name=d]").length) {
						rbuggyQSA.push("name" + whitespace + "*[*^$|!~]?=");
					}

					// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
					// IE8 throws error here and will not see later tests
					if (el.querySelectorAll(":enabled").length !== 2) {
						rbuggyQSA.push(":enabled", ":disabled");
					}

					// Support: IE9-11+
					// IE's :disabled selector does not pick up the children of disabled fieldsets
					docElem.appendChild(el).disabled = true;
					if (el.querySelectorAll(":disabled").length !== 2) {
						rbuggyQSA.push(":enabled", ":disabled");
					}

					// Opera 10-11 does not throw on post-comma invalid pseudos
					el.querySelectorAll("*,:x");
					rbuggyQSA.push(",.*:");
				});
			}

			if (support.matchesSelector = rnative.test(matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector)) {

				assert(function (el) {
					// Check to see if it's possible to do matchesSelector
					// on a disconnected node (IE 9)
					support.disconnectedMatch = matches.call(el, "*");

					// This should fail with an exception
					// Gecko does not error, returns false instead
					matches.call(el, "[s!='']:x");
					rbuggyMatches.push("!=", pseudos);
				});
			}

			rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));
			rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|"));

			/* Contains
   ---------------------------------------------------------------------- */
			hasCompare = rnative.test(docElem.compareDocumentPosition);

			// Element contains another
			// Purposefully self-exclusive
			// As in, an element does not contain itself
			contains = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
				var adown = a.nodeType === 9 ? a.documentElement : a,
				    bup = b && b.parentNode;
				return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
			} : function (a, b) {
				if (b) {
					while (b = b.parentNode) {
						if (b === a) {
							return true;
						}
					}
				}
				return false;
			};

			/* Sorting
   ---------------------------------------------------------------------- */

			// Document order sorting
			sortOrder = hasCompare ? function (a, b) {

				// Flag for duplicate removal
				if (a === b) {
					hasDuplicate = true;
					return 0;
				}

				// Sort on method existence if only one input has compareDocumentPosition
				var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
				if (compare) {
					return compare;
				}

				// Calculate position if both inputs belong to the same document
				compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) :

				// Otherwise we know they are disconnected
				1;

				// Disconnected nodes
				if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {

					// Choose the first element that is related to our preferred document
					if (a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
						return -1;
					}
					if (b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
						return 1;
					}

					// Maintain original order
					return sortInput ? indexOf(sortInput, a) - indexOf(sortInput, b) : 0;
				}

				return compare & 4 ? -1 : 1;
			} : function (a, b) {
				// Exit early if the nodes are identical
				if (a === b) {
					hasDuplicate = true;
					return 0;
				}

				var cur,
				    i = 0,
				    aup = a.parentNode,
				    bup = b.parentNode,
				    ap = [a],
				    bp = [b];

				// Parentless nodes are either documents or disconnected
				if (!aup || !bup) {
					return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf(sortInput, a) - indexOf(sortInput, b) : 0;

					// If the nodes are siblings, we can do a quick check
				} else if (aup === bup) {
					return siblingCheck(a, b);
				}

				// Otherwise we need full lists of their ancestors for comparison
				cur = a;
				while (cur = cur.parentNode) {
					ap.unshift(cur);
				}
				cur = b;
				while (cur = cur.parentNode) {
					bp.unshift(cur);
				}

				// Walk down the tree looking for a discrepancy
				while (ap[i] === bp[i]) {
					i++;
				}

				return i ?
				// Do a sibling check if the nodes have a common ancestor
				siblingCheck(ap[i], bp[i]) :

				// Otherwise nodes in our document sort first
				ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
			};

			return document;
		};

		Sizzle.matches = function (expr, elements) {
			return Sizzle(expr, null, null, elements);
		};

		Sizzle.matchesSelector = function (elem, expr) {
			// Set document vars if needed
			if ((elem.ownerDocument || elem) !== document) {
				setDocument(elem);
			}

			// Make sure that attribute selectors are quoted
			expr = expr.replace(rattributeQuotes, "='$1']");

			if (support.matchesSelector && documentIsHTML && !compilerCache[expr + " "] && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {

				try {
					var ret = matches.call(elem, expr);

					// IE 9's matchesSelector returns false on disconnected nodes
					if (ret || support.disconnectedMatch ||
					// As well, disconnected nodes are said to be in a document
					// fragment in IE 9
					elem.document && elem.document.nodeType !== 11) {
						return ret;
					}
				} catch (e) {}
			}

			return Sizzle(expr, document, null, [elem]).length > 0;
		};

		Sizzle.contains = function (context, elem) {
			// Set document vars if needed
			if ((context.ownerDocument || context) !== document) {
				setDocument(context);
			}
			return contains(context, elem);
		};

		Sizzle.attr = function (elem, name) {
			// Set document vars if needed
			if ((elem.ownerDocument || elem) !== document) {
				setDocument(elem);
			}

			var fn = Expr.attrHandle[name.toLowerCase()],

			// Don't get fooled by Object.prototype properties (jQuery #13807)
			val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;

			return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
		};

		Sizzle.escape = function (sel) {
			return (sel + "").replace(rcssescape, fcssescape);
		};

		Sizzle.error = function (msg) {
			throw new Error("Syntax error, unrecognized expression: " + msg);
		};

		/**
   * Document sorting and removing duplicates
   * @param {ArrayLike} results
   */
		Sizzle.uniqueSort = function (results) {
			var elem,
			    duplicates = [],
			    j = 0,
			    i = 0;

			// Unless we *know* we can detect duplicates, assume their presence
			hasDuplicate = !support.detectDuplicates;
			sortInput = !support.sortStable && results.slice(0);
			results.sort(sortOrder);

			if (hasDuplicate) {
				while (elem = results[i++]) {
					if (elem === results[i]) {
						j = duplicates.push(i);
					}
				}
				while (j--) {
					results.splice(duplicates[j], 1);
				}
			}

			// Clear input after sorting to release objects
			// See https://github.com/jquery/sizzle/pull/225
			sortInput = null;

			return results;
		};

		/**
   * Utility function for retrieving the text value of an array of DOM nodes
   * @param {Array|Element} elem
   */
		getText = Sizzle.getText = function (elem) {
			var node,
			    ret = "",
			    i = 0,
			    nodeType = elem.nodeType;

			if (!nodeType) {
				// If no nodeType, this is expected to be an array
				while (node = elem[i++]) {
					// Do not traverse comment nodes
					ret += getText(node);
				}
			} else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
				// Use textContent for elements
				// innerText usage removed for consistency of new lines (jQuery #11153)
				if (typeof elem.textContent === "string") {
					return elem.textContent;
				} else {
					// Traverse its children
					for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
						ret += getText(elem);
					}
				}
			} else if (nodeType === 3 || nodeType === 4) {
				return elem.nodeValue;
			}
			// Do not include comment or processing instruction nodes

			return ret;
		};

		Expr = Sizzle.selectors = {

			// Can be adjusted by the user
			cacheLength: 50,

			createPseudo: markFunction,

			match: matchExpr,

			attrHandle: {},

			find: {},

			relative: {
				">": { dir: "parentNode", first: true },
				" ": { dir: "parentNode" },
				"+": { dir: "previousSibling", first: true },
				"~": { dir: "previousSibling" }
			},

			preFilter: {
				"ATTR": function ATTR(match) {
					match[1] = match[1].replace(runescape, funescape);

					// Move the given value to match[3] whether quoted or unquoted
					match[3] = (match[3] || match[4] || match[5] || "").replace(runescape, funescape);

					if (match[2] === "~=") {
						match[3] = " " + match[3] + " ";
					}

					return match.slice(0, 4);
				},

				"CHILD": function CHILD(match) {
					/* matches from matchExpr["CHILD"]
     	1 type (only|nth|...)
     	2 what (child|of-type)
     	3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
     	4 xn-component of xn+y argument ([+-]?\d*n|)
     	5 sign of xn-component
     	6 x of xn-component
     	7 sign of y-component
     	8 y of y-component
     */
					match[1] = match[1].toLowerCase();

					if (match[1].slice(0, 3) === "nth") {
						// nth-* requires argument
						if (!match[3]) {
							Sizzle.error(match[0]);
						}

						// numeric x and y parameters for Expr.filter.CHILD
						// remember that false/true cast respectively to 0/1
						match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === "even" || match[3] === "odd"));
						match[5] = +(match[7] + match[8] || match[3] === "odd");

						// other types prohibit arguments
					} else if (match[3]) {
						Sizzle.error(match[0]);
					}

					return match;
				},

				"PSEUDO": function PSEUDO(match) {
					var excess,
					    unquoted = !match[6] && match[2];

					if (matchExpr["CHILD"].test(match[0])) {
						return null;
					}

					// Accept quoted arguments as-is
					if (match[3]) {
						match[2] = match[4] || match[5] || "";

						// Strip excess characters from unquoted arguments
					} else if (unquoted && rpseudo.test(unquoted) && (
					// Get excess from tokenize (recursively)
					excess = tokenize(unquoted, true)) && (
					// advance to the next closing parenthesis
					excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {

						// excess is a negative index
						match[0] = match[0].slice(0, excess);
						match[2] = unquoted.slice(0, excess);
					}

					// Return only captures needed by the pseudo filter method (type and argument)
					return match.slice(0, 3);
				}
			},

			filter: {

				"TAG": function TAG(nodeNameSelector) {
					var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
					return nodeNameSelector === "*" ? function () {
						return true;
					} : function (elem) {
						return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
					};
				},

				"CLASS": function CLASS(className) {
					var pattern = classCache[className + " "];

					return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function (elem) {
						return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "");
					});
				},

				"ATTR": function ATTR(name, operator, check) {
					return function (elem) {
						var result = Sizzle.attr(elem, name);

						if (result == null) {
							return operator === "!=";
						}
						if (!operator) {
							return true;
						}

						result += "";

						return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf(check) === 0 : operator === "*=" ? check && result.indexOf(check) > -1 : operator === "$=" ? check && result.slice(-check.length) === check : operator === "~=" ? (" " + result.replace(rwhitespace, " ") + " ").indexOf(check) > -1 : operator === "|=" ? result === check || result.slice(0, check.length + 1) === check + "-" : false;
					};
				},

				"CHILD": function CHILD(type, what, argument, first, last) {
					var simple = type.slice(0, 3) !== "nth",
					    forward = type.slice(-4) !== "last",
					    ofType = what === "of-type";

					return first === 1 && last === 0 ?

					// Shortcut for :nth-*(n)
					function (elem) {
						return !!elem.parentNode;
					} : function (elem, context, xml) {
						var cache,
						    uniqueCache,
						    outerCache,
						    node,
						    nodeIndex,
						    start,
						    dir = simple !== forward ? "nextSibling" : "previousSibling",
						    parent = elem.parentNode,
						    name = ofType && elem.nodeName.toLowerCase(),
						    useCache = !xml && !ofType,
						    diff = false;

						if (parent) {

							// :(first|last|only)-(child|of-type)
							if (simple) {
								while (dir) {
									node = elem;
									while (node = node[dir]) {
										if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {

											return false;
										}
									}
									// Reverse direction for :only-* (if we haven't yet done so)
									start = dir = type === "only" && !start && "nextSibling";
								}
								return true;
							}

							start = [forward ? parent.firstChild : parent.lastChild];

							// non-xml :nth-child(...) stores cache data on `parent`
							if (forward && useCache) {

								// Seek `elem` from a previously-cached index

								// ...in a gzip-friendly way
								node = parent;
								outerCache = node[expando] || (node[expando] = {});

								// Support: IE <9 only
								// Defend against cloned attroperties (jQuery gh-1709)
								uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});

								cache = uniqueCache[type] || [];
								nodeIndex = cache[0] === dirruns && cache[1];
								diff = nodeIndex && cache[2];
								node = nodeIndex && parent.childNodes[nodeIndex];

								while (node = ++nodeIndex && node && node[dir] || (

								// Fallback to seeking `elem` from the start
								diff = nodeIndex = 0) || start.pop()) {

									// When found, cache indexes on `parent` and break
									if (node.nodeType === 1 && ++diff && node === elem) {
										uniqueCache[type] = [dirruns, nodeIndex, diff];
										break;
									}
								}
							} else {
								// Use previously-cached element index if available
								if (useCache) {
									// ...in a gzip-friendly way
									node = elem;
									outerCache = node[expando] || (node[expando] = {});

									// Support: IE <9 only
									// Defend against cloned attroperties (jQuery gh-1709)
									uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});

									cache = uniqueCache[type] || [];
									nodeIndex = cache[0] === dirruns && cache[1];
									diff = nodeIndex;
								}

								// xml :nth-child(...)
								// or :nth-last-child(...) or :nth(-last)?-of-type(...)
								if (diff === false) {
									// Use the same loop as above to seek `elem` from the start
									while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {

										if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {

											// Cache the index of each encountered element
											if (useCache) {
												outerCache = node[expando] || (node[expando] = {});

												// Support: IE <9 only
												// Defend against cloned attroperties (jQuery gh-1709)
												uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});

												uniqueCache[type] = [dirruns, diff];
											}

											if (node === elem) {
												break;
											}
										}
									}
								}
							}

							// Incorporate the offset, then check against cycle size
							diff -= last;
							return diff === first || diff % first === 0 && diff / first >= 0;
						}
					};
				},

				"PSEUDO": function PSEUDO(pseudo, argument) {
					// pseudo-class names are case-insensitive
					// http://www.w3.org/TR/selectors/#pseudo-classes
					// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
					// Remember that setFilters inherits from pseudos
					var args,
					    fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo);

					// The user may use createPseudo to indicate that
					// arguments are needed to create the filter function
					// just as Sizzle does
					if (fn[expando]) {
						return fn(argument);
					}

					// But maintain support for old signatures
					if (fn.length > 1) {
						args = [pseudo, pseudo, "", argument];
						return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
							var idx,
							    matched = fn(seed, argument),
							    i = matched.length;
							while (i--) {
								idx = indexOf(seed, matched[i]);
								seed[idx] = !(matches[idx] = matched[i]);
							}
						}) : function (elem) {
							return fn(elem, 0, args);
						};
					}

					return fn;
				}
			},

			pseudos: {
				// Potentially complex pseudos
				"not": markFunction(function (selector) {
					// Trim the selector passed to compile
					// to avoid treating leading and trailing
					// spaces as combinators
					var input = [],
					    results = [],
					    matcher = compile(selector.replace(rtrim, "$1"));

					return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
						var elem,
						    unmatched = matcher(seed, null, xml, []),
						    i = seed.length;

						// Match elements unmatched by `matcher`
						while (i--) {
							if (elem = unmatched[i]) {
								seed[i] = !(matches[i] = elem);
							}
						}
					}) : function (elem, context, xml) {
						input[0] = elem;
						matcher(input, null, xml, results);
						// Don't keep the element (issue #299)
						input[0] = null;
						return !results.pop();
					};
				}),

				"has": markFunction(function (selector) {
					return function (elem) {
						return Sizzle(selector, elem).length > 0;
					};
				}),

				"contains": markFunction(function (text) {
					text = text.replace(runescape, funescape);
					return function (elem) {
						return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
					};
				}),

				// "Whether an element is represented by a :lang() selector
				// is based solely on the element's language value
				// being equal to the identifier C,
				// or beginning with the identifier C immediately followed by "-".
				// The matching of C against the element's language value is performed case-insensitively.
				// The identifier C does not have to be a valid language name."
				// http://www.w3.org/TR/selectors/#lang-pseudo
				"lang": markFunction(function (lang) {
					// lang value must be a valid identifier
					if (!ridentifier.test(lang || "")) {
						Sizzle.error("unsupported lang: " + lang);
					}
					lang = lang.replace(runescape, funescape).toLowerCase();
					return function (elem) {
						var elemLang;
						do {
							if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) {

								elemLang = elemLang.toLowerCase();
								return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
							}
						} while ((elem = elem.parentNode) && elem.nodeType === 1);
						return false;
					};
				}),

				// Miscellaneous
				"target": function target(elem) {
					var hash = window.location && window.location.hash;
					return hash && hash.slice(1) === elem.id;
				},

				"root": function root(elem) {
					return elem === docElem;
				},

				"focus": function focus(elem) {
					return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
				},

				// Boolean properties
				"enabled": createDisabledPseudo(false),
				"disabled": createDisabledPseudo(true),

				"checked": function checked(elem) {
					// In CSS3, :checked should return both checked and selected elements
					// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
					var nodeName = elem.nodeName.toLowerCase();
					return nodeName === "input" && !!elem.checked || nodeName === "option" && !!elem.selected;
				},

				"selected": function selected(elem) {
					// Accessing this property makes selected-by-default
					// options in Safari work properly
					if (elem.parentNode) {
						elem.parentNode.selectedIndex;
					}

					return elem.selected === true;
				},

				// Contents
				"empty": function empty(elem) {
					// http://www.w3.org/TR/selectors/#empty-pseudo
					// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
					//   but not by others (comment: 8; processing instruction: 7; etc.)
					// nodeType < 6 works because attributes (2) do not appear as children
					for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
						if (elem.nodeType < 6) {
							return false;
						}
					}
					return true;
				},

				"parent": function parent(elem) {
					return !Expr.pseudos["empty"](elem);
				},

				// Element/input types
				"header": function header(elem) {
					return rheader.test(elem.nodeName);
				},

				"input": function input(elem) {
					return rinputs.test(elem.nodeName);
				},

				"button": function button(elem) {
					var name = elem.nodeName.toLowerCase();
					return name === "input" && elem.type === "button" || name === "button";
				},

				"text": function text(elem) {
					var attr;
					return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && (

					// Support: IE<8
					// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
					(attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text");
				},

				// Position-in-collection
				"first": createPositionalPseudo(function () {
					return [0];
				}),

				"last": createPositionalPseudo(function (matchIndexes, length) {
					return [length - 1];
				}),

				"eq": createPositionalPseudo(function (matchIndexes, length, argument) {
					return [argument < 0 ? argument + length : argument];
				}),

				"even": createPositionalPseudo(function (matchIndexes, length) {
					var i = 0;
					for (; i < length; i += 2) {
						matchIndexes.push(i);
					}
					return matchIndexes;
				}),

				"odd": createPositionalPseudo(function (matchIndexes, length) {
					var i = 1;
					for (; i < length; i += 2) {
						matchIndexes.push(i);
					}
					return matchIndexes;
				}),

				"lt": createPositionalPseudo(function (matchIndexes, length, argument) {
					var i = argument < 0 ? argument + length : argument;
					for (; --i >= 0;) {
						matchIndexes.push(i);
					}
					return matchIndexes;
				}),

				"gt": createPositionalPseudo(function (matchIndexes, length, argument) {
					var i = argument < 0 ? argument + length : argument;
					for (; ++i < length;) {
						matchIndexes.push(i);
					}
					return matchIndexes;
				})
			}
		};

		Expr.pseudos["nth"] = Expr.pseudos["eq"];

		// Add button/input type pseudos
		for (i in { radio: true, checkbox: true, file: true, password: true, image: true }) {
			Expr.pseudos[i] = createInputPseudo(i);
		}
		for (i in { submit: true, reset: true }) {
			Expr.pseudos[i] = createButtonPseudo(i);
		}

		// Easy API for creating new setFilters
		function setFilters() {}
		setFilters.prototype = Expr.filters = Expr.pseudos;
		Expr.setFilters = new setFilters();

		tokenize = Sizzle.tokenize = function (selector, parseOnly) {
			var matched,
			    match,
			    tokens,
			    type,
			    soFar,
			    groups,
			    preFilters,
			    cached = tokenCache[selector + " "];

			if (cached) {
				return parseOnly ? 0 : cached.slice(0);
			}

			soFar = selector;
			groups = [];
			preFilters = Expr.preFilter;

			while (soFar) {

				// Comma and first run
				if (!matched || (match = rcomma.exec(soFar))) {
					if (match) {
						// Don't consume trailing commas as valid
						soFar = soFar.slice(match[0].length) || soFar;
					}
					groups.push(tokens = []);
				}

				matched = false;

				// Combinators
				if (match = rcombinators.exec(soFar)) {
					matched = match.shift();
					tokens.push({
						value: matched,
						// Cast descendant combinators to space
						type: match[0].replace(rtrim, " ")
					});
					soFar = soFar.slice(matched.length);
				}

				// Filters
				for (type in Expr.filter) {
					if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
						matched = match.shift();
						tokens.push({
							value: matched,
							type: type,
							matches: match
						});
						soFar = soFar.slice(matched.length);
					}
				}

				if (!matched) {
					break;
				}
			}

			// Return the length of the invalid excess
			// if we're just parsing
			// Otherwise, throw an error or return tokens
			return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) :
			// Cache the tokens
			tokenCache(selector, groups).slice(0);
		};

		function toSelector(tokens) {
			var i = 0,
			    len = tokens.length,
			    selector = "";
			for (; i < len; i++) {
				selector += tokens[i].value;
			}
			return selector;
		}

		function addCombinator(matcher, combinator, base) {
			var dir = combinator.dir,
			    skip = combinator.next,
			    key = skip || dir,
			    checkNonElements = base && key === "parentNode",
			    doneName = done++;

			return combinator.first ?
			// Check against closest ancestor/preceding element
			function (elem, context, xml) {
				while (elem = elem[dir]) {
					if (elem.nodeType === 1 || checkNonElements) {
						return matcher(elem, context, xml);
					}
				}
				return false;
			} :

			// Check against all ancestor/preceding elements
			function (elem, context, xml) {
				var oldCache,
				    uniqueCache,
				    outerCache,
				    newCache = [dirruns, doneName];

				// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
				if (xml) {
					while (elem = elem[dir]) {
						if (elem.nodeType === 1 || checkNonElements) {
							if (matcher(elem, context, xml)) {
								return true;
							}
						}
					}
				} else {
					while (elem = elem[dir]) {
						if (elem.nodeType === 1 || checkNonElements) {
							outerCache = elem[expando] || (elem[expando] = {});

							// Support: IE <9 only
							// Defend against cloned attroperties (jQuery gh-1709)
							uniqueCache = outerCache[elem.uniqueID] || (outerCache[elem.uniqueID] = {});

							if (skip && skip === elem.nodeName.toLowerCase()) {
								elem = elem[dir] || elem;
							} else if ((oldCache = uniqueCache[key]) && oldCache[0] === dirruns && oldCache[1] === doneName) {

								// Assign to newCache so results back-propagate to previous elements
								return newCache[2] = oldCache[2];
							} else {
								// Reuse newcache so results back-propagate to previous elements
								uniqueCache[key] = newCache;

								// A match means we're done; a fail means we have to keep checking
								if (newCache[2] = matcher(elem, context, xml)) {
									return true;
								}
							}
						}
					}
				}
				return false;
			};
		}

		function elementMatcher(matchers) {
			return matchers.length > 1 ? function (elem, context, xml) {
				var i = matchers.length;
				while (i--) {
					if (!matchers[i](elem, context, xml)) {
						return false;
					}
				}
				return true;
			} : matchers[0];
		}

		function multipleContexts(selector, contexts, results) {
			var i = 0,
			    len = contexts.length;
			for (; i < len; i++) {
				Sizzle(selector, contexts[i], results);
			}
			return results;
		}

		function condense(unmatched, map, filter, context, xml) {
			var elem,
			    newUnmatched = [],
			    i = 0,
			    len = unmatched.length,
			    mapped = map != null;

			for (; i < len; i++) {
				if (elem = unmatched[i]) {
					if (!filter || filter(elem, context, xml)) {
						newUnmatched.push(elem);
						if (mapped) {
							map.push(i);
						}
					}
				}
			}

			return newUnmatched;
		}

		function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
			if (postFilter && !postFilter[expando]) {
				postFilter = setMatcher(postFilter);
			}
			if (postFinder && !postFinder[expando]) {
				postFinder = setMatcher(postFinder, postSelector);
			}
			return markFunction(function (seed, results, context, xml) {
				var temp,
				    i,
				    elem,
				    preMap = [],
				    postMap = [],
				    preexisting = results.length,


				// Get initial elements from seed or context
				elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, []),


				// Prefilter to get matcher input, preserving a map for seed-results synchronization
				matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems,
				    matcherOut = matcher ?
				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
				postFinder || (seed ? preFilter : preexisting || postFilter) ?

				// ...intermediate processing is necessary
				[] :

				// ...otherwise use results directly
				results : matcherIn;

				// Find primary matches
				if (matcher) {
					matcher(matcherIn, matcherOut, context, xml);
				}

				// Apply postFilter
				if (postFilter) {
					temp = condense(matcherOut, postMap);
					postFilter(temp, [], context, xml);

					// Un-match failing elements by moving them back to matcherIn
					i = temp.length;
					while (i--) {
						if (elem = temp[i]) {
							matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
						}
					}
				}

				if (seed) {
					if (postFinder || preFilter) {
						if (postFinder) {
							// Get the final matcherOut by condensing this intermediate into postFinder contexts
							temp = [];
							i = matcherOut.length;
							while (i--) {
								if (elem = matcherOut[i]) {
									// Restore matcherIn since elem is not yet a final match
									temp.push(matcherIn[i] = elem);
								}
							}
							postFinder(null, matcherOut = [], temp, xml);
						}

						// Move matched elements from seed to results to keep them synchronized
						i = matcherOut.length;
						while (i--) {
							if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf(seed, elem) : preMap[i]) > -1) {

								seed[temp] = !(results[temp] = elem);
							}
						}
					}

					// Add elements to results, through postFinder if defined
				} else {
					matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
					if (postFinder) {
						postFinder(null, results, matcherOut, xml);
					} else {
						push.apply(results, matcherOut);
					}
				}
			});
		}

		function matcherFromTokens(tokens) {
			var checkContext,
			    matcher,
			    j,
			    len = tokens.length,
			    leadingRelative = Expr.relative[tokens[0].type],
			    implicitRelative = leadingRelative || Expr.relative[" "],
			    i = leadingRelative ? 1 : 0,


			// The foundational matcher ensures that elements are reachable from top-level context(s)
			matchContext = addCombinator(function (elem) {
				return elem === checkContext;
			}, implicitRelative, true),
			    matchAnyContext = addCombinator(function (elem) {
				return indexOf(checkContext, elem) > -1;
			}, implicitRelative, true),
			    matchers = [function (elem, context, xml) {
				var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
				// Avoid hanging onto element (issue #299)
				checkContext = null;
				return ret;
			}];

			for (; i < len; i++) {
				if (matcher = Expr.relative[tokens[i].type]) {
					matchers = [addCombinator(elementMatcher(matchers), matcher)];
				} else {
					matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);

					// Return special upon seeing a positional matcher
					if (matcher[expando]) {
						// Find the next relative operator (if any) for proper handling
						j = ++i;
						for (; j < len; j++) {
							if (Expr.relative[tokens[j].type]) {
								break;
							}
						}
						return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && toSelector(
						// If the preceding token was a descendant combinator, insert an implicit any-element `*`
						tokens.slice(0, i - 1).concat({ value: tokens[i - 2].type === " " ? "*" : "" })).replace(rtrim, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens));
					}
					matchers.push(matcher);
				}
			}

			return elementMatcher(matchers);
		}

		function matcherFromGroupMatchers(elementMatchers, setMatchers) {
			var bySet = setMatchers.length > 0,
			    byElement = elementMatchers.length > 0,
			    superMatcher = function superMatcher(seed, context, xml, results, outermost) {
				var elem,
				    j,
				    matcher,
				    matchedCount = 0,
				    i = "0",
				    unmatched = seed && [],
				    setMatched = [],
				    contextBackup = outermostContext,

				// We must always have either seed elements or outermost context
				elems = seed || byElement && Expr.find["TAG"]("*", outermost),

				// Use integer dirruns iff this is the outermost matcher
				dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1,
				    len = elems.length;

				if (outermost) {
					outermostContext = context === document || context || outermost;
				}

				// Add elements passing elementMatchers directly to results
				// Support: IE<9, Safari
				// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
				for (; i !== len && (elem = elems[i]) != null; i++) {
					if (byElement && elem) {
						j = 0;
						if (!context && elem.ownerDocument !== document) {
							setDocument(elem);
							xml = !documentIsHTML;
						}
						while (matcher = elementMatchers[j++]) {
							if (matcher(elem, context || document, xml)) {
								results.push(elem);
								break;
							}
						}
						if (outermost) {
							dirruns = dirrunsUnique;
						}
					}

					// Track unmatched elements for set filters
					if (bySet) {
						// They will have gone through all possible matchers
						if (elem = !matcher && elem) {
							matchedCount--;
						}

						// Lengthen the array for every element, matched or not
						if (seed) {
							unmatched.push(elem);
						}
					}
				}

				// `i` is now the count of elements visited above, and adding it to `matchedCount`
				// makes the latter nonnegative.
				matchedCount += i;

				// Apply set filters to unmatched elements
				// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
				// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
				// no element matchers and no seed.
				// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
				// case, which will result in a "00" `matchedCount` that differs from `i` but is also
				// numerically zero.
				if (bySet && i !== matchedCount) {
					j = 0;
					while (matcher = setMatchers[j++]) {
						matcher(unmatched, setMatched, context, xml);
					}

					if (seed) {
						// Reintegrate element matches to eliminate the need for sorting
						if (matchedCount > 0) {
							while (i--) {
								if (!(unmatched[i] || setMatched[i])) {
									setMatched[i] = pop.call(results);
								}
							}
						}

						// Discard index placeholder values to get only actual matches
						setMatched = condense(setMatched);
					}

					// Add matches to results
					push.apply(results, setMatched);

					// Seedless set matches succeeding multiple successful matchers stipulate sorting
					if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {

						Sizzle.uniqueSort(results);
					}
				}

				// Override manipulation of globals by nested matchers
				if (outermost) {
					dirruns = dirrunsUnique;
					outermostContext = contextBackup;
				}

				return unmatched;
			};

			return bySet ? markFunction(superMatcher) : superMatcher;
		}

		compile = Sizzle.compile = function (selector, match /* Internal Use Only */) {
			var i,
			    setMatchers = [],
			    elementMatchers = [],
			    cached = compilerCache[selector + " "];

			if (!cached) {
				// Generate a function of recursive functions that can be used to check each element
				if (!match) {
					match = tokenize(selector);
				}
				i = match.length;
				while (i--) {
					cached = matcherFromTokens(match[i]);
					if (cached[expando]) {
						setMatchers.push(cached);
					} else {
						elementMatchers.push(cached);
					}
				}

				// Cache the compiled function
				cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));

				// Save selector and tokenization
				cached.selector = selector;
			}
			return cached;
		};

		/**
   * A low-level selection function that works with Sizzle's compiled
   *  selector functions
   * @param {String|Function} selector A selector or a pre-compiled
   *  selector function built with Sizzle.compile
   * @param {Element} context
   * @param {Array} [results]
   * @param {Array} [seed] A set of elements to match against
   */
		select = Sizzle.select = function (selector, context, results, seed) {
			var i,
			    tokens,
			    token,
			    type,
			    find,
			    compiled = typeof selector === "function" && selector,
			    match = !seed && tokenize(selector = compiled.selector || selector);

			results = results || [];

			// Try to minimize operations if there is only one selector in the list and no seed
			// (the latter of which guarantees us context)
			if (match.length === 1) {

				// Reduce context if the leading compound selector is an ID
				tokens = match[0] = match[0].slice(0);
				if (tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {

					context = (Expr.find["ID"](token.matches[0].replace(runescape, funescape), context) || [])[0];
					if (!context) {
						return results;

						// Precompiled matchers will still verify ancestry, so step up a level
					} else if (compiled) {
						context = context.parentNode;
					}

					selector = selector.slice(tokens.shift().value.length);
				}

				// Fetch a seed set for right-to-left matching
				i = matchExpr["needsContext"].test(selector) ? 0 : tokens.length;
				while (i--) {
					token = tokens[i];

					// Abort if we hit a combinator
					if (Expr.relative[type = token.type]) {
						break;
					}
					if (find = Expr.find[type]) {
						// Search, expanding context for leading sibling combinators
						if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {

							// If seed is empty or no tokens remain, we can return early
							tokens.splice(i, 1);
							selector = seed.length && toSelector(tokens);
							if (!selector) {
								push.apply(results, seed);
								return results;
							}

							break;
						}
					}
				}
			}

			// Compile and execute a filtering function if one is not provided
			// Provide `match` to avoid retokenization if we modified the selector above
			(compiled || compile(selector, match))(seed, context, !documentIsHTML, results, !context || rsibling.test(selector) && testContext(context.parentNode) || context);
			return results;
		};

		// One-time assignments

		// Sort stability
		support.sortStable = expando.split("").sort(sortOrder).join("") === expando;

		// Support: Chrome 14-35+
		// Always assume duplicates if they aren't passed to the comparison function
		support.detectDuplicates = !!hasDuplicate;

		// Initialize against the default document
		setDocument();

		// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
		// Detached nodes confoundingly follow *each other*
		support.sortDetached = assert(function (el) {
			// Should return 1, but returns 4 (following)
			return el.compareDocumentPosition(document.createElement("fieldset")) & 1;
		});

		// Support: IE<8
		// Prevent attribute/property "interpolation"
		// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
		if (!assert(function (el) {
			el.innerHTML = "<a href='#'></a>";
			return el.firstChild.getAttribute("href") === "#";
		})) {
			addHandle("type|href|height|width", function (elem, name, isXML) {
				if (!isXML) {
					return elem.getAttribute(name, name.toLowerCase() === "type" ? 1 : 2);
				}
			});
		}

		// Support: IE<9
		// Use defaultValue in place of getAttribute("value")
		if (!support.attributes || !assert(function (el) {
			el.innerHTML = "<input/>";
			el.firstChild.setAttribute("value", "");
			return el.firstChild.getAttribute("value") === "";
		})) {
			addHandle("value", function (elem, name, isXML) {
				if (!isXML && elem.nodeName.toLowerCase() === "input") {
					return elem.defaultValue;
				}
			});
		}

		// Support: IE<9
		// Use getAttributeNode to fetch booleans when getAttribute lies
		if (!assert(function (el) {
			return el.getAttribute("disabled") == null;
		})) {
			addHandle(booleans, function (elem, name, isXML) {
				var val;
				if (!isXML) {
					return elem[name] === true ? name.toLowerCase() : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
				}
			});
		}

		return Sizzle;
	}(window);

	jQuery.find = Sizzle;
	jQuery.expr = Sizzle.selectors;

	// Deprecated
	jQuery.expr[":"] = jQuery.expr.pseudos;
	jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
	jQuery.text = Sizzle.getText;
	jQuery.isXMLDoc = Sizzle.isXML;
	jQuery.contains = Sizzle.contains;
	jQuery.escapeSelector = Sizzle.escape;

	var dir = function dir(elem, _dir, until) {
		var matched = [],
		    truncate = until !== undefined;

		while ((elem = elem[_dir]) && elem.nodeType !== 9) {
			if (elem.nodeType === 1) {
				if (truncate && jQuery(elem).is(until)) {
					break;
				}
				matched.push(elem);
			}
		}
		return matched;
	};

	var _siblings = function _siblings(n, elem) {
		var matched = [];

		for (; n; n = n.nextSibling) {
			if (n.nodeType === 1 && n !== elem) {
				matched.push(n);
			}
		}

		return matched;
	};

	var rneedsContext = jQuery.expr.match.needsContext;

	function nodeName(elem, name) {

		return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
	};
	var rsingleTag = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;

	// Implement the identical functionality for filter and not
	function winnow(elements, qualifier, not) {
		if (isFunction(qualifier)) {
			return jQuery.grep(elements, function (elem, i) {
				return !!qualifier.call(elem, i, elem) !== not;
			});
		}

		// Single element
		if (qualifier.nodeType) {
			return jQuery.grep(elements, function (elem) {
				return elem === qualifier !== not;
			});
		}

		// Arraylike of elements (jQuery, arguments, Array)
		if (typeof qualifier !== "string") {
			return jQuery.grep(elements, function (elem) {
				return indexOf.call(qualifier, elem) > -1 !== not;
			});
		}

		// Filtered directly for both simple and complex selectors
		return jQuery.filter(qualifier, elements, not);
	}

	jQuery.filter = function (expr, elems, not) {
		var elem = elems[0];

		if (not) {
			expr = ":not(" + expr + ")";
		}

		if (elems.length === 1 && elem.nodeType === 1) {
			return jQuery.find.matchesSelector(elem, expr) ? [elem] : [];
		}

		return jQuery.find.matches(expr, jQuery.grep(elems, function (elem) {
			return elem.nodeType === 1;
		}));
	};

	jQuery.fn.extend({
		find: function find(selector) {
			var i,
			    ret,
			    len = this.length,
			    self = this;

			if (typeof selector !== "string") {
				return this.pushStack(jQuery(selector).filter(function () {
					for (i = 0; i < len; i++) {
						if (jQuery.contains(self[i], this)) {
							return true;
						}
					}
				}));
			}

			ret = this.pushStack([]);

			for (i = 0; i < len; i++) {
				jQuery.find(selector, self[i], ret);
			}

			return len > 1 ? jQuery.uniqueSort(ret) : ret;
		},
		filter: function filter(selector) {
			return this.pushStack(winnow(this, selector || [], false));
		},
		not: function not(selector) {
			return this.pushStack(winnow(this, selector || [], true));
		},
		is: function is(selector) {
			return !!winnow(this,

			// If this is a positional/relative selector, check membership in the returned set
			// so $("p:first").is("p:last") won't return true for a doc with two "p".
			typeof selector === "string" && rneedsContext.test(selector) ? jQuery(selector) : selector || [], false).length;
		}
	});

	// Initialize a jQuery object


	// A central reference to the root jQuery(document)
	var rootjQuery,


	// A simple way to check for HTML strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
	// Strict HTML recognition (#11290: must start with <)
	// Shortcut simple #id case for speed
	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
	    init = jQuery.fn.init = function (selector, context, root) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if (!selector) {
			return this;
		}

		// Method init() accepts an alternate rootjQuery
		// so migrate can support jQuery.sub (gh-2101)
		root = root || rootjQuery;

		// Handle HTML strings
		if (typeof selector === "string") {
			if (selector[0] === "<" && selector[selector.length - 1] === ">" && selector.length >= 3) {

				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [null, selector, null];
			} else {
				match = rquickExpr.exec(selector);
			}

			// Match html or make sure no context is specified for #id
			if (match && (match[1] || !context)) {

				// HANDLE: $(html) -> $(array)
				if (match[1]) {
					context = context instanceof jQuery ? context[0] : context;

					// Option to run scripts is true for back-compat
					// Intentionally let the error be thrown if parseHTML is not present
					jQuery.merge(this, jQuery.parseHTML(match[1], context && context.nodeType ? context.ownerDocument || context : document, true));

					// HANDLE: $(html, props)
					if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
						for (match in context) {

							// Properties of context are called as methods if possible
							if (isFunction(this[match])) {
								this[match](context[match]);

								// ...and otherwise set as attributes
							} else {
								this.attr(match, context[match]);
							}
						}
					}

					return this;

					// HANDLE: $(#id)
				} else {
					elem = document.getElementById(match[2]);

					if (elem) {

						// Inject the element directly into the jQuery object
						this[0] = elem;
						this.length = 1;
					}
					return this;
				}

				// HANDLE: $(expr, $(...))
			} else if (!context || context.jquery) {
				return (context || root).find(selector);

				// HANDLE: $(expr, context)
				// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor(context).find(selector);
			}

			// HANDLE: $(DOMElement)
		} else if (selector.nodeType) {
			this[0] = selector;
			this.length = 1;
			return this;

			// HANDLE: $(function)
			// Shortcut for document ready
		} else if (isFunction(selector)) {
			return root.ready !== undefined ? root.ready(selector) :

			// Execute immediately if ready is not present
			selector(jQuery);
		}

		return jQuery.makeArray(selector, this);
	};

	// Give the init function the jQuery prototype for later instantiation
	init.prototype = jQuery.fn;

	// Initialize central reference
	rootjQuery = jQuery(document);

	var rparentsprev = /^(?:parents|prev(?:Until|All))/,


	// Methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

	jQuery.fn.extend({
		has: function has(target) {
			var targets = jQuery(target, this),
			    l = targets.length;

			return this.filter(function () {
				var i = 0;
				for (; i < l; i++) {
					if (jQuery.contains(this, targets[i])) {
						return true;
					}
				}
			});
		},

		closest: function closest(selectors, context) {
			var cur,
			    i = 0,
			    l = this.length,
			    matched = [],
			    targets = typeof selectors !== "string" && jQuery(selectors);

			// Positional selectors never match, since there's no _selection_ context
			if (!rneedsContext.test(selectors)) {
				for (; i < l; i++) {
					for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) {

						// Always skip document fragments
						if (cur.nodeType < 11 && (targets ? targets.index(cur) > -1 :

						// Don't pass non-elements to Sizzle
						cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors))) {

							matched.push(cur);
							break;
						}
					}
				}
			}

			return this.pushStack(matched.length > 1 ? jQuery.uniqueSort(matched) : matched);
		},

		// Determine the position of an element within the set
		index: function index(elem) {

			// No argument, return index in parent
			if (!elem) {
				return this[0] && this[0].parentNode ? this.first().prevAll().length : -1;
			}

			// Index in selector
			if (typeof elem === "string") {
				return indexOf.call(jQuery(elem), this[0]);
			}

			// Locate the position of the desired element
			return indexOf.call(this,

			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[0] : elem);
		},

		add: function add(selector, context) {
			return this.pushStack(jQuery.uniqueSort(jQuery.merge(this.get(), jQuery(selector, context))));
		},

		addBack: function addBack(selector) {
			return this.add(selector == null ? this.prevObject : this.prevObject.filter(selector));
		}
	});

	function sibling(cur, dir) {
		while ((cur = cur[dir]) && cur.nodeType !== 1) {}
		return cur;
	}

	jQuery.each({
		parent: function parent(elem) {
			var parent = elem.parentNode;
			return parent && parent.nodeType !== 11 ? parent : null;
		},
		parents: function parents(elem) {
			return dir(elem, "parentNode");
		},
		parentsUntil: function parentsUntil(elem, i, until) {
			return dir(elem, "parentNode", until);
		},
		next: function next(elem) {
			return sibling(elem, "nextSibling");
		},
		prev: function prev(elem) {
			return sibling(elem, "previousSibling");
		},
		nextAll: function nextAll(elem) {
			return dir(elem, "nextSibling");
		},
		prevAll: function prevAll(elem) {
			return dir(elem, "previousSibling");
		},
		nextUntil: function nextUntil(elem, i, until) {
			return dir(elem, "nextSibling", until);
		},
		prevUntil: function prevUntil(elem, i, until) {
			return dir(elem, "previousSibling", until);
		},
		siblings: function siblings(elem) {
			return _siblings((elem.parentNode || {}).firstChild, elem);
		},
		children: function children(elem) {
			return _siblings(elem.firstChild);
		},
		contents: function contents(elem) {
			if (nodeName(elem, "iframe")) {
				return elem.contentDocument;
			}

			// Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
			// Treat the template element as a regular one in browsers that
			// don't support it.
			if (nodeName(elem, "template")) {
				elem = elem.content || elem;
			}

			return jQuery.merge([], elem.childNodes);
		}
	}, function (name, fn) {
		jQuery.fn[name] = function (until, selector) {
			var matched = jQuery.map(this, fn, until);

			if (name.slice(-5) !== "Until") {
				selector = until;
			}

			if (selector && typeof selector === "string") {
				matched = jQuery.filter(selector, matched);
			}

			if (this.length > 1) {

				// Remove duplicates
				if (!guaranteedUnique[name]) {
					jQuery.uniqueSort(matched);
				}

				// Reverse order for parents* and prev-derivatives
				if (rparentsprev.test(name)) {
					matched.reverse();
				}
			}

			return this.pushStack(matched);
		};
	});
	var rnothtmlwhite = /[^\x20\t\r\n\f]+/g;

	// Convert String-formatted options into Object-formatted ones
	function createOptions(options) {
		var object = {};
		jQuery.each(options.match(rnothtmlwhite) || [], function (_, flag) {
			object[flag] = true;
		});
		return object;
	}

	/*
  * Create a callback list using the following parameters:
  *
  *	options: an optional list of space-separated options that will change how
  *			the callback list behaves or a more traditional option object
  *
  * By default a callback list will act like an event callback list and can be
  * "fired" multiple times.
  *
  * Possible options:
  *
  *	once:			will ensure the callback list can only be fired once (like a Deferred)
  *
  *	memory:			will keep track of previous values and will call any callback added
  *					after the list has been fired right away with the latest "memorized"
  *					values (like a Deferred)
  *
  *	unique:			will ensure a callback can only be added once (no duplicate in the list)
  *
  *	stopOnFalse:	interrupt callings when a callback returns false
  *
  */
	jQuery.Callbacks = function (options) {

		// Convert options from String-formatted to Object-formatted if needed
		// (we check in cache first)
		options = typeof options === "string" ? createOptions(options) : jQuery.extend({}, options);

		var // Flag to know if list is currently firing
		firing,


		// Last fire value for non-forgettable lists
		memory,


		// Flag to know if list was already fired
		_fired,


		// Flag to prevent firing
		_locked,


		// Actual callback list
		list = [],


		// Queue of execution data for repeatable lists
		queue = [],


		// Index of currently firing callback (modified by add/remove as needed)
		firingIndex = -1,


		// Fire callbacks
		fire = function fire() {

			// Enforce single-firing
			_locked = _locked || options.once;

			// Execute callbacks for all pending executions,
			// respecting firingIndex overrides and runtime changes
			_fired = firing = true;
			for (; queue.length; firingIndex = -1) {
				memory = queue.shift();
				while (++firingIndex < list.length) {

					// Run callback and check for early termination
					if (list[firingIndex].apply(memory[0], memory[1]) === false && options.stopOnFalse) {

						// Jump to end and forget the data so .add doesn't re-fire
						firingIndex = list.length;
						memory = false;
					}
				}
			}

			// Forget the data if we're done with it
			if (!options.memory) {
				memory = false;
			}

			firing = false;

			// Clean up if we're done firing for good
			if (_locked) {

				// Keep an empty list if we have data for future add calls
				if (memory) {
					list = [];

					// Otherwise, this object is spent
				} else {
					list = "";
				}
			}
		},


		// Actual Callbacks object
		self = {

			// Add a callback or a collection of callbacks to the list
			add: function add() {
				if (list) {

					// If we have memory from a past run, we should fire after adding
					if (memory && !firing) {
						firingIndex = list.length - 1;
						queue.push(memory);
					}

					(function add(args) {
						jQuery.each(args, function (_, arg) {
							if (isFunction(arg)) {
								if (!options.unique || !self.has(arg)) {
									list.push(arg);
								}
							} else if (arg && arg.length && toType(arg) !== "string") {

								// Inspect recursively
								add(arg);
							}
						});
					})(arguments);

					if (memory && !firing) {
						fire();
					}
				}
				return this;
			},

			// Remove a callback from the list
			remove: function remove() {
				jQuery.each(arguments, function (_, arg) {
					var index;
					while ((index = jQuery.inArray(arg, list, index)) > -1) {
						list.splice(index, 1);

						// Handle firing indexes
						if (index <= firingIndex) {
							firingIndex--;
						}
					}
				});
				return this;
			},

			// Check if a given callback is in the list.
			// If no argument is given, return whether or not list has callbacks attached.
			has: function has(fn) {
				return fn ? jQuery.inArray(fn, list) > -1 : list.length > 0;
			},

			// Remove all callbacks from the list
			empty: function empty() {
				if (list) {
					list = [];
				}
				return this;
			},

			// Disable .fire and .add
			// Abort any current/pending executions
			// Clear all callbacks and values
			disable: function disable() {
				_locked = queue = [];
				list = memory = "";
				return this;
			},
			disabled: function disabled() {
				return !list;
			},

			// Disable .fire
			// Also disable .add unless we have memory (since it would have no effect)
			// Abort any pending executions
			lock: function lock() {
				_locked = queue = [];
				if (!memory && !firing) {
					list = memory = "";
				}
				return this;
			},
			locked: function locked() {
				return !!_locked;
			},

			// Call all callbacks with the given context and arguments
			fireWith: function fireWith(context, args) {
				if (!_locked) {
					args = args || [];
					args = [context, args.slice ? args.slice() : args];
					queue.push(args);
					if (!firing) {
						fire();
					}
				}
				return this;
			},

			// Call all the callbacks with the given arguments
			fire: function fire() {
				self.fireWith(this, arguments);
				return this;
			},

			// To know if the callbacks have already been called at least once
			fired: function fired() {
				return !!_fired;
			}
		};

		return self;
	};

	function Identity(v) {
		return v;
	}
	function Thrower(ex) {
		throw ex;
	}

	function adoptValue(value, resolve, reject, noValue) {
		var method;

		try {

			// Check for promise aspect first to privilege synchronous behavior
			if (value && isFunction(method = value.promise)) {
				method.call(value).done(resolve).fail(reject);

				// Other thenables
			} else if (value && isFunction(method = value.then)) {
				method.call(value, resolve, reject);

				// Other non-thenables
			} else {

				// Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
				// * false: [ value ].slice( 0 ) => resolve( value )
				// * true: [ value ].slice( 1 ) => resolve()
				resolve.apply(undefined, [value].slice(noValue));
			}

			// For Promises/A+, convert exceptions into rejections
			// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
			// Deferred#then to conditionally suppress rejection.
		} catch (value) {

			// Support: Android 4.0 only
			// Strict mode functions invoked without .call/.apply get global-object context
			reject.apply(undefined, [value]);
		}
	}

	jQuery.extend({

		Deferred: function Deferred(func) {
			var tuples = [

			// action, add listener, callbacks,
			// ... .then handlers, argument index, [final state]
			["notify", "progress", jQuery.Callbacks("memory"), jQuery.Callbacks("memory"), 2], ["resolve", "done", jQuery.Callbacks("once memory"), jQuery.Callbacks("once memory"), 0, "resolved"], ["reject", "fail", jQuery.Callbacks("once memory"), jQuery.Callbacks("once memory"), 1, "rejected"]],
			    _state = "pending",
			    _promise = {
				state: function state() {
					return _state;
				},
				always: function always() {
					deferred.done(arguments).fail(arguments);
					return this;
				},
				"catch": function _catch(fn) {
					return _promise.then(null, fn);
				},

				// Keep pipe for back-compat
				pipe: function pipe() /* fnDone, fnFail, fnProgress */{
					var fns = arguments;

					return jQuery.Deferred(function (newDefer) {
						jQuery.each(tuples, function (i, tuple) {

							// Map tuples (progress, done, fail) to arguments (done, fail, progress)
							var fn = isFunction(fns[tuple[4]]) && fns[tuple[4]];

							// deferred.progress(function() { bind to newDefer or newDefer.notify })
							// deferred.done(function() { bind to newDefer or newDefer.resolve })
							// deferred.fail(function() { bind to newDefer or newDefer.reject })
							deferred[tuple[1]](function () {
								var returned = fn && fn.apply(this, arguments);
								if (returned && isFunction(returned.promise)) {
									returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject);
								} else {
									newDefer[tuple[0] + "With"](this, fn ? [returned] : arguments);
								}
							});
						});
						fns = null;
					}).promise();
				},
				then: function then(onFulfilled, onRejected, onProgress) {
					var maxDepth = 0;
					function resolve(depth, deferred, handler, special) {
						return function () {
							var that = this,
							    args = arguments,
							    mightThrow = function mightThrow() {
								var returned, then;

								// Support: Promises/A+ section 2.3.3.3.3
								// https://promisesaplus.com/#point-59
								// Ignore double-resolution attempts
								if (depth < maxDepth) {
									return;
								}

								returned = handler.apply(that, args);

								// Support: Promises/A+ section 2.3.1
								// https://promisesaplus.com/#point-48
								if (returned === deferred.promise()) {
									throw new TypeError("Thenable self-resolution");
								}

								// Support: Promises/A+ sections 2.3.3.1, 3.5
								// https://promisesaplus.com/#point-54
								// https://promisesaplus.com/#point-75
								// Retrieve `then` only once
								then = returned && (

								// Support: Promises/A+ section 2.3.4
								// https://promisesaplus.com/#point-64
								// Only check objects and functions for thenability
								(typeof returned === "undefined" ? "undefined" : _typeof(returned)) === "object" || typeof returned === "function") && returned.then;

								// Handle a returned thenable
								if (isFunction(then)) {

									// Special processors (notify) just wait for resolution
									if (special) {
										then.call(returned, resolve(maxDepth, deferred, Identity, special), resolve(maxDepth, deferred, Thrower, special));

										// Normal processors (resolve) also hook into progress
									} else {

										// ...and disregard older resolution values
										maxDepth++;

										then.call(returned, resolve(maxDepth, deferred, Identity, special), resolve(maxDepth, deferred, Thrower, special), resolve(maxDepth, deferred, Identity, deferred.notifyWith));
									}

									// Handle all other returned values
								} else {

									// Only substitute handlers pass on context
									// and multiple values (non-spec behavior)
									if (handler !== Identity) {
										that = undefined;
										args = [returned];
									}

									// Process the value(s)
									// Default process is resolve
									(special || deferred.resolveWith)(that, args);
								}
							},


							// Only normal processors (resolve) catch and reject exceptions
							process = special ? mightThrow : function () {
								try {
									mightThrow();
								} catch (e) {

									if (jQuery.Deferred.exceptionHook) {
										jQuery.Deferred.exceptionHook(e, process.stackTrace);
									}

									// Support: Promises/A+ section 2.3.3.3.4.1
									// https://promisesaplus.com/#point-61
									// Ignore post-resolution exceptions
									if (depth + 1 >= maxDepth) {

										// Only substitute handlers pass on context
										// and multiple values (non-spec behavior)
										if (handler !== Thrower) {
											that = undefined;
											args = [e];
										}

										deferred.rejectWith(that, args);
									}
								}
							};

							// Support: Promises/A+ section 2.3.3.3.1
							// https://promisesaplus.com/#point-57
							// Re-resolve promises immediately to dodge false rejection from
							// subsequent errors
							if (depth) {
								process();
							} else {

								// Call an optional hook to record the stack, in case of exception
								// since it's otherwise lost when execution goes async
								if (jQuery.Deferred.getStackHook) {
									process.stackTrace = jQuery.Deferred.getStackHook();
								}
								window.setTimeout(process);
							}
						};
					}

					return jQuery.Deferred(function (newDefer) {

						// progress_handlers.add( ... )
						tuples[0][3].add(resolve(0, newDefer, isFunction(onProgress) ? onProgress : Identity, newDefer.notifyWith));

						// fulfilled_handlers.add( ... )
						tuples[1][3].add(resolve(0, newDefer, isFunction(onFulfilled) ? onFulfilled : Identity));

						// rejected_handlers.add( ... )
						tuples[2][3].add(resolve(0, newDefer, isFunction(onRejected) ? onRejected : Thrower));
					}).promise();
				},

				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function promise(obj) {
					return obj != null ? jQuery.extend(obj, _promise) : _promise;
				}
			},
			    deferred = {};

			// Add list-specific methods
			jQuery.each(tuples, function (i, tuple) {
				var list = tuple[2],
				    stateString = tuple[5];

				// promise.progress = list.add
				// promise.done = list.add
				// promise.fail = list.add
				_promise[tuple[1]] = list.add;

				// Handle state
				if (stateString) {
					list.add(function () {

						// state = "resolved" (i.e., fulfilled)
						// state = "rejected"
						_state = stateString;
					},

					// rejected_callbacks.disable
					// fulfilled_callbacks.disable
					tuples[3 - i][2].disable,

					// rejected_handlers.disable
					// fulfilled_handlers.disable
					tuples[3 - i][3].disable,

					// progress_callbacks.lock
					tuples[0][2].lock,

					// progress_handlers.lock
					tuples[0][3].lock);
				}

				// progress_handlers.fire
				// fulfilled_handlers.fire
				// rejected_handlers.fire
				list.add(tuple[3].fire);

				// deferred.notify = function() { deferred.notifyWith(...) }
				// deferred.resolve = function() { deferred.resolveWith(...) }
				// deferred.reject = function() { deferred.rejectWith(...) }
				deferred[tuple[0]] = function () {
					deferred[tuple[0] + "With"](this === deferred ? undefined : this, arguments);
					return this;
				};

				// deferred.notifyWith = list.fireWith
				// deferred.resolveWith = list.fireWith
				// deferred.rejectWith = list.fireWith
				deferred[tuple[0] + "With"] = list.fireWith;
			});

			// Make the deferred a promise
			_promise.promise(deferred);

			// Call given func if any
			if (func) {
				func.call(deferred, deferred);
			}

			// All done!
			return deferred;
		},

		// Deferred helper
		when: function when(singleValue) {
			var

			// count of uncompleted subordinates
			remaining = arguments.length,


			// count of unprocessed arguments
			i = remaining,


			// subordinate fulfillment data
			resolveContexts = Array(i),
			    resolveValues = _slice.call(arguments),


			// the master Deferred
			master = jQuery.Deferred(),


			// subordinate callback factory
			updateFunc = function updateFunc(i) {
				return function (value) {
					resolveContexts[i] = this;
					resolveValues[i] = arguments.length > 1 ? _slice.call(arguments) : value;
					if (! --remaining) {
						master.resolveWith(resolveContexts, resolveValues);
					}
				};
			};

			// Single- and empty arguments are adopted like Promise.resolve
			if (remaining <= 1) {
				adoptValue(singleValue, master.done(updateFunc(i)).resolve, master.reject, !remaining);

				// Use .then() to unwrap secondary thenables (cf. gh-3000)
				if (master.state() === "pending" || isFunction(resolveValues[i] && resolveValues[i].then)) {

					return master.then();
				}
			}

			// Multiple arguments are aggregated like Promise.all array elements
			while (i--) {
				adoptValue(resolveValues[i], updateFunc(i), master.reject);
			}

			return master.promise();
		}
	});

	// These usually indicate a programmer mistake during development,
	// warn about them ASAP rather than swallowing them by default.
	var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;

	jQuery.Deferred.exceptionHook = function (error, stack) {

		// Support: IE 8 - 9 only
		// Console exists when dev tools are open, which can happen at any time
		if (window.console && window.console.warn && error && rerrorNames.test(error.name)) {
			window.console.warn("jQuery.Deferred exception: " + error.message, error.stack, stack);
		}
	};

	jQuery.readyException = function (error) {
		window.setTimeout(function () {
			throw error;
		});
	};

	// The deferred used on DOM ready
	var readyList = jQuery.Deferred();

	jQuery.fn.ready = function (fn) {

		readyList.then(fn)

		// Wrap jQuery.readyException in a function so that the lookup
		// happens at the time of error handling instead of callback
		// registration.
		.catch(function (error) {
			jQuery.readyException(error);
		});

		return this;
	};

	jQuery.extend({

		// Is the DOM ready to be used? Set to true once it occurs.
		isReady: false,

		// A counter to track how many items to wait for before
		// the ready event fires. See #6781
		readyWait: 1,

		// Handle when the DOM is ready
		ready: function ready(wait) {

			// Abort if there are pending holds or we're already ready
			if (wait === true ? --jQuery.readyWait : jQuery.isReady) {
				return;
			}

			// Remember that the DOM is ready
			jQuery.isReady = true;

			// If a normal DOM Ready event fired, decrement, and wait if need be
			if (wait !== true && --jQuery.readyWait > 0) {
				return;
			}

			// If there are functions bound, to execute
			readyList.resolveWith(document, [jQuery]);
		}
	});

	jQuery.ready.then = readyList.then;

	// The ready event handler and self cleanup method
	function completed() {
		document.removeEventListener("DOMContentLoaded", completed);
		window.removeEventListener("load", completed);
		jQuery.ready();
	}

	// Catch cases where $(document).ready() is called
	// after the browser event has already occurred.
	// Support: IE <=9 - 10 only
	// Older IE sometimes signals "interactive" too soon
	if (document.readyState === "complete" || document.readyState !== "loading" && !document.documentElement.doScroll) {

		// Handle it asynchronously to allow scripts the opportunity to delay ready
		window.setTimeout(jQuery.ready);
	} else {

		// Use the handy event callback
		document.addEventListener("DOMContentLoaded", completed);

		// A fallback to window.onload, that will always work
		window.addEventListener("load", completed);
	}

	// Multifunctional method to get and set values of a collection
	// The value/s can optionally be executed if it's a function
	var access = function access(elems, fn, key, value, chainable, emptyGet, raw) {
		var i = 0,
		    len = elems.length,
		    bulk = key == null;

		// Sets many values
		if (toType(key) === "object") {
			chainable = true;
			for (i in key) {
				access(elems, fn, i, key[i], true, emptyGet, raw);
			}

			// Sets one value
		} else if (value !== undefined) {
			chainable = true;

			if (!isFunction(value)) {
				raw = true;
			}

			if (bulk) {

				// Bulk operations run against the entire set
				if (raw) {
					fn.call(elems, value);
					fn = null;

					// ...except when executing function values
				} else {
					bulk = fn;
					fn = function fn(elem, key, value) {
						return bulk.call(jQuery(elem), value);
					};
				}
			}

			if (fn) {
				for (; i < len; i++) {
					fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key)));
				}
			}
		}

		if (chainable) {
			return elems;
		}

		// Gets
		if (bulk) {
			return fn.call(elems);
		}

		return len ? fn(elems[0], key) : emptyGet;
	};

	// Matches dashed string for camelizing
	var rmsPrefix = /^-ms-/,
	    rdashAlpha = /-([a-z])/g;

	// Used by camelCase as callback to replace()
	function fcamelCase(all, letter) {
		return letter.toUpperCase();
	}

	// Convert dashed to camelCase; used by the css and data modules
	// Support: IE <=9 - 11, Edge 12 - 15
	// Microsoft forgot to hump their vendor prefix (#9572)
	function camelCase(string) {
		return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
	}
	var acceptData = function acceptData(owner) {

		// Accepts only:
		//  - Node
		//    - Node.ELEMENT_NODE
		//    - Node.DOCUMENT_NODE
		//  - Object
		//    - Any
		return owner.nodeType === 1 || owner.nodeType === 9 || !+owner.nodeType;
	};

	function Data() {
		this.expando = jQuery.expando + Data.uid++;
	}

	Data.uid = 1;

	Data.prototype = {

		cache: function cache(owner) {

			// Check if the owner object already has a cache
			var value = owner[this.expando];

			// If not, create one
			if (!value) {
				value = {};

				// We can accept data for non-element nodes in modern browsers,
				// but we should not, see #8335.
				// Always return an empty object.
				if (acceptData(owner)) {

					// If it is a node unlikely to be stringify-ed or looped over
					// use plain assignment
					if (owner.nodeType) {
						owner[this.expando] = value;

						// Otherwise secure it in a non-enumerable property
						// configurable must be true to allow the property to be
						// deleted when data is removed
					} else {
						Object.defineProperty(owner, this.expando, {
							value: value,
							configurable: true
						});
					}
				}
			}

			return value;
		},
		set: function set(owner, data, value) {
			var prop,
			    cache = this.cache(owner);

			// Handle: [ owner, key, value ] args
			// Always use camelCase key (gh-2257)
			if (typeof data === "string") {
				cache[camelCase(data)] = value;

				// Handle: [ owner, { properties } ] args
			} else {

				// Copy the properties one-by-one to the cache object
				for (prop in data) {
					cache[camelCase(prop)] = data[prop];
				}
			}
			return cache;
		},
		get: function get(owner, key) {
			return key === undefined ? this.cache(owner) :

			// Always use camelCase key (gh-2257)
			owner[this.expando] && owner[this.expando][camelCase(key)];
		},
		access: function access(owner, key, value) {

			// In cases where either:
			//
			//   1. No key was specified
			//   2. A string key was specified, but no value provided
			//
			// Take the "read" path and allow the get method to determine
			// which value to return, respectively either:
			//
			//   1. The entire cache object
			//   2. The data stored at the key
			//
			if (key === undefined || key && typeof key === "string" && value === undefined) {

				return this.get(owner, key);
			}

			// When the key is not a string, or both a key and value
			// are specified, set or extend (existing objects) with either:
			//
			//   1. An object of properties
			//   2. A key and value
			//
			this.set(owner, key, value);

			// Since the "set" path can have two possible entry points
			// return the expected data based on which path was taken[*]
			return value !== undefined ? value : key;
		},
		remove: function remove(owner, key) {
			var i,
			    cache = owner[this.expando];

			if (cache === undefined) {
				return;
			}

			if (key !== undefined) {

				// Support array or space separated string of keys
				if (Array.isArray(key)) {

					// If key is an array of keys...
					// We always set camelCase keys, so remove that.
					key = key.map(camelCase);
				} else {
					key = camelCase(key);

					// If a key with the spaces exists, use it.
					// Otherwise, create an array by matching non-whitespace
					key = key in cache ? [key] : key.match(rnothtmlwhite) || [];
				}

				i = key.length;

				while (i--) {
					delete cache[key[i]];
				}
			}

			// Remove the expando if there's no more data
			if (key === undefined || jQuery.isEmptyObject(cache)) {

				// Support: Chrome <=35 - 45
				// Webkit & Blink performance suffers when deleting properties
				// from DOM nodes, so set to undefined instead
				// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
				if (owner.nodeType) {
					owner[this.expando] = undefined;
				} else {
					delete owner[this.expando];
				}
			}
		},
		hasData: function hasData(owner) {
			var cache = owner[this.expando];
			return cache !== undefined && !jQuery.isEmptyObject(cache);
		}
	};
	var dataPriv = new Data();

	var dataUser = new Data();

	//	Implementation Summary
	//
	//	1. Enforce API surface and semantic compatibility with 1.9.x branch
	//	2. Improve the module's maintainability by reducing the storage
	//		paths to a single mechanism.
	//	3. Use the same single mechanism to support "private" and "user" data.
	//	4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
	//	5. Avoid exposing implementation details on user objects (eg. expando properties)
	//	6. Provide a clear path for implementation upgrade to WeakMap in 2014

	var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
	    rmultiDash = /[A-Z]/g;

	function getData(data) {
		if (data === "true") {
			return true;
		}

		if (data === "false") {
			return false;
		}

		if (data === "null") {
			return null;
		}

		// Only convert to a number if it doesn't change the string
		if (data === +data + "") {
			return +data;
		}

		if (rbrace.test(data)) {
			return JSON.parse(data);
		}

		return data;
	}

	function dataAttr(elem, key, data) {
		var name;

		// If nothing was found internally, try to fetch any
		// data from the HTML5 data-* attribute
		if (data === undefined && elem.nodeType === 1) {
			name = "data-" + key.replace(rmultiDash, "-$&").toLowerCase();
			data = elem.getAttribute(name);

			if (typeof data === "string") {
				try {
					data = getData(data);
				} catch (e) {}

				// Make sure we set the data so it isn't changed later
				dataUser.set(elem, key, data);
			} else {
				data = undefined;
			}
		}
		return data;
	}

	jQuery.extend({
		hasData: function hasData(elem) {
			return dataUser.hasData(elem) || dataPriv.hasData(elem);
		},

		data: function data(elem, name, _data) {
			return dataUser.access(elem, name, _data);
		},

		removeData: function removeData(elem, name) {
			dataUser.remove(elem, name);
		},

		// TODO: Now that all calls to _data and _removeData have been replaced
		// with direct calls to dataPriv methods, these can be deprecated.
		_data: function _data(elem, name, data) {
			return dataPriv.access(elem, name, data);
		},

		_removeData: function _removeData(elem, name) {
			dataPriv.remove(elem, name);
		}
	});

	jQuery.fn.extend({
		data: function data(key, value) {
			var i,
			    name,
			    data,
			    elem = this[0],
			    attrs = elem && elem.attributes;

			// Gets all values
			if (key === undefined) {
				if (this.length) {
					data = dataUser.get(elem);

					if (elem.nodeType === 1 && !dataPriv.get(elem, "hasDataAttrs")) {
						i = attrs.length;
						while (i--) {

							// Support: IE 11 only
							// The attrs elements can be null (#14894)
							if (attrs[i]) {
								name = attrs[i].name;
								if (name.indexOf("data-") === 0) {
									name = camelCase(name.slice(5));
									dataAttr(elem, name, data[name]);
								}
							}
						}
						dataPriv.set(elem, "hasDataAttrs", true);
					}
				}

				return data;
			}

			// Sets multiple values
			if ((typeof key === "undefined" ? "undefined" : _typeof(key)) === "object") {
				return this.each(function () {
					dataUser.set(this, key);
				});
			}

			return access(this, function (value) {
				var data;

				// The calling jQuery object (element matches) is not empty
				// (and therefore has an element appears at this[ 0 ]) and the
				// `value` parameter was not undefined. An empty jQuery object
				// will result in `undefined` for elem = this[ 0 ] which will
				// throw an exception if an attempt to read a data cache is made.
				if (elem && value === undefined) {

					// Attempt to get data from the cache
					// The key will always be camelCased in Data
					data = dataUser.get(elem, key);
					if (data !== undefined) {
						return data;
					}

					// Attempt to "discover" the data in
					// HTML5 custom data-* attrs
					data = dataAttr(elem, key);
					if (data !== undefined) {
						return data;
					}

					// We tried really hard, but the data doesn't exist.
					return;
				}

				// Set the data...
				this.each(function () {

					// We always store the camelCased key
					dataUser.set(this, key, value);
				});
			}, null, value, arguments.length > 1, null, true);
		},

		removeData: function removeData(key) {
			return this.each(function () {
				dataUser.remove(this, key);
			});
		}
	});

	jQuery.extend({
		queue: function queue(elem, type, data) {
			var queue;

			if (elem) {
				type = (type || "fx") + "queue";
				queue = dataPriv.get(elem, type);

				// Speed up dequeue by getting out quickly if this is just a lookup
				if (data) {
					if (!queue || Array.isArray(data)) {
						queue = dataPriv.access(elem, type, jQuery.makeArray(data));
					} else {
						queue.push(data);
					}
				}
				return queue || [];
			}
		},

		dequeue: function dequeue(elem, type) {
			type = type || "fx";

			var queue = jQuery.queue(elem, type),
			    startLength = queue.length,
			    fn = queue.shift(),
			    hooks = jQuery._queueHooks(elem, type),
			    next = function next() {
				jQuery.dequeue(elem, type);
			};

			// If the fx queue is dequeued, always remove the progress sentinel
			if (fn === "inprogress") {
				fn = queue.shift();
				startLength--;
			}

			if (fn) {

				// Add a progress sentinel to prevent the fx queue from being
				// automatically dequeued
				if (type === "fx") {
					queue.unshift("inprogress");
				}

				// Clear up the last queue stop function
				delete hooks.stop;
				fn.call(elem, next, hooks);
			}

			if (!startLength && hooks) {
				hooks.empty.fire();
			}
		},

		// Not public - generate a queueHooks object, or return the current one
		_queueHooks: function _queueHooks(elem, type) {
			var key = type + "queueHooks";
			return dataPriv.get(elem, key) || dataPriv.access(elem, key, {
				empty: jQuery.Callbacks("once memory").add(function () {
					dataPriv.remove(elem, [type + "queue", key]);
				})
			});
		}
	});

	jQuery.fn.extend({
		queue: function queue(type, data) {
			var setter = 2;

			if (typeof type !== "string") {
				data = type;
				type = "fx";
				setter--;
			}

			if (arguments.length < setter) {
				return jQuery.queue(this[0], type);
			}

			return data === undefined ? this : this.each(function () {
				var queue = jQuery.queue(this, type, data);

				// Ensure a hooks for this queue
				jQuery._queueHooks(this, type);

				if (type === "fx" && queue[0] !== "inprogress") {
					jQuery.dequeue(this, type);
				}
			});
		},
		dequeue: function dequeue(type) {
			return this.each(function () {
				jQuery.dequeue(this, type);
			});
		},
		clearQueue: function clearQueue(type) {
			return this.queue(type || "fx", []);
		},

		// Get a promise resolved when queues of a certain type
		// are emptied (fx is the type by default)
		promise: function promise(type, obj) {
			var tmp,
			    count = 1,
			    defer = jQuery.Deferred(),
			    elements = this,
			    i = this.length,
			    resolve = function resolve() {
				if (! --count) {
					defer.resolveWith(elements, [elements]);
				}
			};

			if (typeof type !== "string") {
				obj = type;
				type = undefined;
			}
			type = type || "fx";

			while (i--) {
				tmp = dataPriv.get(elements[i], type + "queueHooks");
				if (tmp && tmp.empty) {
					count++;
					tmp.empty.add(resolve);
				}
			}
			resolve();
			return defer.promise(obj);
		}
	});
	var pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source;

	var rcssNum = new RegExp("^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i");

	var cssExpand = ["Top", "Right", "Bottom", "Left"];

	var isHiddenWithinTree = function isHiddenWithinTree(elem, el) {

		// isHiddenWithinTree might be called from jQuery#filter function;
		// in that case, element will be second argument
		elem = el || elem;

		// Inline style trumps all
		return elem.style.display === "none" || elem.style.display === "" &&

		// Otherwise, check computed style
		// Support: Firefox <=43 - 45
		// Disconnected elements can have computed display: none, so first confirm that elem is
		// in the document.
		jQuery.contains(elem.ownerDocument, elem) && jQuery.css(elem, "display") === "none";
	};

	var swap = function swap(elem, options, callback, args) {
		var ret,
		    name,
		    old = {};

		// Remember the old values, and insert the new ones
		for (name in options) {
			old[name] = elem.style[name];
			elem.style[name] = options[name];
		}

		ret = callback.apply(elem, args || []);

		// Revert the old values
		for (name in options) {
			elem.style[name] = old[name];
		}

		return ret;
	};

	function adjustCSS(elem, prop, valueParts, tween) {
		var adjusted,
		    scale,
		    maxIterations = 20,
		    currentValue = tween ? function () {
			return tween.cur();
		} : function () {
			return jQuery.css(elem, prop, "");
		},
		    initial = currentValue(),
		    unit = valueParts && valueParts[3] || (jQuery.cssNumber[prop] ? "" : "px"),


		// Starting value computation is required for potential unit mismatches
		initialInUnit = (jQuery.cssNumber[prop] || unit !== "px" && +initial) && rcssNum.exec(jQuery.css(elem, prop));

		if (initialInUnit && initialInUnit[3] !== unit) {

			// Support: Firefox <=54
			// Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144)
			initial = initial / 2;

			// Trust units reported by jQuery.css
			unit = unit || initialInUnit[3];

			// Iteratively approximate from a nonzero starting point
			initialInUnit = +initial || 1;

			while (maxIterations--) {

				// Evaluate and update our best guess (doubling guesses that zero out).
				// Finish if the scale equals or crosses 1 (making the old*new product non-positive).
				jQuery.style(elem, prop, initialInUnit + unit);
				if ((1 - scale) * (1 - (scale = currentValue() / initial || 0.5)) <= 0) {
					maxIterations = 0;
				}
				initialInUnit = initialInUnit / scale;
			}

			initialInUnit = initialInUnit * 2;
			jQuery.style(elem, prop, initialInUnit + unit);

			// Make sure we update the tween properties later on
			valueParts = valueParts || [];
		}

		if (valueParts) {
			initialInUnit = +initialInUnit || +initial || 0;

			// Apply relative offset (+=/-=) if specified
			adjusted = valueParts[1] ? initialInUnit + (valueParts[1] + 1) * valueParts[2] : +valueParts[2];
			if (tween) {
				tween.unit = unit;
				tween.start = initialInUnit;
				tween.end = adjusted;
			}
		}
		return adjusted;
	}

	var defaultDisplayMap = {};

	function getDefaultDisplay(elem) {
		var temp,
		    doc = elem.ownerDocument,
		    nodeName = elem.nodeName,
		    display = defaultDisplayMap[nodeName];

		if (display) {
			return display;
		}

		temp = doc.body.appendChild(doc.createElement(nodeName));
		display = jQuery.css(temp, "display");

		temp.parentNode.removeChild(temp);

		if (display === "none") {
			display = "block";
		}
		defaultDisplayMap[nodeName] = display;

		return display;
	}

	function showHide(elements, show) {
		var display,
		    elem,
		    values = [],
		    index = 0,
		    length = elements.length;

		// Determine new display value for elements that need to change
		for (; index < length; index++) {
			elem = elements[index];
			if (!elem.style) {
				continue;
			}

			display = elem.style.display;
			if (show) {

				// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
				// check is required in this first loop unless we have a nonempty display value (either
				// inline or about-to-be-restored)
				if (display === "none") {
					values[index] = dataPriv.get(elem, "display") || null;
					if (!values[index]) {
						elem.style.display = "";
					}
				}
				if (elem.style.display === "" && isHiddenWithinTree(elem)) {
					values[index] = getDefaultDisplay(elem);
				}
			} else {
				if (display !== "none") {
					values[index] = "none";

					// Remember what we're overwriting
					dataPriv.set(elem, "display", display);
				}
			}
		}

		// Set the display of the elements in a second loop to avoid constant reflow
		for (index = 0; index < length; index++) {
			if (values[index] != null) {
				elements[index].style.display = values[index];
			}
		}

		return elements;
	}

	jQuery.fn.extend({
		show: function show() {
			return showHide(this, true);
		},
		hide: function hide() {
			return showHide(this);
		},
		toggle: function toggle(state) {
			if (typeof state === "boolean") {
				return state ? this.show() : this.hide();
			}

			return this.each(function () {
				if (isHiddenWithinTree(this)) {
					jQuery(this).show();
				} else {
					jQuery(this).hide();
				}
			});
		}
	});
	var rcheckableType = /^(?:checkbox|radio)$/i;

	var rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]+)/i;

	var rscriptType = /^$|^module$|\/(?:java|ecma)script/i;

	// We have to close these tags to support XHTML (#13200)
	var wrapMap = {

		// Support: IE <=9 only
		option: [1, "<select multiple='multiple'>", "</select>"],

		// XHTML parsers do not magically insert elements in the
		// same way that tag soup parsers do. So we cannot shorten
		// this by omitting <tbody> or other required elements.
		thead: [1, "<table>", "</table>"],
		col: [2, "<table><colgroup>", "</colgroup></table>"],
		tr: [2, "<table><tbody>", "</tbody></table>"],
		td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],

		_default: [0, "", ""]
	};

	// Support: IE <=9 only
	wrapMap.optgroup = wrapMap.option;

	wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
	wrapMap.th = wrapMap.td;

	function getAll(context, tag) {

		// Support: IE <=9 - 11 only
		// Use typeof to avoid zero-argument method invocation on host objects (#15151)
		var ret;

		if (typeof context.getElementsByTagName !== "undefined") {
			ret = context.getElementsByTagName(tag || "*");
		} else if (typeof context.querySelectorAll !== "undefined") {
			ret = context.querySelectorAll(tag || "*");
		} else {
			ret = [];
		}

		if (tag === undefined || tag && nodeName(context, tag)) {
			return jQuery.merge([context], ret);
		}

		return ret;
	}

	// Mark scripts as having already been evaluated
	function setGlobalEval(elems, refElements) {
		var i = 0,
		    l = elems.length;

		for (; i < l; i++) {
			dataPriv.set(elems[i], "globalEval", !refElements || dataPriv.get(refElements[i], "globalEval"));
		}
	}

	var rhtml = /<|&#?\w+;/;

	function buildFragment(elems, context, scripts, selection, ignored) {
		var elem,
		    tmp,
		    tag,
		    wrap,
		    contains,
		    j,
		    fragment = context.createDocumentFragment(),
		    nodes = [],
		    i = 0,
		    l = elems.length;

		for (; i < l; i++) {
			elem = elems[i];

			if (elem || elem === 0) {

				// Add nodes directly
				if (toType(elem) === "object") {

					// Support: Android <=4.0 only, PhantomJS 1 only
					// push.apply(_, arraylike) throws on ancient WebKit
					jQuery.merge(nodes, elem.nodeType ? [elem] : elem);

					// Convert non-html into a text node
				} else if (!rhtml.test(elem)) {
					nodes.push(context.createTextNode(elem));

					// Convert html into DOM nodes
				} else {
					tmp = tmp || fragment.appendChild(context.createElement("div"));

					// Deserialize a standard representation
					tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase();
					wrap = wrapMap[tag] || wrapMap._default;
					tmp.innerHTML = wrap[1] + jQuery.htmlPrefilter(elem) + wrap[2];

					// Descend through wrappers to the right content
					j = wrap[0];
					while (j--) {
						tmp = tmp.lastChild;
					}

					// Support: Android <=4.0 only, PhantomJS 1 only
					// push.apply(_, arraylike) throws on ancient WebKit
					jQuery.merge(nodes, tmp.childNodes);

					// Remember the top-level container
					tmp = fragment.firstChild;

					// Ensure the created nodes are orphaned (#12392)
					tmp.textContent = "";
				}
			}
		}

		// Remove wrapper from fragment
		fragment.textContent = "";

		i = 0;
		while (elem = nodes[i++]) {

			// Skip elements already in the context collection (trac-4087)
			if (selection && jQuery.inArray(elem, selection) > -1) {
				if (ignored) {
					ignored.push(elem);
				}
				continue;
			}

			contains = jQuery.contains(elem.ownerDocument, elem);

			// Append to fragment
			tmp = getAll(fragment.appendChild(elem), "script");

			// Preserve script evaluation history
			if (contains) {
				setGlobalEval(tmp);
			}

			// Capture executables
			if (scripts) {
				j = 0;
				while (elem = tmp[j++]) {
					if (rscriptType.test(elem.type || "")) {
						scripts.push(elem);
					}
				}
			}
		}

		return fragment;
	}

	(function () {
		var fragment = document.createDocumentFragment(),
		    div = fragment.appendChild(document.createElement("div")),
		    input = document.createElement("input");

		// Support: Android 4.0 - 4.3 only
		// Check state lost if the name is set (#11217)
		// Support: Windows Web Apps (WWA)
		// `name` and `type` must use .setAttribute for WWA (#14901)
		input.setAttribute("type", "radio");
		input.setAttribute("checked", "checked");
		input.setAttribute("name", "t");

		div.appendChild(input);

		// Support: Android <=4.1 only
		// Older WebKit doesn't clone checked state correctly in fragments
		support.checkClone = div.cloneNode(true).cloneNode(true).lastChild.checked;

		// Support: IE <=11 only
		// Make sure textarea (and checkbox) defaultValue is properly cloned
		div.innerHTML = "<textarea>x</textarea>";
		support.noCloneChecked = !!div.cloneNode(true).lastChild.defaultValue;
	})();
	var documentElement = document.documentElement;

	var rkeyEvent = /^key/,
	    rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
	    rtypenamespace = /^([^.]*)(?:\.(.+)|)/;

	function returnTrue() {
		return true;
	}

	function returnFalse() {
		return false;
	}

	// Support: IE <=9 only
	// See #13393 for more info
	function safeActiveElement() {
		try {
			return document.activeElement;
		} catch (err) {}
	}

	function _on(elem, types, selector, data, fn, one) {
		var origFn, type;

		// Types can be a map of types/handlers
		if ((typeof types === "undefined" ? "undefined" : _typeof(types)) === "object") {

			// ( types-Object, selector, data )
			if (typeof selector !== "string") {

				// ( types-Object, data )
				data = data || selector;
				selector = undefined;
			}
			for (type in types) {
				_on(elem, type, selector, data, types[type], one);
			}
			return elem;
		}

		if (data == null && fn == null) {

			// ( types, fn )
			fn = selector;
			data = selector = undefined;
		} else if (fn == null) {
			if (typeof selector === "string") {

				// ( types, selector, fn )
				fn = data;
				data = undefined;
			} else {

				// ( types, data, fn )
				fn = data;
				data = selector;
				selector = undefined;
			}
		}
		if (fn === false) {
			fn = returnFalse;
		} else if (!fn) {
			return elem;
		}

		if (one === 1) {
			origFn = fn;
			fn = function fn(event) {

				// Can use an empty set, since event contains the info
				jQuery().off(event);
				return origFn.apply(this, arguments);
			};

			// Use same guid so caller can remove using origFn
			fn.guid = origFn.guid || (origFn.guid = jQuery.guid++);
		}
		return elem.each(function () {
			jQuery.event.add(this, types, fn, data, selector);
		});
	}

	/*
  * Helper functions for managing events -- not part of the public interface.
  * Props to Dean Edwards' addEvent library for many of the ideas.
  */
	jQuery.event = {

		global: {},

		add: function add(elem, types, handler, data, selector) {

			var handleObjIn,
			    eventHandle,
			    tmp,
			    events,
			    t,
			    handleObj,
			    special,
			    handlers,
			    type,
			    namespaces,
			    origType,
			    elemData = dataPriv.get(elem);

			// Don't attach events to noData or text/comment nodes (but allow plain objects)
			if (!elemData) {
				return;
			}

			// Caller can pass in an object of custom data in lieu of the handler
			if (handler.handler) {
				handleObjIn = handler;
				handler = handleObjIn.handler;
				selector = handleObjIn.selector;
			}

			// Ensure that invalid selectors throw exceptions at attach time
			// Evaluate against documentElement in case elem is a non-element node (e.g., document)
			if (selector) {
				jQuery.find.matchesSelector(documentElement, selector);
			}

			// Make sure that the handler has a unique ID, used to find/remove it later
			if (!handler.guid) {
				handler.guid = jQuery.guid++;
			}

			// Init the element's event structure and main handler, if this is the first
			if (!(events = elemData.events)) {
				events = elemData.events = {};
			}
			if (!(eventHandle = elemData.handle)) {
				eventHandle = elemData.handle = function (e) {

					// Discard the second event of a jQuery.event.trigger() and
					// when an event is called after a page has unloaded
					return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply(elem, arguments) : undefined;
				};
			}

			// Handle multiple events separated by a space
			types = (types || "").match(rnothtmlwhite) || [""];
			t = types.length;
			while (t--) {
				tmp = rtypenamespace.exec(types[t]) || [];
				type = origType = tmp[1];
				namespaces = (tmp[2] || "").split(".").sort();

				// There *must* be a type, no attaching namespace-only handlers
				if (!type) {
					continue;
				}

				// If event changes its type, use the special event handlers for the changed type
				special = jQuery.event.special[type] || {};

				// If selector defined, determine special event api type, otherwise given type
				type = (selector ? special.delegateType : special.bindType) || type;

				// Update special based on newly reset type
				special = jQuery.event.special[type] || {};

				// handleObj is passed to all event handlers
				handleObj = jQuery.extend({
					type: type,
					origType: origType,
					data: data,
					handler: handler,
					guid: handler.guid,
					selector: selector,
					needsContext: selector && jQuery.expr.match.needsContext.test(selector),
					namespace: namespaces.join(".")
				}, handleObjIn);

				// Init the event handler queue if we're the first
				if (!(handlers = events[type])) {
					handlers = events[type] = [];
					handlers.delegateCount = 0;

					// Only use addEventListener if the special events handler returns false
					if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {

						if (elem.addEventListener) {
							elem.addEventListener(type, eventHandle);
						}
					}
				}

				if (special.add) {
					special.add.call(elem, handleObj);

					if (!handleObj.handler.guid) {
						handleObj.handler.guid = handler.guid;
					}
				}

				// Add to the element's handler list, delegates in front
				if (selector) {
					handlers.splice(handlers.delegateCount++, 0, handleObj);
				} else {
					handlers.push(handleObj);
				}

				// Keep track of which events have ever been used, for event optimization
				jQuery.event.global[type] = true;
			}
		},

		// Detach an event or set of events from an element
		remove: function remove(elem, types, handler, selector, mappedTypes) {

			var j,
			    origCount,
			    tmp,
			    events,
			    t,
			    handleObj,
			    special,
			    handlers,
			    type,
			    namespaces,
			    origType,
			    elemData = dataPriv.hasData(elem) && dataPriv.get(elem);

			if (!elemData || !(events = elemData.events)) {
				return;
			}

			// Once for each type.namespace in types; type may be omitted
			types = (types || "").match(rnothtmlwhite) || [""];
			t = types.length;
			while (t--) {
				tmp = rtypenamespace.exec(types[t]) || [];
				type = origType = tmp[1];
				namespaces = (tmp[2] || "").split(".").sort();

				// Unbind all events (on this namespace, if provided) for the element
				if (!type) {
					for (type in events) {
						jQuery.event.remove(elem, type + types[t], handler, selector, true);
					}
					continue;
				}

				special = jQuery.event.special[type] || {};
				type = (selector ? special.delegateType : special.bindType) || type;
				handlers = events[type] || [];
				tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)");

				// Remove matching events
				origCount = j = handlers.length;
				while (j--) {
					handleObj = handlers[j];

					if ((mappedTypes || origType === handleObj.origType) && (!handler || handler.guid === handleObj.guid) && (!tmp || tmp.test(handleObj.namespace)) && (!selector || selector === handleObj.selector || selector === "**" && handleObj.selector)) {
						handlers.splice(j, 1);

						if (handleObj.selector) {
							handlers.delegateCount--;
						}
						if (special.remove) {
							special.remove.call(elem, handleObj);
						}
					}
				}

				// Remove generic event handler if we removed something and no more handlers exist
				// (avoids potential for endless recursion during removal of special event handlers)
				if (origCount && !handlers.length) {
					if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) {

						jQuery.removeEvent(elem, type, elemData.handle);
					}

					delete events[type];
				}
			}

			// Remove data and the expando if it's no longer used
			if (jQuery.isEmptyObject(events)) {
				dataPriv.remove(elem, "handle events");
			}
		},

		dispatch: function dispatch(nativeEvent) {

			// Make a writable jQuery.Event from the native event object
			var event = jQuery.event.fix(nativeEvent);

			var i,
			    j,
			    ret,
			    matched,
			    handleObj,
			    handlerQueue,
			    args = new Array(arguments.length),
			    handlers = (dataPriv.get(this, "events") || {})[event.type] || [],
			    special = jQuery.event.special[event.type] || {};

			// Use the fix-ed jQuery.Event rather than the (read-only) native event
			args[0] = event;

			for (i = 1; i < arguments.length; i++) {
				args[i] = arguments[i];
			}

			event.delegateTarget = this;

			// Call the preDispatch hook for the mapped type, and let it bail if desired
			if (special.preDispatch && special.preDispatch.call(this, event) === false) {
				return;
			}

			// Determine handlers
			handlerQueue = jQuery.event.handlers.call(this, event, handlers);

			// Run delegates first; they may want to stop propagation beneath us
			i = 0;
			while ((matched = handlerQueue[i++]) && !event.isPropagationStopped()) {
				event.currentTarget = matched.elem;

				j = 0;
				while ((handleObj = matched.handlers[j++]) && !event.isImmediatePropagationStopped()) {

					// Triggered event must either 1) have no namespace, or 2) have namespace(s)
					// a subset or equal to those in the bound event (both can have no namespace).
					if (!event.rnamespace || event.rnamespace.test(handleObj.namespace)) {

						event.handleObj = handleObj;
						event.data = handleObj.data;

						ret = ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler).apply(matched.elem, args);

						if (ret !== undefined) {
							if ((event.result = ret) === false) {
								event.preventDefault();
								event.stopPropagation();
							}
						}
					}
				}
			}

			// Call the postDispatch hook for the mapped type
			if (special.postDispatch) {
				special.postDispatch.call(this, event);
			}

			return event.result;
		},

		handlers: function handlers(event, _handlers) {
			var i,
			    handleObj,
			    sel,
			    matchedHandlers,
			    matchedSelectors,
			    handlerQueue = [],
			    delegateCount = _handlers.delegateCount,
			    cur = event.target;

			// Find delegate handlers
			if (delegateCount &&

			// Support: IE <=9
			// Black-hole SVG <use> instance trees (trac-13180)
			cur.nodeType &&

			// Support: Firefox <=42
			// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
			// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
			// Support: IE 11 only
			// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
			!(event.type === "click" && event.button >= 1)) {

				for (; cur !== this; cur = cur.parentNode || this) {

					// Don't check non-elements (#13208)
					// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
					if (cur.nodeType === 1 && !(event.type === "click" && cur.disabled === true)) {
						matchedHandlers = [];
						matchedSelectors = {};
						for (i = 0; i < delegateCount; i++) {
							handleObj = _handlers[i];

							// Don't conflict with Object.prototype properties (#13203)
							sel = handleObj.selector + " ";

							if (matchedSelectors[sel] === undefined) {
								matchedSelectors[sel] = handleObj.needsContext ? jQuery(sel, this).index(cur) > -1 : jQuery.find(sel, this, null, [cur]).length;
							}
							if (matchedSelectors[sel]) {
								matchedHandlers.push(handleObj);
							}
						}
						if (matchedHandlers.length) {
							handlerQueue.push({ elem: cur, handlers: matchedHandlers });
						}
					}
				}
			}

			// Add the remaining (directly-bound) handlers
			cur = this;
			if (delegateCount < _handlers.length) {
				handlerQueue.push({ elem: cur, handlers: _handlers.slice(delegateCount) });
			}

			return handlerQueue;
		},

		addProp: function addProp(name, hook) {
			Object.defineProperty(jQuery.Event.prototype, name, {
				enumerable: true,
				configurable: true,

				get: isFunction(hook) ? function () {
					if (this.originalEvent) {
						return hook(this.originalEvent);
					}
				} : function () {
					if (this.originalEvent) {
						return this.originalEvent[name];
					}
				},

				set: function set(value) {
					Object.defineProperty(this, name, {
						enumerable: true,
						configurable: true,
						writable: true,
						value: value
					});
				}
			});
		},

		fix: function fix(originalEvent) {
			return originalEvent[jQuery.expando] ? originalEvent : new jQuery.Event(originalEvent);
		},

		special: {
			load: {

				// Prevent triggered image.load events from bubbling to window.load
				noBubble: true
			},
			focus: {

				// Fire native event if possible so blur/focus sequence is correct
				trigger: function trigger() {
					if (this !== safeActiveElement() && this.focus) {
						this.focus();
						return false;
					}
				},
				delegateType: "focusin"
			},
			blur: {
				trigger: function trigger() {
					if (this === safeActiveElement() && this.blur) {
						this.blur();
						return false;
					}
				},
				delegateType: "focusout"
			},
			click: {

				// For checkbox, fire native event so checked state will be right
				trigger: function trigger() {
					if (this.type === "checkbox" && this.click && nodeName(this, "input")) {
						this.click();
						return false;
					}
				},

				// For cross-browser consistency, don't fire native .click() on links
				_default: function _default(event) {
					return nodeName(event.target, "a");
				}
			},

			beforeunload: {
				postDispatch: function postDispatch(event) {

					// Support: Firefox 20+
					// Firefox doesn't alert if the returnValue field is not set.
					if (event.result !== undefined && event.originalEvent) {
						event.originalEvent.returnValue = event.result;
					}
				}
			}
		}
	};

	jQuery.removeEvent = function (elem, type, handle) {

		// This "if" is needed for plain objects
		if (elem.removeEventListener) {
			elem.removeEventListener(type, handle);
		}
	};

	jQuery.Event = function (src, props) {

		// Allow instantiation without the 'new' keyword
		if (!(this instanceof jQuery.Event)) {
			return new jQuery.Event(src, props);
		}

		// Event object
		if (src && src.type) {
			this.originalEvent = src;
			this.type = src.type;

			// Events bubbling up the document may have been marked as prevented
			// by a handler lower down the tree; reflect the correct value.
			this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined &&

			// Support: Android <=2.3 only
			src.returnValue === false ? returnTrue : returnFalse;

			// Create target properties
			// Support: Safari <=6 - 7 only
			// Target should not be a text node (#504, #13143)
			this.target = src.target && src.target.nodeType === 3 ? src.target.parentNode : src.target;

			this.currentTarget = src.currentTarget;
			this.relatedTarget = src.relatedTarget;

			// Event type
		} else {
			this.type = src;
		}

		// Put explicitly provided properties onto the event object
		if (props) {
			jQuery.extend(this, props);
		}

		// Create a timestamp if incoming event doesn't have one
		this.timeStamp = src && src.timeStamp || Date.now();

		// Mark it as fixed
		this[jQuery.expando] = true;
	};

	// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
	// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
	jQuery.Event.prototype = {
		constructor: jQuery.Event,
		isDefaultPrevented: returnFalse,
		isPropagationStopped: returnFalse,
		isImmediatePropagationStopped: returnFalse,
		isSimulated: false,

		preventDefault: function preventDefault() {
			var e = this.originalEvent;

			this.isDefaultPrevented = returnTrue;

			if (e && !this.isSimulated) {
				e.preventDefault();
			}
		},
		stopPropagation: function stopPropagation() {
			var e = this.originalEvent;

			this.isPropagationStopped = returnTrue;

			if (e && !this.isSimulated) {
				e.stopPropagation();
			}
		},
		stopImmediatePropagation: function stopImmediatePropagation() {
			var e = this.originalEvent;

			this.isImmediatePropagationStopped = returnTrue;

			if (e && !this.isSimulated) {
				e.stopImmediatePropagation();
			}

			this.stopPropagation();
		}
	};

	// Includes all common event props including KeyEvent and MouseEvent specific props
	jQuery.each({
		altKey: true,
		bubbles: true,
		cancelable: true,
		changedTouches: true,
		ctrlKey: true,
		detail: true,
		eventPhase: true,
		metaKey: true,
		pageX: true,
		pageY: true,
		shiftKey: true,
		view: true,
		"char": true,
		charCode: true,
		key: true,
		keyCode: true,
		button: true,
		buttons: true,
		clientX: true,
		clientY: true,
		offsetX: true,
		offsetY: true,
		pointerId: true,
		pointerType: true,
		screenX: true,
		screenY: true,
		targetTouches: true,
		toElement: true,
		touches: true,

		which: function which(event) {
			var button = event.button;

			// Add which for key events
			if (event.which == null && rkeyEvent.test(event.type)) {
				return event.charCode != null ? event.charCode : event.keyCode;
			}

			// Add which for click: 1 === left; 2 === middle; 3 === right
			if (!event.which && button !== undefined && rmouseEvent.test(event.type)) {
				if (button & 1) {
					return 1;
				}

				if (button & 2) {
					return 3;
				}

				if (button & 4) {
					return 2;
				}

				return 0;
			}

			return event.which;
		}
	}, jQuery.event.addProp);

	// Create mouseenter/leave events using mouseover/out and event-time checks
	// so that event delegation works in jQuery.
	// Do the same for pointerenter/pointerleave and pointerover/pointerout
	//
	// Support: Safari 7 only
	// Safari sends mouseenter too often; see:
	// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
	// for the description of the bug (it existed in older Chrome versions as well).
	jQuery.each({
		mouseenter: "mouseover",
		mouseleave: "mouseout",
		pointerenter: "pointerover",
		pointerleave: "pointerout"
	}, function (orig, fix) {
		jQuery.event.special[orig] = {
			delegateType: fix,
			bindType: fix,

			handle: function handle(event) {
				var ret,
				    target = this,
				    related = event.relatedTarget,
				    handleObj = event.handleObj;

				// For mouseenter/leave call the handler if related is outside the target.
				// NB: No relatedTarget if the mouse left/entered the browser window
				if (!related || related !== target && !jQuery.contains(target, related)) {
					event.type = handleObj.origType;
					ret = handleObj.handler.apply(this, arguments);
					event.type = fix;
				}
				return ret;
			}
		};
	});

	jQuery.fn.extend({

		on: function on(types, selector, data, fn) {
			return _on(this, types, selector, data, fn);
		},
		one: function one(types, selector, data, fn) {
			return _on(this, types, selector, data, fn, 1);
		},
		off: function off(types, selector, fn) {
			var handleObj, type;
			if (types && types.preventDefault && types.handleObj) {

				// ( event )  dispatched jQuery.Event
				handleObj = types.handleObj;
				jQuery(types.delegateTarget).off(handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler);
				return this;
			}
			if ((typeof types === "undefined" ? "undefined" : _typeof(types)) === "object") {

				// ( types-object [, selector] )
				for (type in types) {
					this.off(type, selector, types[type]);
				}
				return this;
			}
			if (selector === false || typeof selector === "function") {

				// ( types [, fn] )
				fn = selector;
				selector = undefined;
			}
			if (fn === false) {
				fn = returnFalse;
			}
			return this.each(function () {
				jQuery.event.remove(this, types, fn, selector);
			});
		}
	});

	var

	/* eslint-disable max-len */

	// See https://github.com/eslint/eslint/issues/3229
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,


	/* eslint-enable */

	// Support: IE <=10 - 11, Edge 12 - 13 only
	// In IE/Edge using regex groups here causes severe slowdowns.
	// See https://connect.microsoft.com/IE/feedback/details/1736512/
	rnoInnerhtml = /<script|<style|<link/i,


	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	    rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;

	// Prefer a tbody over its parent table for containing new rows
	function manipulationTarget(elem, content) {
		if (nodeName(elem, "table") && nodeName(content.nodeType !== 11 ? content : content.firstChild, "tr")) {

			return jQuery(elem).children("tbody")[0] || elem;
		}

		return elem;
	}

	// Replace/restore the type attribute of script elements for safe DOM manipulation
	function disableScript(elem) {
		elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
		return elem;
	}
	function restoreScript(elem) {
		if ((elem.type || "").slice(0, 5) === "true/") {
			elem.type = elem.type.slice(5);
		} else {
			elem.removeAttribute("type");
		}

		return elem;
	}

	function cloneCopyEvent(src, dest) {
		var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;

		if (dest.nodeType !== 1) {
			return;
		}

		// 1. Copy private data: events, handlers, etc.
		if (dataPriv.hasData(src)) {
			pdataOld = dataPriv.access(src);
			pdataCur = dataPriv.set(dest, pdataOld);
			events = pdataOld.events;

			if (events) {
				delete pdataCur.handle;
				pdataCur.events = {};

				for (type in events) {
					for (i = 0, l = events[type].length; i < l; i++) {
						jQuery.event.add(dest, type, events[type][i]);
					}
				}
			}
		}

		// 2. Copy user data
		if (dataUser.hasData(src)) {
			udataOld = dataUser.access(src);
			udataCur = jQuery.extend({}, udataOld);

			dataUser.set(dest, udataCur);
		}
	}

	// Fix IE bugs, see support tests
	function fixInput(src, dest) {
		var nodeName = dest.nodeName.toLowerCase();

		// Fails to persist the checked state of a cloned checkbox or radio button.
		if (nodeName === "input" && rcheckableType.test(src.type)) {
			dest.checked = src.checked;

			// Fails to return the selected option to the default selected state when cloning options
		} else if (nodeName === "input" || nodeName === "textarea") {
			dest.defaultValue = src.defaultValue;
		}
	}

	function domManip(collection, args, callback, ignored) {

		// Flatten any nested arrays
		args = concat.apply([], args);

		var fragment,
		    first,
		    scripts,
		    hasScripts,
		    node,
		    doc,
		    i = 0,
		    l = collection.length,
		    iNoClone = l - 1,
		    value = args[0],
		    valueIsFunction = isFunction(value);

		// We can't cloneNode fragments that contain checked, in WebKit
		if (valueIsFunction || l > 1 && typeof value === "string" && !support.checkClone && rchecked.test(value)) {
			return collection.each(function (index) {
				var self = collection.eq(index);
				if (valueIsFunction) {
					args[0] = value.call(this, index, self.html());
				}
				domManip(self, args, callback, ignored);
			});
		}

		if (l) {
			fragment = buildFragment(args, collection[0].ownerDocument, false, collection, ignored);
			first = fragment.firstChild;

			if (fragment.childNodes.length === 1) {
				fragment = first;
			}

			// Require either new content or an interest in ignored elements to invoke the callback
			if (first || ignored) {
				scripts = jQuery.map(getAll(fragment, "script"), disableScript);
				hasScripts = scripts.length;

				// Use the original fragment for the last item
				// instead of the first because it can end up
				// being emptied incorrectly in certain situations (#8070).
				for (; i < l; i++) {
					node = fragment;

					if (i !== iNoClone) {
						node = jQuery.clone(node, true, true);

						// Keep references to cloned scripts for later restoration
						if (hasScripts) {

							// Support: Android <=4.0 only, PhantomJS 1 only
							// push.apply(_, arraylike) throws on ancient WebKit
							jQuery.merge(scripts, getAll(node, "script"));
						}
					}

					callback.call(collection[i], node, i);
				}

				if (hasScripts) {
					doc = scripts[scripts.length - 1].ownerDocument;

					// Reenable scripts
					jQuery.map(scripts, restoreScript);

					// Evaluate executable scripts on first document insertion
					for (i = 0; i < hasScripts; i++) {
						node = scripts[i];
						if (rscriptType.test(node.type || "") && !dataPriv.access(node, "globalEval") && jQuery.contains(doc, node)) {

							if (node.src && (node.type || "").toLowerCase() !== "module") {

								// Optional AJAX dependency, but won't run scripts if not present
								if (jQuery._evalUrl) {
									jQuery._evalUrl(node.src);
								}
							} else {
								DOMEval(node.textContent.replace(rcleanScript, ""), doc, node);
							}
						}
					}
				}
			}
		}

		return collection;
	}

	function _remove(elem, selector, keepData) {
		var node,
		    nodes = selector ? jQuery.filter(selector, elem) : elem,
		    i = 0;

		for (; (node = nodes[i]) != null; i++) {
			if (!keepData && node.nodeType === 1) {
				jQuery.cleanData(getAll(node));
			}

			if (node.parentNode) {
				if (keepData && jQuery.contains(node.ownerDocument, node)) {
					setGlobalEval(getAll(node, "script"));
				}
				node.parentNode.removeChild(node);
			}
		}

		return elem;
	}

	jQuery.extend({
		htmlPrefilter: function htmlPrefilter(html) {
			return html.replace(rxhtmlTag, "<$1></$2>");
		},

		clone: function clone(elem, dataAndEvents, deepDataAndEvents) {
			var i,
			    l,
			    srcElements,
			    destElements,
			    clone = elem.cloneNode(true),
			    inPage = jQuery.contains(elem.ownerDocument, elem);

			// Fix IE cloning issues
			if (!support.noCloneChecked && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) {

				// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
				destElements = getAll(clone);
				srcElements = getAll(elem);

				for (i = 0, l = srcElements.length; i < l; i++) {
					fixInput(srcElements[i], destElements[i]);
				}
			}

			// Copy the events from the original to the clone
			if (dataAndEvents) {
				if (deepDataAndEvents) {
					srcElements = srcElements || getAll(elem);
					destElements = destElements || getAll(clone);

					for (i = 0, l = srcElements.length; i < l; i++) {
						cloneCopyEvent(srcElements[i], destElements[i]);
					}
				} else {
					cloneCopyEvent(elem, clone);
				}
			}

			// Preserve script evaluation history
			destElements = getAll(clone, "script");
			if (destElements.length > 0) {
				setGlobalEval(destElements, !inPage && getAll(elem, "script"));
			}

			// Return the cloned set
			return clone;
		},

		cleanData: function cleanData(elems) {
			var data,
			    elem,
			    type,
			    special = jQuery.event.special,
			    i = 0;

			for (; (elem = elems[i]) !== undefined; i++) {
				if (acceptData(elem)) {
					if (data = elem[dataPriv.expando]) {
						if (data.events) {
							for (type in data.events) {
								if (special[type]) {
									jQuery.event.remove(elem, type);

									// This is a shortcut to avoid jQuery.event.remove's overhead
								} else {
									jQuery.removeEvent(elem, type, data.handle);
								}
							}
						}

						// Support: Chrome <=35 - 45+
						// Assign undefined instead of using delete, see Data#remove
						elem[dataPriv.expando] = undefined;
					}
					if (elem[dataUser.expando]) {

						// Support: Chrome <=35 - 45+
						// Assign undefined instead of using delete, see Data#remove
						elem[dataUser.expando] = undefined;
					}
				}
			}
		}
	});

	jQuery.fn.extend({
		detach: function detach(selector) {
			return _remove(this, selector, true);
		},

		remove: function remove(selector) {
			return _remove(this, selector);
		},

		text: function text(value) {
			return access(this, function (value) {
				return value === undefined ? jQuery.text(this) : this.empty().each(function () {
					if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
						this.textContent = value;
					}
				});
			}, null, value, arguments.length);
		},

		append: function append() {
			return domManip(this, arguments, function (elem) {
				if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
					var target = manipulationTarget(this, elem);
					target.appendChild(elem);
				}
			});
		},

		prepend: function prepend() {
			return domManip(this, arguments, function (elem) {
				if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
					var target = manipulationTarget(this, elem);
					target.insertBefore(elem, target.firstChild);
				}
			});
		},

		before: function before() {
			return domManip(this, arguments, function (elem) {
				if (this.parentNode) {
					this.parentNode.insertBefore(elem, this);
				}
			});
		},

		after: function after() {
			return domManip(this, arguments, function (elem) {
				if (this.parentNode) {
					this.parentNode.insertBefore(elem, this.nextSibling);
				}
			});
		},

		empty: function empty() {
			var elem,
			    i = 0;

			for (; (elem = this[i]) != null; i++) {
				if (elem.nodeType === 1) {

					// Prevent memory leaks
					jQuery.cleanData(getAll(elem, false));

					// Remove any remaining nodes
					elem.textContent = "";
				}
			}

			return this;
		},

		clone: function clone(dataAndEvents, deepDataAndEvents) {
			dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
			deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

			return this.map(function () {
				return jQuery.clone(this, dataAndEvents, deepDataAndEvents);
			});
		},

		html: function html(value) {
			return access(this, function (value) {
				var elem = this[0] || {},
				    i = 0,
				    l = this.length;

				if (value === undefined && elem.nodeType === 1) {
					return elem.innerHTML;
				}

				// See if we can take a shortcut and just use innerHTML
				if (typeof value === "string" && !rnoInnerhtml.test(value) && !wrapMap[(rtagName.exec(value) || ["", ""])[1].toLowerCase()]) {

					value = jQuery.htmlPrefilter(value);

					try {
						for (; i < l; i++) {
							elem = this[i] || {};

							// Remove element nodes and prevent memory leaks
							if (elem.nodeType === 1) {
								jQuery.cleanData(getAll(elem, false));
								elem.innerHTML = value;
							}
						}

						elem = 0;

						// If using innerHTML throws an exception, use the fallback method
					} catch (e) {}
				}

				if (elem) {
					this.empty().append(value);
				}
			}, null, value, arguments.length);
		},

		replaceWith: function replaceWith() {
			var ignored = [];

			// Make the changes, replacing each non-ignored context element with the new content
			return domManip(this, arguments, function (elem) {
				var parent = this.parentNode;

				if (jQuery.inArray(this, ignored) < 0) {
					jQuery.cleanData(getAll(this));
					if (parent) {
						parent.replaceChild(elem, this);
					}
				}

				// Force callback invocation
			}, ignored);
		}
	});

	jQuery.each({
		appendTo: "append",
		prependTo: "prepend",
		insertBefore: "before",
		insertAfter: "after",
		replaceAll: "replaceWith"
	}, function (name, original) {
		jQuery.fn[name] = function (selector) {
			var elems,
			    ret = [],
			    insert = jQuery(selector),
			    last = insert.length - 1,
			    i = 0;

			for (; i <= last; i++) {
				elems = i === last ? this : this.clone(true);
				jQuery(insert[i])[original](elems);

				// Support: Android <=4.0 only, PhantomJS 1 only
				// .get() because push.apply(_, arraylike) throws on ancient WebKit
				push.apply(ret, elems.get());
			}

			return this.pushStack(ret);
		};
	});
	var rnumnonpx = new RegExp("^(" + pnum + ")(?!px)[a-z%]+$", "i");

	var getStyles = function getStyles(elem) {

		// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
		// IE throws on elements created in popups
		// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
		var view = elem.ownerDocument.defaultView;

		if (!view || !view.opener) {
			view = window;
		}

		return view.getComputedStyle(elem);
	};

	var rboxStyle = new RegExp(cssExpand.join("|"), "i");

	(function () {

		// Executing both pixelPosition & boxSizingReliable tests require only one layout
		// so they're executed at the same time to save the second computation.
		function computeStyleTests() {

			// This is a singleton, we need to execute it only once
			if (!div) {
				return;
			}

			container.style.cssText = "position:absolute;left:-11111px;width:60px;" + "margin-top:1px;padding:0;border:0";
			div.style.cssText = "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + "margin:auto;border:1px;padding:1px;" + "width:60%;top:1%";
			documentElement.appendChild(container).appendChild(div);

			var divStyle = window.getComputedStyle(div);
			pixelPositionVal = divStyle.top !== "1%";

			// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
			reliableMarginLeftVal = roundPixelMeasures(divStyle.marginLeft) === 12;

			// Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3
			// Some styles come back with percentage values, even though they shouldn't
			div.style.right = "60%";
			pixelBoxStylesVal = roundPixelMeasures(divStyle.right) === 36;

			// Support: IE 9 - 11 only
			// Detect misreporting of content dimensions for box-sizing:border-box elements
			boxSizingReliableVal = roundPixelMeasures(divStyle.width) === 36;

			// Support: IE 9 only
			// Detect overflow:scroll screwiness (gh-3699)
			div.style.position = "absolute";
			scrollboxSizeVal = div.offsetWidth === 36 || "absolute";

			documentElement.removeChild(container);

			// Nullify the div so it wouldn't be stored in the memory and
			// it will also be a sign that checks already performed
			div = null;
		}

		function roundPixelMeasures(measure) {
			return Math.round(parseFloat(measure));
		}

		var pixelPositionVal,
		    boxSizingReliableVal,
		    scrollboxSizeVal,
		    pixelBoxStylesVal,
		    reliableMarginLeftVal,
		    container = document.createElement("div"),
		    div = document.createElement("div");

		// Finish early in limited (non-browser) environments
		if (!div.style) {
			return;
		}

		// Support: IE <=9 - 11 only
		// Style of cloned element affects source element cloned (#8908)
		div.style.backgroundClip = "content-box";
		div.cloneNode(true).style.backgroundClip = "";
		support.clearCloneStyle = div.style.backgroundClip === "content-box";

		jQuery.extend(support, {
			boxSizingReliable: function boxSizingReliable() {
				computeStyleTests();
				return boxSizingReliableVal;
			},
			pixelBoxStyles: function pixelBoxStyles() {
				computeStyleTests();
				return pixelBoxStylesVal;
			},
			pixelPosition: function pixelPosition() {
				computeStyleTests();
				return pixelPositionVal;
			},
			reliableMarginLeft: function reliableMarginLeft() {
				computeStyleTests();
				return reliableMarginLeftVal;
			},
			scrollboxSize: function scrollboxSize() {
				computeStyleTests();
				return scrollboxSizeVal;
			}
		});
	})();

	function curCSS(elem, name, computed) {
		var width,
		    minWidth,
		    maxWidth,
		    ret,


		// Support: Firefox 51+
		// Retrieving style before computed somehow
		// fixes an issue with getting wrong values
		// on detached elements
		style = elem.style;

		computed = computed || getStyles(elem);

		// getPropertyValue is needed for:
		//   .css('filter') (IE 9 only, #12537)
		//   .css('--customProperty) (#3144)
		if (computed) {
			ret = computed.getPropertyValue(name) || computed[name];

			if (ret === "" && !jQuery.contains(elem.ownerDocument, elem)) {
				ret = jQuery.style(elem, name);
			}

			// A tribute to the "awesome hack by Dean Edwards"
			// Android Browser returns percentage for some values,
			// but width seems to be reliably pixels.
			// This is against the CSSOM draft spec:
			// https://drafts.csswg.org/cssom/#resolved-values
			if (!support.pixelBoxStyles() && rnumnonpx.test(ret) && rboxStyle.test(name)) {

				// Remember the original values
				width = style.width;
				minWidth = style.minWidth;
				maxWidth = style.maxWidth;

				// Put in the new values to get a computed value out
				style.minWidth = style.maxWidth = style.width = ret;
				ret = computed.width;

				// Revert the changed values
				style.width = width;
				style.minWidth = minWidth;
				style.maxWidth = maxWidth;
			}
		}

		return ret !== undefined ?

		// Support: IE <=9 - 11 only
		// IE returns zIndex value as an integer.
		ret + "" : ret;
	}

	function addGetHookIf(conditionFn, hookFn) {

		// Define the hook, we'll check on the first run if it's really needed.
		return {
			get: function get() {
				if (conditionFn()) {

					// Hook not needed (or it's not possible to use it due
					// to missing dependency), remove it.
					delete this.get;
					return;
				}

				// Hook needed; redefine it so that the support test is not executed again.
				return (this.get = hookFn).apply(this, arguments);
			}
		};
	}

	var

	// Swappable if display is none or starts with table
	// except "table", "table-cell", or "table-caption"
	// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
	    rcustomProp = /^--/,
	    cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	    cssNormalTransform = {
		letterSpacing: "0",
		fontWeight: "400"
	},
	    cssPrefixes = ["Webkit", "Moz", "ms"],
	    emptyStyle = document.createElement("div").style;

	// Return a css property mapped to a potentially vendor prefixed property
	function vendorPropName(name) {

		// Shortcut for names that are not vendor prefixed
		if (name in emptyStyle) {
			return name;
		}

		// Check for vendor prefixed names
		var capName = name[0].toUpperCase() + name.slice(1),
		    i = cssPrefixes.length;

		while (i--) {
			name = cssPrefixes[i] + capName;
			if (name in emptyStyle) {
				return name;
			}
		}
	}

	// Return a property mapped along what jQuery.cssProps suggests or to
	// a vendor prefixed property.
	function finalPropName(name) {
		var ret = jQuery.cssProps[name];
		if (!ret) {
			ret = jQuery.cssProps[name] = vendorPropName(name) || name;
		}
		return ret;
	}

	function setPositiveNumber(elem, value, subtract) {

		// Any relative (+/-) values have already been
		// normalized at this point
		var matches = rcssNum.exec(value);
		return matches ?

		// Guard against undefined "subtract", e.g., when used as in cssHooks
		Math.max(0, matches[2] - (subtract || 0)) + (matches[3] || "px") : value;
	}

	function boxModelAdjustment(elem, dimension, box, isBorderBox, styles, computedVal) {
		var i = dimension === "width" ? 1 : 0,
		    extra = 0,
		    delta = 0;

		// Adjustment may not be necessary
		if (box === (isBorderBox ? "border" : "content")) {
			return 0;
		}

		for (; i < 4; i += 2) {

			// Both box models exclude margin
			if (box === "margin") {
				delta += jQuery.css(elem, box + cssExpand[i], true, styles);
			}

			// If we get here with a content-box, we're seeking "padding" or "border" or "margin"
			if (!isBorderBox) {

				// Add padding
				delta += jQuery.css(elem, "padding" + cssExpand[i], true, styles);

				// For "border" or "margin", add border
				if (box !== "padding") {
					delta += jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);

					// But still keep track of it otherwise
				} else {
					extra += jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);
				}

				// If we get here with a border-box (content + padding + border), we're seeking "content" or
				// "padding" or "margin"
			} else {

				// For "content", subtract padding
				if (box === "content") {
					delta -= jQuery.css(elem, "padding" + cssExpand[i], true, styles);
				}

				// For "content" or "padding", subtract border
				if (box !== "margin") {
					delta -= jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);
				}
			}
		}

		// Account for positive content-box scroll gutter when requested by providing computedVal
		if (!isBorderBox && computedVal >= 0) {

			// offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
			// Assuming integer scroll gutter, subtract the rest and round down
			delta += Math.max(0, Math.ceil(elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)] - computedVal - delta - extra - 0.5));
		}

		return delta;
	}

	function getWidthOrHeight(elem, dimension, extra) {

		// Start with computed style
		var styles = getStyles(elem),
		    val = curCSS(elem, dimension, styles),
		    isBorderBox = jQuery.css(elem, "boxSizing", false, styles) === "border-box",
		    valueIsBorderBox = isBorderBox;

		// Support: Firefox <=54
		// Return a confounding non-pixel value or feign ignorance, as appropriate.
		if (rnumnonpx.test(val)) {
			if (!extra) {
				return val;
			}
			val = "auto";
		}

		// Check for style in case a browser which returns unreliable values
		// for getComputedStyle silently falls back to the reliable elem.style
		valueIsBorderBox = valueIsBorderBox && (support.boxSizingReliable() || val === elem.style[dimension]);

		// Fall back to offsetWidth/offsetHeight when value is "auto"
		// This happens for inline elements with no explicit setting (gh-3571)
		// Support: Android <=4.1 - 4.3 only
		// Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
		if (val === "auto" || !parseFloat(val) && jQuery.css(elem, "display", false, styles) === "inline") {

			val = elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)];

			// offsetWidth/offsetHeight provide border-box values
			valueIsBorderBox = true;
		}

		// Normalize "" and auto
		val = parseFloat(val) || 0;

		// Adjust for the element's box model
		return val + boxModelAdjustment(elem, dimension, extra || (isBorderBox ? "border" : "content"), valueIsBorderBox, styles,

		// Provide the current computed size to request scroll gutter calculation (gh-3589)
		val) + "px";
	}

	jQuery.extend({

		// Add in style property hooks for overriding the default
		// behavior of getting and setting a style property
		cssHooks: {
			opacity: {
				get: function get(elem, computed) {
					if (computed) {

						// We should always get a number back from opacity
						var ret = curCSS(elem, "opacity");
						return ret === "" ? "1" : ret;
					}
				}
			}
		},

		// Don't automatically add "px" to these possibly-unitless properties
		cssNumber: {
			"animationIterationCount": true,
			"columnCount": true,
			"fillOpacity": true,
			"flexGrow": true,
			"flexShrink": true,
			"fontWeight": true,
			"lineHeight": true,
			"opacity": true,
			"order": true,
			"orphans": true,
			"widows": true,
			"zIndex": true,
			"zoom": true
		},

		// Add in properties whose names you wish to fix before
		// setting or getting the value
		cssProps: {},

		// Get and set the style property on a DOM Node
		style: function style(elem, name, value, extra) {

			// Don't set styles on text and comment nodes
			if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) {
				return;
			}

			// Make sure that we're working with the right name
			var ret,
			    type,
			    hooks,
			    origName = camelCase(name),
			    isCustomProp = rcustomProp.test(name),
			    style = elem.style;

			// Make sure that we're working with the right name. We don't
			// want to query the value if it is a CSS custom property
			// since they are user-defined.
			if (!isCustomProp) {
				name = finalPropName(origName);
			}

			// Gets hook for the prefixed version, then unprefixed version
			hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName];

			// Check if we're setting a value
			if (value !== undefined) {
				type = typeof value === "undefined" ? "undefined" : _typeof(value);

				// Convert "+=" or "-=" to relative numbers (#7345)
				if (type === "string" && (ret = rcssNum.exec(value)) && ret[1]) {
					value = adjustCSS(elem, name, ret);

					// Fixes bug #9237
					type = "number";
				}

				// Make sure that null and NaN values aren't set (#7116)
				if (value == null || value !== value) {
					return;
				}

				// If a number was passed in, add the unit (except for certain CSS properties)
				if (type === "number") {
					value += ret && ret[3] || (jQuery.cssNumber[origName] ? "" : "px");
				}

				// background-* props affect original clone's values
				if (!support.clearCloneStyle && value === "" && name.indexOf("background") === 0) {
					style[name] = "inherit";
				}

				// If a hook was provided, use that value, otherwise just set the specified value
				if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== undefined) {

					if (isCustomProp) {
						style.setProperty(name, value);
					} else {
						style[name] = value;
					}
				}
			} else {

				// If a hook was provided get the non-computed value from there
				if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) {

					return ret;
				}

				// Otherwise just get the value from the style object
				return style[name];
			}
		},

		css: function css(elem, name, extra, styles) {
			var val,
			    num,
			    hooks,
			    origName = camelCase(name),
			    isCustomProp = rcustomProp.test(name);

			// Make sure that we're working with the right name. We don't
			// want to modify the value if it is a CSS custom property
			// since they are user-defined.
			if (!isCustomProp) {
				name = finalPropName(origName);
			}

			// Try prefixed name followed by the unprefixed name
			hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName];

			// If a hook was provided get the computed value from there
			if (hooks && "get" in hooks) {
				val = hooks.get(elem, true, extra);
			}

			// Otherwise, if a way to get the computed value exists, use that
			if (val === undefined) {
				val = curCSS(elem, name, styles);
			}

			// Convert "normal" to computed value
			if (val === "normal" && name in cssNormalTransform) {
				val = cssNormalTransform[name];
			}

			// Make numeric if forced or a qualifier was provided and val looks numeric
			if (extra === "" || extra) {
				num = parseFloat(val);
				return extra === true || isFinite(num) ? num || 0 : val;
			}

			return val;
		}
	});

	jQuery.each(["height", "width"], function (i, dimension) {
		jQuery.cssHooks[dimension] = {
			get: function get(elem, computed, extra) {
				if (computed) {

					// Certain elements can have dimension info if we invisibly show them
					// but it must have a current display style that would benefit
					return rdisplayswap.test(jQuery.css(elem, "display")) && (

					// Support: Safari 8+
					// Table columns in Safari have non-zero offsetWidth & zero
					// getBoundingClientRect().width unless display is changed.
					// Support: IE <=11 only
					// Running getBoundingClientRect on a disconnected node
					// in IE throws an error.
					!elem.getClientRects().length || !elem.getBoundingClientRect().width) ? swap(elem, cssShow, function () {
						return getWidthOrHeight(elem, dimension, extra);
					}) : getWidthOrHeight(elem, dimension, extra);
				}
			},

			set: function set(elem, value, extra) {
				var matches,
				    styles = getStyles(elem),
				    isBorderBox = jQuery.css(elem, "boxSizing", false, styles) === "border-box",
				    subtract = extra && boxModelAdjustment(elem, dimension, extra, isBorderBox, styles);

				// Account for unreliable border-box dimensions by comparing offset* to computed and
				// faking a content-box to get border and padding (gh-3699)
				if (isBorderBox && support.scrollboxSize() === styles.position) {
					subtract -= Math.ceil(elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)] - parseFloat(styles[dimension]) - boxModelAdjustment(elem, dimension, "border", false, styles) - 0.5);
				}

				// Convert to pixels if value adjustment is needed
				if (subtract && (matches = rcssNum.exec(value)) && (matches[3] || "px") !== "px") {

					elem.style[dimension] = value;
					value = jQuery.css(elem, dimension);
				}

				return setPositiveNumber(elem, value, subtract);
			}
		};
	});

	jQuery.cssHooks.marginLeft = addGetHookIf(support.reliableMarginLeft, function (elem, computed) {
		if (computed) {
			return (parseFloat(curCSS(elem, "marginLeft")) || elem.getBoundingClientRect().left - swap(elem, { marginLeft: 0 }, function () {
				return elem.getBoundingClientRect().left;
			})) + "px";
		}
	});

	// These hooks are used by animate to expand properties
	jQuery.each({
		margin: "",
		padding: "",
		border: "Width"
	}, function (prefix, suffix) {
		jQuery.cssHooks[prefix + suffix] = {
			expand: function expand(value) {
				var i = 0,
				    expanded = {},


				// Assumes a single number if not a string
				parts = typeof value === "string" ? value.split(" ") : [value];

				for (; i < 4; i++) {
					expanded[prefix + cssExpand[i] + suffix] = parts[i] || parts[i - 2] || parts[0];
				}

				return expanded;
			}
		};

		if (prefix !== "margin") {
			jQuery.cssHooks[prefix + suffix].set = setPositiveNumber;
		}
	});

	jQuery.fn.extend({
		css: function css(name, value) {
			return access(this, function (elem, name, value) {
				var styles,
				    len,
				    map = {},
				    i = 0;

				if (Array.isArray(name)) {
					styles = getStyles(elem);
					len = name.length;

					for (; i < len; i++) {
						map[name[i]] = jQuery.css(elem, name[i], false, styles);
					}

					return map;
				}

				return value !== undefined ? jQuery.style(elem, name, value) : jQuery.css(elem, name);
			}, name, value, arguments.length > 1);
		}
	});

	function Tween(elem, options, prop, end, easing) {
		return new Tween.prototype.init(elem, options, prop, end, easing);
	}
	jQuery.Tween = Tween;

	Tween.prototype = {
		constructor: Tween,
		init: function init(elem, options, prop, end, easing, unit) {
			this.elem = elem;
			this.prop = prop;
			this.easing = easing || jQuery.easing._default;
			this.options = options;
			this.start = this.now = this.cur();
			this.end = end;
			this.unit = unit || (jQuery.cssNumber[prop] ? "" : "px");
		},
		cur: function cur() {
			var hooks = Tween.propHooks[this.prop];

			return hooks && hooks.get ? hooks.get(this) : Tween.propHooks._default.get(this);
		},
		run: function run(percent) {
			var eased,
			    hooks = Tween.propHooks[this.prop];

			if (this.options.duration) {
				this.pos = eased = jQuery.easing[this.easing](percent, this.options.duration * percent, 0, 1, this.options.duration);
			} else {
				this.pos = eased = percent;
			}
			this.now = (this.end - this.start) * eased + this.start;

			if (this.options.step) {
				this.options.step.call(this.elem, this.now, this);
			}

			if (hooks && hooks.set) {
				hooks.set(this);
			} else {
				Tween.propHooks._default.set(this);
			}
			return this;
		}
	};

	Tween.prototype.init.prototype = Tween.prototype;

	Tween.propHooks = {
		_default: {
			get: function get(tween) {
				var result;

				// Use a property on the element directly when it is not a DOM element,
				// or when there is no matching style property that exists.
				if (tween.elem.nodeType !== 1 || tween.elem[tween.prop] != null && tween.elem.style[tween.prop] == null) {
					return tween.elem[tween.prop];
				}

				// Passing an empty string as a 3rd parameter to .css will automatically
				// attempt a parseFloat and fallback to a string if the parse fails.
				// Simple values such as "10px" are parsed to Float;
				// complex values such as "rotate(1rad)" are returned as-is.
				result = jQuery.css(tween.elem, tween.prop, "");

				// Empty strings, null, undefined and "auto" are converted to 0.
				return !result || result === "auto" ? 0 : result;
			},
			set: function set(tween) {

				// Use step hook for back compat.
				// Use cssHook if its there.
				// Use .style if available and use plain properties where available.
				if (jQuery.fx.step[tween.prop]) {
					jQuery.fx.step[tween.prop](tween);
				} else if (tween.elem.nodeType === 1 && (tween.elem.style[jQuery.cssProps[tween.prop]] != null || jQuery.cssHooks[tween.prop])) {
					jQuery.style(tween.elem, tween.prop, tween.now + tween.unit);
				} else {
					tween.elem[tween.prop] = tween.now;
				}
			}
		}
	};

	// Support: IE <=9 only
	// Panic based approach to setting things on disconnected nodes
	Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
		set: function set(tween) {
			if (tween.elem.nodeType && tween.elem.parentNode) {
				tween.elem[tween.prop] = tween.now;
			}
		}
	};

	jQuery.easing = {
		linear: function linear(p) {
			return p;
		},
		swing: function swing(p) {
			return 0.5 - Math.cos(p * Math.PI) / 2;
		},
		_default: "swing"
	};

	jQuery.fx = Tween.prototype.init;

	// Back compat <1.8 extension point
	jQuery.fx.step = {};

	var fxNow,
	    inProgress,
	    rfxtypes = /^(?:toggle|show|hide)$/,
	    rrun = /queueHooks$/;

	function schedule() {
		if (inProgress) {
			if (document.hidden === false && window.requestAnimationFrame) {
				window.requestAnimationFrame(schedule);
			} else {
				window.setTimeout(schedule, jQuery.fx.interval);
			}

			jQuery.fx.tick();
		}
	}

	// Animations created synchronously will run synchronously
	function createFxNow() {
		window.setTimeout(function () {
			fxNow = undefined;
		});
		return fxNow = Date.now();
	}

	// Generate parameters to create a standard animation
	function genFx(type, includeWidth) {
		var which,
		    i = 0,
		    attrs = { height: type };

		// If we include width, step value is 1 to do all cssExpand values,
		// otherwise step value is 2 to skip over Left and Right
		includeWidth = includeWidth ? 1 : 0;
		for (; i < 4; i += 2 - includeWidth) {
			which = cssExpand[i];
			attrs["margin" + which] = attrs["padding" + which] = type;
		}

		if (includeWidth) {
			attrs.opacity = attrs.width = type;
		}

		return attrs;
	}

	function createTween(value, prop, animation) {
		var tween,
		    collection = (Animation.tweeners[prop] || []).concat(Animation.tweeners["*"]),
		    index = 0,
		    length = collection.length;
		for (; index < length; index++) {
			if (tween = collection[index].call(animation, prop, value)) {

				// We're done with this property
				return tween;
			}
		}
	}

	function defaultPrefilter(elem, props, opts) {
		var prop,
		    value,
		    toggle,
		    hooks,
		    oldfire,
		    propTween,
		    restoreDisplay,
		    display,
		    isBox = "width" in props || "height" in props,
		    anim = this,
		    orig = {},
		    style = elem.style,
		    hidden = elem.nodeType && isHiddenWithinTree(elem),
		    dataShow = dataPriv.get(elem, "fxshow");

		// Queue-skipping animations hijack the fx hooks
		if (!opts.queue) {
			hooks = jQuery._queueHooks(elem, "fx");
			if (hooks.unqueued == null) {
				hooks.unqueued = 0;
				oldfire = hooks.empty.fire;
				hooks.empty.fire = function () {
					if (!hooks.unqueued) {
						oldfire();
					}
				};
			}
			hooks.unqueued++;

			anim.always(function () {

				// Ensure the complete handler is called before this completes
				anim.always(function () {
					hooks.unqueued--;
					if (!jQuery.queue(elem, "fx").length) {
						hooks.empty.fire();
					}
				});
			});
		}

		// Detect show/hide animations
		for (prop in props) {
			value = props[prop];
			if (rfxtypes.test(value)) {
				delete props[prop];
				toggle = toggle || value === "toggle";
				if (value === (hidden ? "hide" : "show")) {

					// Pretend to be hidden if this is a "show" and
					// there is still data from a stopped show/hide
					if (value === "show" && dataShow && dataShow[prop] !== undefined) {
						hidden = true;

						// Ignore all other no-op show/hide data
					} else {
						continue;
					}
				}
				orig[prop] = dataShow && dataShow[prop] || jQuery.style(elem, prop);
			}
		}

		// Bail out if this is a no-op like .hide().hide()
		propTween = !jQuery.isEmptyObject(props);
		if (!propTween && jQuery.isEmptyObject(orig)) {
			return;
		}

		// Restrict "overflow" and "display" styles during box animations
		if (isBox && elem.nodeType === 1) {

			// Support: IE <=9 - 11, Edge 12 - 15
			// Record all 3 overflow attributes because IE does not infer the shorthand
			// from identically-valued overflowX and overflowY and Edge just mirrors
			// the overflowX value there.
			opts.overflow = [style.overflow, style.overflowX, style.overflowY];

			// Identify a display type, preferring old show/hide data over the CSS cascade
			restoreDisplay = dataShow && dataShow.display;
			if (restoreDisplay == null) {
				restoreDisplay = dataPriv.get(elem, "display");
			}
			display = jQuery.css(elem, "display");
			if (display === "none") {
				if (restoreDisplay) {
					display = restoreDisplay;
				} else {

					// Get nonempty value(s) by temporarily forcing visibility
					showHide([elem], true);
					restoreDisplay = elem.style.display || restoreDisplay;
					display = jQuery.css(elem, "display");
					showHide([elem]);
				}
			}

			// Animate inline elements as inline-block
			if (display === "inline" || display === "inline-block" && restoreDisplay != null) {
				if (jQuery.css(elem, "float") === "none") {

					// Restore the original display value at the end of pure show/hide animations
					if (!propTween) {
						anim.done(function () {
							style.display = restoreDisplay;
						});
						if (restoreDisplay == null) {
							display = style.display;
							restoreDisplay = display === "none" ? "" : display;
						}
					}
					style.display = "inline-block";
				}
			}
		}

		if (opts.overflow) {
			style.overflow = "hidden";
			anim.always(function () {
				style.overflow = opts.overflow[0];
				style.overflowX = opts.overflow[1];
				style.overflowY = opts.overflow[2];
			});
		}

		// Implement show/hide animations
		propTween = false;
		for (prop in orig) {

			// General show/hide setup for this element animation
			if (!propTween) {
				if (dataShow) {
					if ("hidden" in dataShow) {
						hidden = dataShow.hidden;
					}
				} else {
					dataShow = dataPriv.access(elem, "fxshow", { display: restoreDisplay });
				}

				// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
				if (toggle) {
					dataShow.hidden = !hidden;
				}

				// Show elements before animating them
				if (hidden) {
					showHide([elem], true);
				}

				/* eslint-disable no-loop-func */

				anim.done(function () {

					/* eslint-enable no-loop-func */

					// The final step of a "hide" animation is actually hiding the element
					if (!hidden) {
						showHide([elem]);
					}
					dataPriv.remove(elem, "fxshow");
					for (prop in orig) {
						jQuery.style(elem, prop, orig[prop]);
					}
				});
			}

			// Per-property setup
			propTween = createTween(hidden ? dataShow[prop] : 0, prop, anim);
			if (!(prop in dataShow)) {
				dataShow[prop] = propTween.start;
				if (hidden) {
					propTween.end = propTween.start;
					propTween.start = 0;
				}
			}
		}
	}

	function propFilter(props, specialEasing) {
		var index, name, easing, value, hooks;

		// camelCase, specialEasing and expand cssHook pass
		for (index in props) {
			name = camelCase(index);
			easing = specialEasing[name];
			value = props[index];
			if (Array.isArray(value)) {
				easing = value[1];
				value = props[index] = value[0];
			}

			if (index !== name) {
				props[name] = value;
				delete props[index];
			}

			hooks = jQuery.cssHooks[name];
			if (hooks && "expand" in hooks) {
				value = hooks.expand(value);
				delete props[name];

				// Not quite $.extend, this won't overwrite existing keys.
				// Reusing 'index' because we have the correct "name"
				for (index in value) {
					if (!(index in props)) {
						props[index] = value[index];
						specialEasing[index] = easing;
					}
				}
			} else {
				specialEasing[name] = easing;
			}
		}
	}

	function Animation(elem, properties, options) {
		var result,
		    stopped,
		    index = 0,
		    length = Animation.prefilters.length,
		    deferred = jQuery.Deferred().always(function () {

			// Don't match elem in the :animated selector
			delete tick.elem;
		}),
		    tick = function tick() {
			if (stopped) {
				return false;
			}
			var currentTime = fxNow || createFxNow(),
			    remaining = Math.max(0, animation.startTime + animation.duration - currentTime),


			// Support: Android 2.3 only
			// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
			temp = remaining / animation.duration || 0,
			    percent = 1 - temp,
			    index = 0,
			    length = animation.tweens.length;

			for (; index < length; index++) {
				animation.tweens[index].run(percent);
			}

			deferred.notifyWith(elem, [animation, percent, remaining]);

			// If there's more to do, yield
			if (percent < 1 && length) {
				return remaining;
			}

			// If this was an empty animation, synthesize a final progress notification
			if (!length) {
				deferred.notifyWith(elem, [animation, 1, 0]);
			}

			// Resolve the animation and report its conclusion
			deferred.resolveWith(elem, [animation]);
			return false;
		},
		    animation = deferred.promise({
			elem: elem,
			props: jQuery.extend({}, properties),
			opts: jQuery.extend(true, {
				specialEasing: {},
				easing: jQuery.easing._default
			}, options),
			originalProperties: properties,
			originalOptions: options,
			startTime: fxNow || createFxNow(),
			duration: options.duration,
			tweens: [],
			createTween: function createTween(prop, end) {
				var tween = jQuery.Tween(elem, animation.opts, prop, end, animation.opts.specialEasing[prop] || animation.opts.easing);
				animation.tweens.push(tween);
				return tween;
			},
			stop: function stop(gotoEnd) {
				var index = 0,


				// If we are going to the end, we want to run all the tweens
				// otherwise we skip this part
				length = gotoEnd ? animation.tweens.length : 0;
				if (stopped) {
					return this;
				}
				stopped = true;
				for (; index < length; index++) {
					animation.tweens[index].run(1);
				}

				// Resolve when we played the last frame; otherwise, reject
				if (gotoEnd) {
					deferred.notifyWith(elem, [animation, 1, 0]);
					deferred.resolveWith(elem, [animation, gotoEnd]);
				} else {
					deferred.rejectWith(elem, [animation, gotoEnd]);
				}
				return this;
			}
		}),
		    props = animation.props;

		propFilter(props, animation.opts.specialEasing);

		for (; index < length; index++) {
			result = Animation.prefilters[index].call(animation, elem, props, animation.opts);
			if (result) {
				if (isFunction(result.stop)) {
					jQuery._queueHooks(animation.elem, animation.opts.queue).stop = result.stop.bind(result);
				}
				return result;
			}
		}

		jQuery.map(props, createTween, animation);

		if (isFunction(animation.opts.start)) {
			animation.opts.start.call(elem, animation);
		}

		// Attach callbacks from options
		animation.progress(animation.opts.progress).done(animation.opts.done, animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always);

		jQuery.fx.timer(jQuery.extend(tick, {
			elem: elem,
			anim: animation,
			queue: animation.opts.queue
		}));

		return animation;
	}

	jQuery.Animation = jQuery.extend(Animation, {

		tweeners: {
			"*": [function (prop, value) {
				var tween = this.createTween(prop, value);
				adjustCSS(tween.elem, prop, rcssNum.exec(value), tween);
				return tween;
			}]
		},

		tweener: function tweener(props, callback) {
			if (isFunction(props)) {
				callback = props;
				props = ["*"];
			} else {
				props = props.match(rnothtmlwhite);
			}

			var prop,
			    index = 0,
			    length = props.length;

			for (; index < length; index++) {
				prop = props[index];
				Animation.tweeners[prop] = Animation.tweeners[prop] || [];
				Animation.tweeners[prop].unshift(callback);
			}
		},

		prefilters: [defaultPrefilter],

		prefilter: function prefilter(callback, prepend) {
			if (prepend) {
				Animation.prefilters.unshift(callback);
			} else {
				Animation.prefilters.push(callback);
			}
		}
	});

	jQuery.speed = function (speed, easing, fn) {
		var opt = speed && (typeof speed === "undefined" ? "undefined" : _typeof(speed)) === "object" ? jQuery.extend({}, speed) : {
			complete: fn || !fn && easing || isFunction(speed) && speed,
			duration: speed,
			easing: fn && easing || easing && !isFunction(easing) && easing
		};

		// Go to the end state if fx are off
		if (jQuery.fx.off) {
			opt.duration = 0;
		} else {
			if (typeof opt.duration !== "number") {
				if (opt.duration in jQuery.fx.speeds) {
					opt.duration = jQuery.fx.speeds[opt.duration];
				} else {
					opt.duration = jQuery.fx.speeds._default;
				}
			}
		}

		// Normalize opt.queue - true/undefined/null -> "fx"
		if (opt.queue == null || opt.queue === true) {
			opt.queue = "fx";
		}

		// Queueing
		opt.old = opt.complete;

		opt.complete = function () {
			if (isFunction(opt.old)) {
				opt.old.call(this);
			}

			if (opt.queue) {
				jQuery.dequeue(this, opt.queue);
			}
		};

		return opt;
	};

	jQuery.fn.extend({
		fadeTo: function fadeTo(speed, to, easing, callback) {

			// Show any hidden elements after setting opacity to 0
			return this.filter(isHiddenWithinTree).css("opacity", 0).show()

			// Animate to the value specified
			.end().animate({ opacity: to }, speed, easing, callback);
		},
		animate: function animate(prop, speed, easing, callback) {
			var empty = jQuery.isEmptyObject(prop),
			    optall = jQuery.speed(speed, easing, callback),
			    doAnimation = function doAnimation() {

				// Operate on a copy of prop so per-property easing won't be lost
				var anim = Animation(this, jQuery.extend({}, prop), optall);

				// Empty animations, or finishing resolves immediately
				if (empty || dataPriv.get(this, "finish")) {
					anim.stop(true);
				}
			};
			doAnimation.finish = doAnimation;

			return empty || optall.queue === false ? this.each(doAnimation) : this.queue(optall.queue, doAnimation);
		},
		stop: function stop(type, clearQueue, gotoEnd) {
			var stopQueue = function stopQueue(hooks) {
				var stop = hooks.stop;
				delete hooks.stop;
				stop(gotoEnd);
			};

			if (typeof type !== "string") {
				gotoEnd = clearQueue;
				clearQueue = type;
				type = undefined;
			}
			if (clearQueue && type !== false) {
				this.queue(type || "fx", []);
			}

			return this.each(function () {
				var dequeue = true,
				    index = type != null && type + "queueHooks",
				    timers = jQuery.timers,
				    data = dataPriv.get(this);

				if (index) {
					if (data[index] && data[index].stop) {
						stopQueue(data[index]);
					}
				} else {
					for (index in data) {
						if (data[index] && data[index].stop && rrun.test(index)) {
							stopQueue(data[index]);
						}
					}
				}

				for (index = timers.length; index--;) {
					if (timers[index].elem === this && (type == null || timers[index].queue === type)) {

						timers[index].anim.stop(gotoEnd);
						dequeue = false;
						timers.splice(index, 1);
					}
				}

				// Start the next in the queue if the last step wasn't forced.
				// Timers currently will call their complete callbacks, which
				// will dequeue but only if they were gotoEnd.
				if (dequeue || !gotoEnd) {
					jQuery.dequeue(this, type);
				}
			});
		},
		finish: function finish(type) {
			if (type !== false) {
				type = type || "fx";
			}
			return this.each(function () {
				var index,
				    data = dataPriv.get(this),
				    queue = data[type + "queue"],
				    hooks = data[type + "queueHooks"],
				    timers = jQuery.timers,
				    length = queue ? queue.length : 0;

				// Enable finishing flag on private data
				data.finish = true;

				// Empty the queue first
				jQuery.queue(this, type, []);

				if (hooks && hooks.stop) {
					hooks.stop.call(this, true);
				}

				// Look for any active animations, and finish them
				for (index = timers.length; index--;) {
					if (timers[index].elem === this && timers[index].queue === type) {
						timers[index].anim.stop(true);
						timers.splice(index, 1);
					}
				}

				// Look for any animations in the old queue and finish them
				for (index = 0; index < length; index++) {
					if (queue[index] && queue[index].finish) {
						queue[index].finish.call(this);
					}
				}

				// Turn off finishing flag
				delete data.finish;
			});
		}
	});

	jQuery.each(["toggle", "show", "hide"], function (i, name) {
		var cssFn = jQuery.fn[name];
		jQuery.fn[name] = function (speed, easing, callback) {
			return speed == null || typeof speed === "boolean" ? cssFn.apply(this, arguments) : this.animate(genFx(name, true), speed, easing, callback);
		};
	});

	// Generate shortcuts for custom animations
	jQuery.each({
		slideDown: genFx("show"),
		slideUp: genFx("hide"),
		slideToggle: genFx("toggle"),
		fadeIn: { opacity: "show" },
		fadeOut: { opacity: "hide" },
		fadeToggle: { opacity: "toggle" }
	}, function (name, props) {
		jQuery.fn[name] = function (speed, easing, callback) {
			return this.animate(props, speed, easing, callback);
		};
	});

	jQuery.timers = [];
	jQuery.fx.tick = function () {
		var timer,
		    i = 0,
		    timers = jQuery.timers;

		fxNow = Date.now();

		for (; i < timers.length; i++) {
			timer = timers[i];

			// Run the timer and safely remove it when done (allowing for external removal)
			if (!timer() && timers[i] === timer) {
				timers.splice(i--, 1);
			}
		}

		if (!timers.length) {
			jQuery.fx.stop();
		}
		fxNow = undefined;
	};

	jQuery.fx.timer = function (timer) {
		jQuery.timers.push(timer);
		jQuery.fx.start();
	};

	jQuery.fx.interval = 13;
	jQuery.fx.start = function () {
		if (inProgress) {
			return;
		}

		inProgress = true;
		schedule();
	};

	jQuery.fx.stop = function () {
		inProgress = null;
	};

	jQuery.fx.speeds = {
		slow: 600,
		fast: 200,

		// Default speed
		_default: 400
	};

	// Based off of the plugin by Clint Helfers, with permission.
	// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
	jQuery.fn.delay = function (time, type) {
		time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
		type = type || "fx";

		return this.queue(type, function (next, hooks) {
			var timeout = window.setTimeout(next, time);
			hooks.stop = function () {
				window.clearTimeout(timeout);
			};
		});
	};

	(function () {
		var input = document.createElement("input"),
		    select = document.createElement("select"),
		    opt = select.appendChild(document.createElement("option"));

		input.type = "checkbox";

		// Support: Android <=4.3 only
		// Default value for a checkbox should be "on"
		support.checkOn = input.value !== "";

		// Support: IE <=11 only
		// Must access selectedIndex to make default options select
		support.optSelected = opt.selected;

		// Support: IE <=11 only
		// An input loses its value after becoming a radio
		input = document.createElement("input");
		input.value = "t";
		input.type = "radio";
		support.radioValue = input.value === "t";
	})();

	var boolHook,
	    attrHandle = jQuery.expr.attrHandle;

	jQuery.fn.extend({
		attr: function attr(name, value) {
			return access(this, jQuery.attr, name, value, arguments.length > 1);
		},

		removeAttr: function removeAttr(name) {
			return this.each(function () {
				jQuery.removeAttr(this, name);
			});
		}
	});

	jQuery.extend({
		attr: function attr(elem, name, value) {
			var ret,
			    hooks,
			    nType = elem.nodeType;

			// Don't get/set attributes on text, comment and attribute nodes
			if (nType === 3 || nType === 8 || nType === 2) {
				return;
			}

			// Fallback to prop when attributes are not supported
			if (typeof elem.getAttribute === "undefined") {
				return jQuery.prop(elem, name, value);
			}

			// Attribute hooks are determined by the lowercase version
			// Grab necessary hook if one is defined
			if (nType !== 1 || !jQuery.isXMLDoc(elem)) {
				hooks = jQuery.attrHooks[name.toLowerCase()] || (jQuery.expr.match.bool.test(name) ? boolHook : undefined);
			}

			if (value !== undefined) {
				if (value === null) {
					jQuery.removeAttr(elem, name);
					return;
				}

				if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
					return ret;
				}

				elem.setAttribute(name, value + "");
				return value;
			}

			if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
				return ret;
			}

			ret = jQuery.find.attr(elem, name);

			// Non-existent attributes return null, we normalize to undefined
			return ret == null ? undefined : ret;
		},

		attrHooks: {
			type: {
				set: function set(elem, value) {
					if (!support.radioValue && value === "radio" && nodeName(elem, "input")) {
						var val = elem.value;
						elem.setAttribute("type", value);
						if (val) {
							elem.value = val;
						}
						return value;
					}
				}
			}
		},

		removeAttr: function removeAttr(elem, value) {
			var name,
			    i = 0,


			// Attribute names can contain non-HTML whitespace characters
			// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
			attrNames = value && value.match(rnothtmlwhite);

			if (attrNames && elem.nodeType === 1) {
				while (name = attrNames[i++]) {
					elem.removeAttribute(name);
				}
			}
		}
	});

	// Hooks for boolean attributes
	boolHook = {
		set: function set(elem, value, name) {
			if (value === false) {

				// Remove boolean attributes when set to false
				jQuery.removeAttr(elem, name);
			} else {
				elem.setAttribute(name, name);
			}
			return name;
		}
	};

	jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g), function (i, name) {
		var getter = attrHandle[name] || jQuery.find.attr;

		attrHandle[name] = function (elem, name, isXML) {
			var ret,
			    handle,
			    lowercaseName = name.toLowerCase();

			if (!isXML) {

				// Avoid an infinite loop by temporarily removing this function from the getter
				handle = attrHandle[lowercaseName];
				attrHandle[lowercaseName] = ret;
				ret = getter(elem, name, isXML) != null ? lowercaseName : null;
				attrHandle[lowercaseName] = handle;
			}
			return ret;
		};
	});

	var rfocusable = /^(?:input|select|textarea|button)$/i,
	    rclickable = /^(?:a|area)$/i;

	jQuery.fn.extend({
		prop: function prop(name, value) {
			return access(this, jQuery.prop, name, value, arguments.length > 1);
		},

		removeProp: function removeProp(name) {
			return this.each(function () {
				delete this[jQuery.propFix[name] || name];
			});
		}
	});

	jQuery.extend({
		prop: function prop(elem, name, value) {
			var ret,
			    hooks,
			    nType = elem.nodeType;

			// Don't get/set properties on text, comment and attribute nodes
			if (nType === 3 || nType === 8 || nType === 2) {
				return;
			}

			if (nType !== 1 || !jQuery.isXMLDoc(elem)) {

				// Fix name and attach hooks
				name = jQuery.propFix[name] || name;
				hooks = jQuery.propHooks[name];
			}

			if (value !== undefined) {
				if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
					return ret;
				}

				return elem[name] = value;
			}

			if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
				return ret;
			}

			return elem[name];
		},

		propHooks: {
			tabIndex: {
				get: function get(elem) {

					// Support: IE <=9 - 11 only
					// elem.tabIndex doesn't always return the
					// correct value when it hasn't been explicitly set
					// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
					// Use proper attribute retrieval(#12072)
					var tabindex = jQuery.find.attr(elem, "tabindex");

					if (tabindex) {
						return parseInt(tabindex, 10);
					}

					if (rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href) {
						return 0;
					}

					return -1;
				}
			}
		},

		propFix: {
			"for": "htmlFor",
			"class": "className"
		}
	});

	// Support: IE <=11 only
	// Accessing the selectedIndex property
	// forces the browser to respect setting selected
	// on the option
	// The getter ensures a default option is selected
	// when in an optgroup
	// eslint rule "no-unused-expressions" is disabled for this code
	// since it considers such accessions noop
	if (!support.optSelected) {
		jQuery.propHooks.selected = {
			get: function get(elem) {

				/* eslint no-unused-expressions: "off" */

				var parent = elem.parentNode;
				if (parent && parent.parentNode) {
					parent.parentNode.selectedIndex;
				}
				return null;
			},
			set: function set(elem) {

				/* eslint no-unused-expressions: "off" */

				var parent = elem.parentNode;
				if (parent) {
					parent.selectedIndex;

					if (parent.parentNode) {
						parent.parentNode.selectedIndex;
					}
				}
			}
		};
	}

	jQuery.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function () {
		jQuery.propFix[this.toLowerCase()] = this;
	});

	// Strip and collapse whitespace according to HTML spec
	// https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
	function stripAndCollapse(value) {
		var tokens = value.match(rnothtmlwhite) || [];
		return tokens.join(" ");
	}

	function getClass(elem) {
		return elem.getAttribute && elem.getAttribute("class") || "";
	}

	function classesToArray(value) {
		if (Array.isArray(value)) {
			return value;
		}
		if (typeof value === "string") {
			return value.match(rnothtmlwhite) || [];
		}
		return [];
	}

	jQuery.fn.extend({
		addClass: function addClass(value) {
			var classes,
			    elem,
			    cur,
			    curValue,
			    clazz,
			    j,
			    finalValue,
			    i = 0;

			if (isFunction(value)) {
				return this.each(function (j) {
					jQuery(this).addClass(value.call(this, j, getClass(this)));
				});
			}

			classes = classesToArray(value);

			if (classes.length) {
				while (elem = this[i++]) {
					curValue = getClass(elem);
					cur = elem.nodeType === 1 && " " + stripAndCollapse(curValue) + " ";

					if (cur) {
						j = 0;
						while (clazz = classes[j++]) {
							if (cur.indexOf(" " + clazz + " ") < 0) {
								cur += clazz + " ";
							}
						}

						// Only assign if different to avoid unneeded rendering.
						finalValue = stripAndCollapse(cur);
						if (curValue !== finalValue) {
							elem.setAttribute("class", finalValue);
						}
					}
				}
			}

			return this;
		},

		removeClass: function removeClass(value) {
			var classes,
			    elem,
			    cur,
			    curValue,
			    clazz,
			    j,
			    finalValue,
			    i = 0;

			if (isFunction(value)) {
				return this.each(function (j) {
					jQuery(this).removeClass(value.call(this, j, getClass(this)));
				});
			}

			if (!arguments.length) {
				return this.attr("class", "");
			}

			classes = classesToArray(value);

			if (classes.length) {
				while (elem = this[i++]) {
					curValue = getClass(elem);

					// This expression is here for better compressibility (see addClass)
					cur = elem.nodeType === 1 && " " + stripAndCollapse(curValue) + " ";

					if (cur) {
						j = 0;
						while (clazz = classes[j++]) {

							// Remove *all* instances
							while (cur.indexOf(" " + clazz + " ") > -1) {
								cur = cur.replace(" " + clazz + " ", " ");
							}
						}

						// Only assign if different to avoid unneeded rendering.
						finalValue = stripAndCollapse(cur);
						if (curValue !== finalValue) {
							elem.setAttribute("class", finalValue);
						}
					}
				}
			}

			return this;
		},

		toggleClass: function toggleClass(value, stateVal) {
			var type = typeof value === "undefined" ? "undefined" : _typeof(value),
			    isValidValue = type === "string" || Array.isArray(value);

			if (typeof stateVal === "boolean" && isValidValue) {
				return stateVal ? this.addClass(value) : this.removeClass(value);
			}

			if (isFunction(value)) {
				return this.each(function (i) {
					jQuery(this).toggleClass(value.call(this, i, getClass(this), stateVal), stateVal);
				});
			}

			return this.each(function () {
				var className, i, self, classNames;

				if (isValidValue) {

					// Toggle individual class names
					i = 0;
					self = jQuery(this);
					classNames = classesToArray(value);

					while (className = classNames[i++]) {

						// Check each className given, space separated list
						if (self.hasClass(className)) {
							self.removeClass(className);
						} else {
							self.addClass(className);
						}
					}

					// Toggle whole class name
				} else if (value === undefined || type === "boolean") {
					className = getClass(this);
					if (className) {

						// Store className if set
						dataPriv.set(this, "__className__", className);
					}

					// If the element has a class name or if we're passed `false`,
					// then remove the whole classname (if there was one, the above saved it).
					// Otherwise bring back whatever was previously saved (if anything),
					// falling back to the empty string if nothing was stored.
					if (this.setAttribute) {
						this.setAttribute("class", className || value === false ? "" : dataPriv.get(this, "__className__") || "");
					}
				}
			});
		},

		hasClass: function hasClass(selector) {
			var className,
			    elem,
			    i = 0;

			className = " " + selector + " ";
			while (elem = this[i++]) {
				if (elem.nodeType === 1 && (" " + stripAndCollapse(getClass(elem)) + " ").indexOf(className) > -1) {
					return true;
				}
			}

			return false;
		}
	});

	var rreturn = /\r/g;

	jQuery.fn.extend({
		val: function val(value) {
			var hooks,
			    ret,
			    valueIsFunction,
			    elem = this[0];

			if (!arguments.length) {
				if (elem) {
					hooks = jQuery.valHooks[elem.type] || jQuery.valHooks[elem.nodeName.toLowerCase()];

					if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) {
						return ret;
					}

					ret = elem.value;

					// Handle most common string cases
					if (typeof ret === "string") {
						return ret.replace(rreturn, "");
					}

					// Handle cases where value is null/undef or number
					return ret == null ? "" : ret;
				}

				return;
			}

			valueIsFunction = isFunction(value);

			return this.each(function (i) {
				var val;

				if (this.nodeType !== 1) {
					return;
				}

				if (valueIsFunction) {
					val = value.call(this, i, jQuery(this).val());
				} else {
					val = value;
				}

				// Treat null/undefined as ""; convert numbers to string
				if (val == null) {
					val = "";
				} else if (typeof val === "number") {
					val += "";
				} else if (Array.isArray(val)) {
					val = jQuery.map(val, function (value) {
						return value == null ? "" : value + "";
					});
				}

				hooks = jQuery.valHooks[this.type] || jQuery.valHooks[this.nodeName.toLowerCase()];

				// If set returns undefined, fall back to normal setting
				if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) {
					this.value = val;
				}
			});
		}
	});

	jQuery.extend({
		valHooks: {
			option: {
				get: function get(elem) {

					var val = jQuery.find.attr(elem, "value");
					return val != null ? val :

					// Support: IE <=10 - 11 only
					// option.text throws exceptions (#14686, #14858)
					// Strip and collapse whitespace
					// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
					stripAndCollapse(jQuery.text(elem));
				}
			},
			select: {
				get: function get(elem) {
					var value,
					    option,
					    i,
					    options = elem.options,
					    index = elem.selectedIndex,
					    one = elem.type === "select-one",
					    values = one ? null : [],
					    max = one ? index + 1 : options.length;

					if (index < 0) {
						i = max;
					} else {
						i = one ? index : 0;
					}

					// Loop through all the selected options
					for (; i < max; i++) {
						option = options[i];

						// Support: IE <=9 only
						// IE8-9 doesn't update selected after form reset (#2551)
						if ((option.selected || i === index) &&

						// Don't return options that are disabled or in a disabled optgroup
						!option.disabled && (!option.parentNode.disabled || !nodeName(option.parentNode, "optgroup"))) {

							// Get the specific value for the option
							value = jQuery(option).val();

							// We don't need an array for one selects
							if (one) {
								return value;
							}

							// Multi-Selects return an array
							values.push(value);
						}
					}

					return values;
				},

				set: function set(elem, value) {
					var optionSet,
					    option,
					    options = elem.options,
					    values = jQuery.makeArray(value),
					    i = options.length;

					while (i--) {
						option = options[i];

						/* eslint-disable no-cond-assign */

						if (option.selected = jQuery.inArray(jQuery.valHooks.option.get(option), values) > -1) {
							optionSet = true;
						}

						/* eslint-enable no-cond-assign */
					}

					// Force browsers to behave consistently when non-matching value is set
					if (!optionSet) {
						elem.selectedIndex = -1;
					}
					return values;
				}
			}
		}
	});

	// Radios and checkboxes getter/setter
	jQuery.each(["radio", "checkbox"], function () {
		jQuery.valHooks[this] = {
			set: function set(elem, value) {
				if (Array.isArray(value)) {
					return elem.checked = jQuery.inArray(jQuery(elem).val(), value) > -1;
				}
			}
		};
		if (!support.checkOn) {
			jQuery.valHooks[this].get = function (elem) {
				return elem.getAttribute("value") === null ? "on" : elem.value;
			};
		}
	});

	// Return jQuery for attributes-only inclusion


	support.focusin = "onfocusin" in window;

	var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	    stopPropagationCallback = function stopPropagationCallback(e) {
		e.stopPropagation();
	};

	jQuery.extend(jQuery.event, {

		trigger: function trigger(event, data, elem, onlyHandlers) {

			var i,
			    cur,
			    tmp,
			    bubbleType,
			    ontype,
			    handle,
			    special,
			    lastElement,
			    eventPath = [elem || document],
			    type = hasOwn.call(event, "type") ? event.type : event,
			    namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];

			cur = lastElement = tmp = elem = elem || document;

			// Don't do events on text and comment nodes
			if (elem.nodeType === 3 || elem.nodeType === 8) {
				return;
			}

			// focus/blur morphs to focusin/out; ensure we're not firing them right now
			if (rfocusMorph.test(type + jQuery.event.triggered)) {
				return;
			}

			if (type.indexOf(".") > -1) {

				// Namespaced trigger; create a regexp to match event type in handle()
				namespaces = type.split(".");
				type = namespaces.shift();
				namespaces.sort();
			}
			ontype = type.indexOf(":") < 0 && "on" + type;

			// Caller can pass in a jQuery.Event object, Object, or just an event type string
			event = event[jQuery.expando] ? event : new jQuery.Event(type, (typeof event === "undefined" ? "undefined" : _typeof(event)) === "object" && event);

			// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
			event.isTrigger = onlyHandlers ? 2 : 3;
			event.namespace = namespaces.join(".");
			event.rnamespace = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;

			// Clean up the event in case it is being reused
			event.result = undefined;
			if (!event.target) {
				event.target = elem;
			}

			// Clone any incoming data and prepend the event, creating the handler arg list
			data = data == null ? [event] : jQuery.makeArray(data, [event]);

			// Allow special events to draw outside the lines
			special = jQuery.event.special[type] || {};
			if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) {
				return;
			}

			// Determine event propagation path in advance, per W3C events spec (#9951)
			// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
			if (!onlyHandlers && !special.noBubble && !isWindow(elem)) {

				bubbleType = special.delegateType || type;
				if (!rfocusMorph.test(bubbleType + type)) {
					cur = cur.parentNode;
				}
				for (; cur; cur = cur.parentNode) {
					eventPath.push(cur);
					tmp = cur;
				}

				// Only add window if we got to document (e.g., not plain obj or detached DOM)
				if (tmp === (elem.ownerDocument || document)) {
					eventPath.push(tmp.defaultView || tmp.parentWindow || window);
				}
			}

			// Fire handlers on the event path
			i = 0;
			while ((cur = eventPath[i++]) && !event.isPropagationStopped()) {
				lastElement = cur;
				event.type = i > 1 ? bubbleType : special.bindType || type;

				// jQuery handler
				handle = (dataPriv.get(cur, "events") || {})[event.type] && dataPriv.get(cur, "handle");
				if (handle) {
					handle.apply(cur, data);
				}

				// Native handler
				handle = ontype && cur[ontype];
				if (handle && handle.apply && acceptData(cur)) {
					event.result = handle.apply(cur, data);
					if (event.result === false) {
						event.preventDefault();
					}
				}
			}
			event.type = type;

			// If nobody prevented the default action, do it now
			if (!onlyHandlers && !event.isDefaultPrevented()) {

				if ((!special._default || special._default.apply(eventPath.pop(), data) === false) && acceptData(elem)) {

					// Call a native DOM method on the target with the same name as the event.
					// Don't do default actions on window, that's where global variables be (#6170)
					if (ontype && isFunction(elem[type]) && !isWindow(elem)) {

						// Don't re-trigger an onFOO event when we call its FOO() method
						tmp = elem[ontype];

						if (tmp) {
							elem[ontype] = null;
						}

						// Prevent re-triggering of the same event, since we already bubbled it above
						jQuery.event.triggered = type;

						if (event.isPropagationStopped()) {
							lastElement.addEventListener(type, stopPropagationCallback);
						}

						elem[type]();

						if (event.isPropagationStopped()) {
							lastElement.removeEventListener(type, stopPropagationCallback);
						}

						jQuery.event.triggered = undefined;

						if (tmp) {
							elem[ontype] = tmp;
						}
					}
				}
			}

			return event.result;
		},

		// Piggyback on a donor event to simulate a different one
		// Used only for `focus(in | out)` events
		simulate: function simulate(type, elem, event) {
			var e = jQuery.extend(new jQuery.Event(), event, {
				type: type,
				isSimulated: true
			});

			jQuery.event.trigger(e, null, elem);
		}

	});

	jQuery.fn.extend({

		trigger: function trigger(type, data) {
			return this.each(function () {
				jQuery.event.trigger(type, data, this);
			});
		},
		triggerHandler: function triggerHandler(type, data) {
			var elem = this[0];
			if (elem) {
				return jQuery.event.trigger(type, data, elem, true);
			}
		}
	});

	// Support: Firefox <=44
	// Firefox doesn't have focus(in | out) events
	// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
	//
	// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
	// focus(in | out) events fire after focus & blur events,
	// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
	// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
	if (!support.focusin) {
		jQuery.each({ focus: "focusin", blur: "focusout" }, function (orig, fix) {

			// Attach a single capturing handler on the document while someone wants focusin/focusout
			var handler = function handler(event) {
				jQuery.event.simulate(fix, event.target, jQuery.event.fix(event));
			};

			jQuery.event.special[fix] = {
				setup: function setup() {
					var doc = this.ownerDocument || this,
					    attaches = dataPriv.access(doc, fix);

					if (!attaches) {
						doc.addEventListener(orig, handler, true);
					}
					dataPriv.access(doc, fix, (attaches || 0) + 1);
				},
				teardown: function teardown() {
					var doc = this.ownerDocument || this,
					    attaches = dataPriv.access(doc, fix) - 1;

					if (!attaches) {
						doc.removeEventListener(orig, handler, true);
						dataPriv.remove(doc, fix);
					} else {
						dataPriv.access(doc, fix, attaches);
					}
				}
			};
		});
	}
	var location = window.location;

	var nonce = Date.now();

	var rquery = /\?/;

	// Cross-browser xml parsing
	jQuery.parseXML = function (data) {
		var xml;
		if (!data || typeof data !== "string") {
			return null;
		}

		// Support: IE 9 - 11 only
		// IE throws on parseFromString with invalid input.
		try {
			xml = new window.DOMParser().parseFromString(data, "text/xml");
		} catch (e) {
			xml = undefined;
		}

		if (!xml || xml.getElementsByTagName("parsererror").length) {
			jQuery.error("Invalid XML: " + data);
		}
		return xml;
	};

	var rbracket = /\[\]$/,
	    rCRLF = /\r?\n/g,
	    rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
	    rsubmittable = /^(?:input|select|textarea|keygen)/i;

	function buildParams(prefix, obj, traditional, add) {
		var name;

		if (Array.isArray(obj)) {

			// Serialize array item.
			jQuery.each(obj, function (i, v) {
				if (traditional || rbracket.test(prefix)) {

					// Treat each array item as a scalar.
					add(prefix, v);
				} else {

					// Item is non-scalar (array or object), encode its numeric index.
					buildParams(prefix + "[" + ((typeof v === "undefined" ? "undefined" : _typeof(v)) === "object" && v != null ? i : "") + "]", v, traditional, add);
				}
			});
		} else if (!traditional && toType(obj) === "object") {

			// Serialize object item.
			for (name in obj) {
				buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
			}
		} else {

			// Serialize scalar item.
			add(prefix, obj);
		}
	}

	// Serialize an array of form elements or a set of
	// key/values into a query string
	jQuery.param = function (a, traditional) {
		var prefix,
		    s = [],
		    add = function add(key, valueOrFunction) {

			// If value is a function, invoke it and use its return value
			var value = isFunction(valueOrFunction) ? valueOrFunction() : valueOrFunction;

			s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value == null ? "" : value);
		};

		// If an array was passed in, assume that it is an array of form elements.
		if (Array.isArray(a) || a.jquery && !jQuery.isPlainObject(a)) {

			// Serialize the form elements
			jQuery.each(a, function () {
				add(this.name, this.value);
			});
		} else {

			// If traditional, encode the "old" way (the way 1.3.2 or older
			// did it), otherwise encode params recursively.
			for (prefix in a) {
				buildParams(prefix, a[prefix], traditional, add);
			}
		}

		// Return the resulting serialization
		return s.join("&");
	};

	jQuery.fn.extend({
		serialize: function serialize() {
			return jQuery.param(this.serializeArray());
		},
		serializeArray: function serializeArray() {
			return this.map(function () {

				// Can add propHook for "elements" to filter or add form elements
				var elements = jQuery.prop(this, "elements");
				return elements ? jQuery.makeArray(elements) : this;
			}).filter(function () {
				var type = this.type;

				// Use .is( ":disabled" ) so that fieldset[disabled] works
				return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type));
			}).map(function (i, elem) {
				var val = jQuery(this).val();

				if (val == null) {
					return null;
				}

				if (Array.isArray(val)) {
					return jQuery.map(val, function (val) {
						return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
					});
				}

				return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
			}).get();
		}
	});

	var r20 = /%20/g,
	    rhash = /#.*$/,
	    rantiCache = /([?&])_=[^&]*/,
	    rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,


	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
	    rnoContent = /^(?:GET|HEAD)$/,
	    rprotocol = /^\/\//,


	/* Prefilters
  * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
  * 2) These are called:
  *    - BEFORE asking for a transport
  *    - AFTER param serialization (s.data is a string if s.processData is true)
  * 3) key is the dataType
  * 4) the catchall symbol "*" can be used
  * 5) execution will start with transport dataType and THEN continue down to "*" if needed
  */
	prefilters = {},


	/* Transports bindings
  * 1) key is the dataType
  * 2) the catchall symbol "*" can be used
  * 3) selection will start with transport dataType and THEN go to "*" if needed
  */
	transports = {},


	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
	allTypes = "*/".concat("*"),


	// Anchor tag for parsing the document origin
	originAnchor = document.createElement("a");
	originAnchor.href = location.href;

	// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
	function addToPrefiltersOrTransports(structure) {

		// dataTypeExpression is optional and defaults to "*"
		return function (dataTypeExpression, func) {

			if (typeof dataTypeExpression !== "string") {
				func = dataTypeExpression;
				dataTypeExpression = "*";
			}

			var dataType,
			    i = 0,
			    dataTypes = dataTypeExpression.toLowerCase().match(rnothtmlwhite) || [];

			if (isFunction(func)) {

				// For each dataType in the dataTypeExpression
				while (dataType = dataTypes[i++]) {

					// Prepend if requested
					if (dataType[0] === "+") {
						dataType = dataType.slice(1) || "*";
						(structure[dataType] = structure[dataType] || []).unshift(func);

						// Otherwise append
					} else {
						(structure[dataType] = structure[dataType] || []).push(func);
					}
				}
			}
		};
	}

	// Base inspection function for prefilters and transports
	function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) {

		var inspected = {},
		    seekingTransport = structure === transports;

		function inspect(dataType) {
			var selected;
			inspected[dataType] = true;
			jQuery.each(structure[dataType] || [], function (_, prefilterOrFactory) {
				var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR);
				if (typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[dataTypeOrTransport]) {

					options.dataTypes.unshift(dataTypeOrTransport);
					inspect(dataTypeOrTransport);
					return false;
				} else if (seekingTransport) {
					return !(selected = dataTypeOrTransport);
				}
			});
			return selected;
		}

		return inspect(options.dataTypes[0]) || !inspected["*"] && inspect("*");
	}

	// A special extend for ajax options
	// that takes "flat" options (not to be deep extended)
	// Fixes #9887
	function ajaxExtend(target, src) {
		var key,
		    deep,
		    flatOptions = jQuery.ajaxSettings.flatOptions || {};

		for (key in src) {
			if (src[key] !== undefined) {
				(flatOptions[key] ? target : deep || (deep = {}))[key] = src[key];
			}
		}
		if (deep) {
			jQuery.extend(true, target, deep);
		}

		return target;
	}

	/* Handles responses to an ajax request:
  * - finds the right dataType (mediates between content-type and expected dataType)
  * - returns the corresponding response
  */
	function ajaxHandleResponses(s, jqXHR, responses) {

		var ct,
		    type,
		    finalDataType,
		    firstDataType,
		    contents = s.contents,
		    dataTypes = s.dataTypes;

		// Remove auto dataType and get content-type in the process
		while (dataTypes[0] === "*") {
			dataTypes.shift();
			if (ct === undefined) {
				ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
			}
		}

		// Check if we're dealing with a known content-type
		if (ct) {
			for (type in contents) {
				if (contents[type] && contents[type].test(ct)) {
					dataTypes.unshift(type);
					break;
				}
			}
		}

		// Check to see if we have a response for the expected dataType
		if (dataTypes[0] in responses) {
			finalDataType = dataTypes[0];
		} else {

			// Try convertible dataTypes
			for (type in responses) {
				if (!dataTypes[0] || s.converters[type + " " + dataTypes[0]]) {
					finalDataType = type;
					break;
				}
				if (!firstDataType) {
					firstDataType = type;
				}
			}

			// Or just use first one
			finalDataType = finalDataType || firstDataType;
		}

		// If we found a dataType
		// We add the dataType to the list if needed
		// and return the corresponding response
		if (finalDataType) {
			if (finalDataType !== dataTypes[0]) {
				dataTypes.unshift(finalDataType);
			}
			return responses[finalDataType];
		}
	}

	/* Chain conversions given the request and the original response
  * Also sets the responseXXX fields on the jqXHR instance
  */
	function ajaxConvert(s, response, jqXHR, isSuccess) {
		var conv2,
		    current,
		    conv,
		    tmp,
		    prev,
		    converters = {},


		// Work with a copy of dataTypes in case we need to modify it for conversion
		dataTypes = s.dataTypes.slice();

		// Create converters map with lowercased keys
		if (dataTypes[1]) {
			for (conv in s.converters) {
				converters[conv.toLowerCase()] = s.converters[conv];
			}
		}

		current = dataTypes.shift();

		// Convert to each sequential dataType
		while (current) {

			if (s.responseFields[current]) {
				jqXHR[s.responseFields[current]] = response;
			}

			// Apply the dataFilter if provided
			if (!prev && isSuccess && s.dataFilter) {
				response = s.dataFilter(response, s.dataType);
			}

			prev = current;
			current = dataTypes.shift();

			if (current) {

				// There's only work to do if current dataType is non-auto
				if (current === "*") {

					current = prev;

					// Convert response if prev dataType is non-auto and differs from current
				} else if (prev !== "*" && prev !== current) {

					// Seek a direct converter
					conv = converters[prev + " " + current] || converters["* " + current];

					// If none found, seek a pair
					if (!conv) {
						for (conv2 in converters) {

							// If conv2 outputs current
							tmp = conv2.split(" ");
							if (tmp[1] === current) {

								// If prev can be converted to accepted input
								conv = converters[prev + " " + tmp[0]] || converters["* " + tmp[0]];
								if (conv) {

									// Condense equivalence converters
									if (conv === true) {
										conv = converters[conv2];

										// Otherwise, insert the intermediate dataType
									} else if (converters[conv2] !== true) {
										current = tmp[0];
										dataTypes.unshift(tmp[1]);
									}
									break;
								}
							}
						}
					}

					// Apply converter (if not an equivalence)
					if (conv !== true) {

						// Unless errors are allowed to bubble, catch and return them
						if (conv && s.throws) {
							response = conv(response);
						} else {
							try {
								response = conv(response);
							} catch (e) {
								return {
									state: "parsererror",
									error: conv ? e : "No conversion from " + prev + " to " + current
								};
							}
						}
					}
				}
			}
		}

		return { state: "success", data: response };
	}

	jQuery.extend({

		// Counter for holding the number of active queries
		active: 0,

		// Last-Modified header cache for next request
		lastModified: {},
		etag: {},

		ajaxSettings: {
			url: location.href,
			type: "GET",
			isLocal: rlocalProtocol.test(location.protocol),
			global: true,
			processData: true,
			async: true,
			contentType: "application/x-www-form-urlencoded; charset=UTF-8",

			/*
   timeout: 0,
   data: null,
   dataType: null,
   username: null,
   password: null,
   cache: null,
   throws: false,
   traditional: false,
   headers: {},
   */

			accepts: {
				"*": allTypes,
				text: "text/plain",
				html: "text/html",
				xml: "application/xml, text/xml",
				json: "application/json, text/javascript"
			},

			contents: {
				xml: /\bxml\b/,
				html: /\bhtml/,
				json: /\bjson\b/
			},

			responseFields: {
				xml: "responseXML",
				text: "responseText",
				json: "responseJSON"
			},

			// Data converters
			// Keys separate source (or catchall "*") and destination types with a single space
			converters: {

				// Convert anything to text
				"* text": String,

				// Text to html (true = no transformation)
				"text html": true,

				// Evaluate text as a json expression
				"text json": JSON.parse,

				// Parse text as xml
				"text xml": jQuery.parseXML
			},

			// For options that shouldn't be deep extended:
			// you can add your own custom options here if
			// and when you create one that shouldn't be
			// deep extended (see ajaxExtend)
			flatOptions: {
				url: true,
				context: true
			}
		},

		// Creates a full fledged settings object into target
		// with both ajaxSettings and settings fields.
		// If target is omitted, writes into ajaxSettings.
		ajaxSetup: function ajaxSetup(target, settings) {
			return settings ?

			// Building a settings object
			ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) :

			// Extending ajaxSettings
			ajaxExtend(jQuery.ajaxSettings, target);
		},

		ajaxPrefilter: addToPrefiltersOrTransports(prefilters),
		ajaxTransport: addToPrefiltersOrTransports(transports),

		// Main method
		ajax: function ajax(url, options) {

			// If url is an object, simulate pre-1.5 signature
			if ((typeof url === "undefined" ? "undefined" : _typeof(url)) === "object") {
				options = url;
				url = undefined;
			}

			// Force options to be an object
			options = options || {};

			var transport,


			// URL without anti-cache param
			cacheURL,


			// Response headers
			responseHeadersString,
			    responseHeaders,


			// timeout handle
			timeoutTimer,


			// Url cleanup var
			urlAnchor,


			// Request state (becomes false upon send and true upon completion)
			completed,


			// To know if global events are to be dispatched
			fireGlobals,


			// Loop variable
			i,


			// uncached part of the url
			uncached,


			// Create the final options object
			s = jQuery.ajaxSetup({}, options),


			// Callbacks context
			callbackContext = s.context || s,


			// Context for global events is callbackContext if it is a DOM node or jQuery collection
			globalEventContext = s.context && (callbackContext.nodeType || callbackContext.jquery) ? jQuery(callbackContext) : jQuery.event,


			// Deferreds
			deferred = jQuery.Deferred(),
			    completeDeferred = jQuery.Callbacks("once memory"),


			// Status-dependent callbacks
			_statusCode = s.statusCode || {},


			// Headers (they are sent all at once)
			requestHeaders = {},
			    requestHeadersNames = {},


			// Default abort message
			strAbort = "canceled",


			// Fake xhr
			jqXHR = {
				readyState: 0,

				// Builds headers hashtable if needed
				getResponseHeader: function getResponseHeader(key) {
					var match;
					if (completed) {
						if (!responseHeaders) {
							responseHeaders = {};
							while (match = rheaders.exec(responseHeadersString)) {
								responseHeaders[match[1].toLowerCase()] = match[2];
							}
						}
						match = responseHeaders[key.toLowerCase()];
					}
					return match == null ? null : match;
				},

				// Raw string
				getAllResponseHeaders: function getAllResponseHeaders() {
					return completed ? responseHeadersString : null;
				},

				// Caches the header
				setRequestHeader: function setRequestHeader(name, value) {
					if (completed == null) {
						name = requestHeadersNames[name.toLowerCase()] = requestHeadersNames[name.toLowerCase()] || name;
						requestHeaders[name] = value;
					}
					return this;
				},

				// Overrides response content-type header
				overrideMimeType: function overrideMimeType(type) {
					if (completed == null) {
						s.mimeType = type;
					}
					return this;
				},

				// Status-dependent callbacks
				statusCode: function statusCode(map) {
					var code;
					if (map) {
						if (completed) {

							// Execute the appropriate callbacks
							jqXHR.always(map[jqXHR.status]);
						} else {

							// Lazy-add the new callbacks in a way that preserves old ones
							for (code in map) {
								_statusCode[code] = [_statusCode[code], map[code]];
							}
						}
					}
					return this;
				},

				// Cancel the request
				abort: function abort(statusText) {
					var finalText = statusText || strAbort;
					if (transport) {
						transport.abort(finalText);
					}
					done(0, finalText);
					return this;
				}
			};

			// Attach deferreds
			deferred.promise(jqXHR);

			// Add protocol if not provided (prefilters might expect it)
			// Handle falsy url in the settings object (#10093: consistency with old signature)
			// We also use the url parameter if available
			s.url = ((url || s.url || location.href) + "").replace(rprotocol, location.protocol + "//");

			// Alias method option to type as per ticket #12004
			s.type = options.method || options.type || s.method || s.type;

			// Extract dataTypes list
			s.dataTypes = (s.dataType || "*").toLowerCase().match(rnothtmlwhite) || [""];

			// A cross-domain request is in order when the origin doesn't match the current origin.
			if (s.crossDomain == null) {
				urlAnchor = document.createElement("a");

				// Support: IE <=8 - 11, Edge 12 - 15
				// IE throws exception on accessing the href property if url is malformed,
				// e.g. http://example.com:80x/
				try {
					urlAnchor.href = s.url;

					// Support: IE <=8 - 11 only
					// Anchor's host property isn't correctly set when s.url is relative
					urlAnchor.href = urlAnchor.href;
					s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host;
				} catch (e) {

					// If there is an error parsing the URL, assume it is crossDomain,
					// it can be rejected by the transport if it is invalid
					s.crossDomain = true;
				}
			}

			// Convert data if not already a string
			if (s.data && s.processData && typeof s.data !== "string") {
				s.data = jQuery.param(s.data, s.traditional);
			}

			// Apply prefilters
			inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);

			// If request was aborted inside a prefilter, stop there
			if (completed) {
				return jqXHR;
			}

			// We can fire global events as of now if asked to
			// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
			fireGlobals = jQuery.event && s.global;

			// Watch for a new set of requests
			if (fireGlobals && jQuery.active++ === 0) {
				jQuery.event.trigger("ajaxStart");
			}

			// Uppercase the type
			s.type = s.type.toUpperCase();

			// Determine if request has content
			s.hasContent = !rnoContent.test(s.type);

			// Save the URL in case we're toying with the If-Modified-Since
			// and/or If-None-Match header later on
			// Remove hash to simplify url manipulation
			cacheURL = s.url.replace(rhash, "");

			// More options handling for requests with no content
			if (!s.hasContent) {

				// Remember the hash so we can put it back
				uncached = s.url.slice(cacheURL.length);

				// If data is available and should be processed, append data to url
				if (s.data && (s.processData || typeof s.data === "string")) {
					cacheURL += (rquery.test(cacheURL) ? "&" : "?") + s.data;

					// #9682: remove data so that it's not used in an eventual retry
					delete s.data;
				}

				// Add or update anti-cache param if needed
				if (s.cache === false) {
					cacheURL = cacheURL.replace(rantiCache, "$1");
					uncached = (rquery.test(cacheURL) ? "&" : "?") + "_=" + nonce++ + uncached;
				}

				// Put hash and anti-cache on the URL that will be requested (gh-1732)
				s.url = cacheURL + uncached;

				// Change '%20' to '+' if this is encoded form body content (gh-2658)
			} else if (s.data && s.processData && (s.contentType || "").indexOf("application/x-www-form-urlencoded") === 0) {
				s.data = s.data.replace(r20, "+");
			}

			// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
			if (s.ifModified) {
				if (jQuery.lastModified[cacheURL]) {
					jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[cacheURL]);
				}
				if (jQuery.etag[cacheURL]) {
					jqXHR.setRequestHeader("If-None-Match", jQuery.etag[cacheURL]);
				}
			}

			// Set the correct header, if data is being sent
			if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
				jqXHR.setRequestHeader("Content-Type", s.contentType);
			}

			// Set the Accepts header for the server, depending on the dataType
			jqXHR.setRequestHeader("Accept", s.dataTypes[0] && s.accepts[s.dataTypes[0]] ? s.accepts[s.dataTypes[0]] + (s.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "") : s.accepts["*"]);

			// Check for headers option
			for (i in s.headers) {
				jqXHR.setRequestHeader(i, s.headers[i]);
			}

			// Allow custom headers/mimetypes and early abort
			if (s.beforeSend && (s.beforeSend.call(callbackContext, jqXHR, s) === false || completed)) {

				// Abort if not done already and return
				return jqXHR.abort();
			}

			// Aborting is no longer a cancellation
			strAbort = "abort";

			// Install callbacks on deferreds
			completeDeferred.add(s.complete);
			jqXHR.done(s.success);
			jqXHR.fail(s.error);

			// Get transport
			transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR);

			// If no transport, we auto-abort
			if (!transport) {
				done(-1, "No Transport");
			} else {
				jqXHR.readyState = 1;

				// Send global event
				if (fireGlobals) {
					globalEventContext.trigger("ajaxSend", [jqXHR, s]);
				}

				// If request was aborted inside ajaxSend, stop there
				if (completed) {
					return jqXHR;
				}

				// Timeout
				if (s.async && s.timeout > 0) {
					timeoutTimer = window.setTimeout(function () {
						jqXHR.abort("timeout");
					}, s.timeout);
				}

				try {
					completed = false;
					transport.send(requestHeaders, done);
				} catch (e) {

					// Rethrow post-completion exceptions
					if (completed) {
						throw e;
					}

					// Propagate others as results
					done(-1, e);
				}
			}

			// Callback for when everything is done
			function done(status, nativeStatusText, responses, headers) {
				var isSuccess,
				    success,
				    error,
				    response,
				    modified,
				    statusText = nativeStatusText;

				// Ignore repeat invocations
				if (completed) {
					return;
				}

				completed = true;

				// Clear timeout if it exists
				if (timeoutTimer) {
					window.clearTimeout(timeoutTimer);
				}

				// Dereference transport for early garbage collection
				// (no matter how long the jqXHR object will be used)
				transport = undefined;

				// Cache response headers
				responseHeadersString = headers || "";

				// Set readyState
				jqXHR.readyState = status > 0 ? 4 : 0;

				// Determine if successful
				isSuccess = status >= 200 && status < 300 || status === 304;

				// Get response data
				if (responses) {
					response = ajaxHandleResponses(s, jqXHR, responses);
				}

				// Convert no matter what (that way responseXXX fields are always set)
				response = ajaxConvert(s, response, jqXHR, isSuccess);

				// If successful, handle type chaining
				if (isSuccess) {

					// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
					if (s.ifModified) {
						modified = jqXHR.getResponseHeader("Last-Modified");
						if (modified) {
							jQuery.lastModified[cacheURL] = modified;
						}
						modified = jqXHR.getResponseHeader("etag");
						if (modified) {
							jQuery.etag[cacheURL] = modified;
						}
					}

					// if no content
					if (status === 204 || s.type === "HEAD") {
						statusText = "nocontent";

						// if not modified
					} else if (status === 304) {
						statusText = "notmodified";

						// If we have data, let's convert it
					} else {
						statusText = response.state;
						success = response.data;
						error = response.error;
						isSuccess = !error;
					}
				} else {

					// Extract error from statusText and normalize for non-aborts
					error = statusText;
					if (status || !statusText) {
						statusText = "error";
						if (status < 0) {
							status = 0;
						}
					}
				}

				// Set data for the fake xhr object
				jqXHR.status = status;
				jqXHR.statusText = (nativeStatusText || statusText) + "";

				// Success/Error
				if (isSuccess) {
					deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
				} else {
					deferred.rejectWith(callbackContext, [jqXHR, statusText, error]);
				}

				// Status-dependent callbacks
				jqXHR.statusCode(_statusCode);
				_statusCode = undefined;

				if (fireGlobals) {
					globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError", [jqXHR, s, isSuccess ? success : error]);
				}

				// Complete
				completeDeferred.fireWith(callbackContext, [jqXHR, statusText]);

				if (fireGlobals) {
					globalEventContext.trigger("ajaxComplete", [jqXHR, s]);

					// Handle the global AJAX counter
					if (! --jQuery.active) {
						jQuery.event.trigger("ajaxStop");
					}
				}
			}

			return jqXHR;
		},

		getJSON: function getJSON(url, data, callback) {
			return jQuery.get(url, data, callback, "json");
		},

		getScript: function getScript(url, callback) {
			return jQuery.get(url, undefined, callback, "script");
		}
	});

	jQuery.each(["get", "post"], function (i, method) {
		jQuery[method] = function (url, data, callback, type) {

			// Shift arguments if data argument was omitted
			if (isFunction(data)) {
				type = type || callback;
				callback = data;
				data = undefined;
			}

			// The url can be an options object (which then must have .url)
			return jQuery.ajax(jQuery.extend({
				url: url,
				type: method,
				dataType: type,
				data: data,
				success: callback
			}, jQuery.isPlainObject(url) && url));
		};
	});

	jQuery._evalUrl = function (url) {
		return jQuery.ajax({
			url: url,

			// Make this explicit, since user can override this through ajaxSetup (#11264)
			type: "GET",
			dataType: "script",
			cache: true,
			async: false,
			global: false,
			"throws": true
		});
	};

	jQuery.fn.extend({
		wrapAll: function wrapAll(html) {
			var wrap;

			if (this[0]) {
				if (isFunction(html)) {
					html = html.call(this[0]);
				}

				// The elements to wrap the target around
				wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true);

				if (this[0].parentNode) {
					wrap.insertBefore(this[0]);
				}

				wrap.map(function () {
					var elem = this;

					while (elem.firstElementChild) {
						elem = elem.firstElementChild;
					}

					return elem;
				}).append(this);
			}

			return this;
		},

		wrapInner: function wrapInner(html) {
			if (isFunction(html)) {
				return this.each(function (i) {
					jQuery(this).wrapInner(html.call(this, i));
				});
			}

			return this.each(function () {
				var self = jQuery(this),
				    contents = self.contents();

				if (contents.length) {
					contents.wrapAll(html);
				} else {
					self.append(html);
				}
			});
		},

		wrap: function wrap(html) {
			var htmlIsFunction = isFunction(html);

			return this.each(function (i) {
				jQuery(this).wrapAll(htmlIsFunction ? html.call(this, i) : html);
			});
		},

		unwrap: function unwrap(selector) {
			this.parent(selector).not("body").each(function () {
				jQuery(this).replaceWith(this.childNodes);
			});
			return this;
		}
	});

	jQuery.expr.pseudos.hidden = function (elem) {
		return !jQuery.expr.pseudos.visible(elem);
	};
	jQuery.expr.pseudos.visible = function (elem) {
		return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
	};

	jQuery.ajaxSettings.xhr = function () {
		try {
			return new window.XMLHttpRequest();
		} catch (e) {}
	};

	var xhrSuccessStatus = {

		// File protocol always yields status code 0, assume 200
		0: 200,

		// Support: IE <=9 only
		// #1450: sometimes IE returns 1223 when it should be 204
		1223: 204
	},
	    xhrSupported = jQuery.ajaxSettings.xhr();

	support.cors = !!xhrSupported && "withCredentials" in xhrSupported;
	support.ajax = xhrSupported = !!xhrSupported;

	jQuery.ajaxTransport(function (options) {
		var _callback, errorCallback;

		// Cross domain only allowed if supported through XMLHttpRequest
		if (support.cors || xhrSupported && !options.crossDomain) {
			return {
				send: function send(headers, complete) {
					var i,
					    xhr = options.xhr();

					xhr.open(options.type, options.url, options.async, options.username, options.password);

					// Apply custom fields if provided
					if (options.xhrFields) {
						for (i in options.xhrFields) {
							xhr[i] = options.xhrFields[i];
						}
					}

					// Override mime type if needed
					if (options.mimeType && xhr.overrideMimeType) {
						xhr.overrideMimeType(options.mimeType);
					}

					// X-Requested-With header
					// For cross-domain requests, seeing as conditions for a preflight are
					// akin to a jigsaw puzzle, we simply never set it to be sure.
					// (it can always be set on a per-request basis or even using ajaxSetup)
					// For same-domain requests, won't change header if already provided.
					if (!options.crossDomain && !headers["X-Requested-With"]) {
						headers["X-Requested-With"] = "XMLHttpRequest";
					}

					// Set headers
					for (i in headers) {
						xhr.setRequestHeader(i, headers[i]);
					}

					// Callback
					_callback = function callback(type) {
						return function () {
							if (_callback) {
								_callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.ontimeout = xhr.onreadystatechange = null;

								if (type === "abort") {
									xhr.abort();
								} else if (type === "error") {

									// Support: IE <=9 only
									// On a manual native abort, IE9 throws
									// errors on any property access that is not readyState
									if (typeof xhr.status !== "number") {
										complete(0, "error");
									} else {
										complete(

										// File: protocol always yields status 0; see #8605, #14207
										xhr.status, xhr.statusText);
									}
								} else {
									complete(xhrSuccessStatus[xhr.status] || xhr.status, xhr.statusText,

									// Support: IE <=9 only
									// IE9 has no XHR2 but throws on binary (trac-11426)
									// For XHR2 non-text, let the caller handle it (gh-2498)
									(xhr.responseType || "text") !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders());
								}
							}
						};
					};

					// Listen to events
					xhr.onload = _callback();
					errorCallback = xhr.onerror = xhr.ontimeout = _callback("error");

					// Support: IE 9 only
					// Use onreadystatechange to replace onabort
					// to handle uncaught aborts
					if (xhr.onabort !== undefined) {
						xhr.onabort = errorCallback;
					} else {
						xhr.onreadystatechange = function () {

							// Check readyState before timeout as it changes
							if (xhr.readyState === 4) {

								// Allow onerror to be called first,
								// but that will not handle a native abort
								// Also, save errorCallback to a variable
								// as xhr.onerror cannot be accessed
								window.setTimeout(function () {
									if (_callback) {
										errorCallback();
									}
								});
							}
						};
					}

					// Create the abort callback
					_callback = _callback("abort");

					try {

						// Do send the request (this may raise an exception)
						xhr.send(options.hasContent && options.data || null);
					} catch (e) {

						// #14683: Only rethrow if this hasn't been notified as an error yet
						if (_callback) {
							throw e;
						}
					}
				},

				abort: function abort() {
					if (_callback) {
						_callback();
					}
				}
			};
		}
	});

	// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
	jQuery.ajaxPrefilter(function (s) {
		if (s.crossDomain) {
			s.contents.script = false;
		}
	});

	// Install script dataType
	jQuery.ajaxSetup({
		accepts: {
			script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript"
		},
		contents: {
			script: /\b(?:java|ecma)script\b/
		},
		converters: {
			"text script": function textScript(text) {
				jQuery.globalEval(text);
				return text;
			}
		}
	});

	// Handle cache's special case and crossDomain
	jQuery.ajaxPrefilter("script", function (s) {
		if (s.cache === undefined) {
			s.cache = false;
		}
		if (s.crossDomain) {
			s.type = "GET";
		}
	});

	// Bind script tag hack transport
	jQuery.ajaxTransport("script", function (s) {

		// This transport only deals with cross domain requests
		if (s.crossDomain) {
			var script, _callback2;
			return {
				send: function send(_, complete) {
					script = jQuery("<script>").prop({
						charset: s.scriptCharset,
						src: s.url
					}).on("load error", _callback2 = function callback(evt) {
						script.remove();
						_callback2 = null;
						if (evt) {
							complete(evt.type === "error" ? 404 : 200, evt.type);
						}
					});

					// Use native DOM manipulation to avoid our domManip AJAX trickery
					document.head.appendChild(script[0]);
				},
				abort: function abort() {
					if (_callback2) {
						_callback2();
					}
				}
			};
		}
	});

	var oldCallbacks = [],
	    rjsonp = /(=)\?(?=&|$)|\?\?/;

	// Default jsonp settings
	jQuery.ajaxSetup({
		jsonp: "callback",
		jsonpCallback: function jsonpCallback() {
			var callback = oldCallbacks.pop() || jQuery.expando + "_" + nonce++;
			this[callback] = true;
			return callback;
		}
	});

	// Detect, normalize options and install callbacks for jsonp requests
	jQuery.ajaxPrefilter("json jsonp", function (s, originalSettings, jqXHR) {

		var callbackName,
		    overwritten,
		    responseContainer,
		    jsonProp = s.jsonp !== false && (rjsonp.test(s.url) ? "url" : typeof s.data === "string" && (s.contentType || "").indexOf("application/x-www-form-urlencoded") === 0 && rjsonp.test(s.data) && "data");

		// Handle iff the expected data type is "jsonp" or we have a parameter to set
		if (jsonProp || s.dataTypes[0] === "jsonp") {

			// Get callback name, remembering preexisting value associated with it
			callbackName = s.jsonpCallback = isFunction(s.jsonpCallback) ? s.jsonpCallback() : s.jsonpCallback;

			// Insert callback into url or form data
			if (jsonProp) {
				s[jsonProp] = s[jsonProp].replace(rjsonp, "$1" + callbackName);
			} else if (s.jsonp !== false) {
				s.url += (rquery.test(s.url) ? "&" : "?") + s.jsonp + "=" + callbackName;
			}

			// Use data converter to retrieve json after script execution
			s.converters["script json"] = function () {
				if (!responseContainer) {
					jQuery.error(callbackName + " was not called");
				}
				return responseContainer[0];
			};

			// Force json dataType
			s.dataTypes[0] = "json";

			// Install callback
			overwritten = window[callbackName];
			window[callbackName] = function () {
				responseContainer = arguments;
			};

			// Clean-up function (fires after converters)
			jqXHR.always(function () {

				// If previous value didn't exist - remove it
				if (overwritten === undefined) {
					jQuery(window).removeProp(callbackName);

					// Otherwise restore preexisting value
				} else {
					window[callbackName] = overwritten;
				}

				// Save back as free
				if (s[callbackName]) {

					// Make sure that re-using the options doesn't screw things around
					s.jsonpCallback = originalSettings.jsonpCallback;

					// Save the callback name for future use
					oldCallbacks.push(callbackName);
				}

				// Call if it was a function and we have a response
				if (responseContainer && isFunction(overwritten)) {
					overwritten(responseContainer[0]);
				}

				responseContainer = overwritten = undefined;
			});

			// Delegate to script
			return "script";
		}
	});

	// Support: Safari 8 only
	// In Safari 8 documents created via document.implementation.createHTMLDocument
	// collapse sibling forms: the second one becomes a child of the first one.
	// Because of that, this security measure has to be disabled in Safari 8.
	// https://bugs.webkit.org/show_bug.cgi?id=137337
	support.createHTMLDocument = function () {
		var body = document.implementation.createHTMLDocument("").body;
		body.innerHTML = "<form></form><form></form>";
		return body.childNodes.length === 2;
	}();

	// Argument "data" should be string of html
	// context (optional): If specified, the fragment will be created in this context,
	// defaults to document
	// keepScripts (optional): If true, will include scripts passed in the html string
	jQuery.parseHTML = function (data, context, keepScripts) {
		if (typeof data !== "string") {
			return [];
		}
		if (typeof context === "boolean") {
			keepScripts = context;
			context = false;
		}

		var base, parsed, scripts;

		if (!context) {

			// Stop scripts or inline event handlers from being executed immediately
			// by using document.implementation
			if (support.createHTMLDocument) {
				context = document.implementation.createHTMLDocument("");

				// Set the base href for the created document
				// so any parsed elements with URLs
				// are based on the document's URL (gh-2965)
				base = context.createElement("base");
				base.href = document.location.href;
				context.head.appendChild(base);
			} else {
				context = document;
			}
		}

		parsed = rsingleTag.exec(data);
		scripts = !keepScripts && [];

		// Single tag
		if (parsed) {
			return [context.createElement(parsed[1])];
		}

		parsed = buildFragment([data], context, scripts);

		if (scripts && scripts.length) {
			jQuery(scripts).remove();
		}

		return jQuery.merge([], parsed.childNodes);
	};

	/**
  * Load a url into a page
  */
	jQuery.fn.load = function (url, params, callback) {
		var selector,
		    type,
		    response,
		    self = this,
		    off = url.indexOf(" ");

		if (off > -1) {
			selector = stripAndCollapse(url.slice(off));
			url = url.slice(0, off);
		}

		// If it's a function
		if (isFunction(params)) {

			// We assume that it's the callback
			callback = params;
			params = undefined;

			// Otherwise, build a param string
		} else if (params && (typeof params === "undefined" ? "undefined" : _typeof(params)) === "object") {
			type = "POST";
		}

		// If we have elements to modify, make the request
		if (self.length > 0) {
			jQuery.ajax({
				url: url,

				// If "type" variable is undefined, then "GET" method will be used.
				// Make value of this field explicit since
				// user can override it through ajaxSetup method
				type: type || "GET",
				dataType: "html",
				data: params
			}).done(function (responseText) {

				// Save response for use in complete callback
				response = arguments;

				self.html(selector ?

				// If a selector was specified, locate the right elements in a dummy div
				// Exclude scripts to avoid IE 'Permission Denied' errors
				jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :

				// Otherwise use the full result
				responseText);

				// If the request succeeds, this function gets "data", "status", "jqXHR"
				// but they are ignored because response was set above.
				// If it fails, this function gets "jqXHR", "status", "error"
			}).always(callback && function (jqXHR, status) {
				self.each(function () {
					callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
				});
			});
		}

		return this;
	};

	// Attach a bunch of functions for handling common AJAX events
	jQuery.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function (i, type) {
		jQuery.fn[type] = function (fn) {
			return this.on(type, fn);
		};
	});

	jQuery.expr.pseudos.animated = function (elem) {
		return jQuery.grep(jQuery.timers, function (fn) {
			return elem === fn.elem;
		}).length;
	};

	jQuery.offset = {
		setOffset: function setOffset(elem, options, i) {
			var curPosition,
			    curLeft,
			    curCSSTop,
			    curTop,
			    curOffset,
			    curCSSLeft,
			    calculatePosition,
			    position = jQuery.css(elem, "position"),
			    curElem = jQuery(elem),
			    props = {};

			// Set position first, in-case top/left are set even on static elem
			if (position === "static") {
				elem.style.position = "relative";
			}

			curOffset = curElem.offset();
			curCSSTop = jQuery.css(elem, "top");
			curCSSLeft = jQuery.css(elem, "left");
			calculatePosition = (position === "absolute" || position === "fixed") && (curCSSTop + curCSSLeft).indexOf("auto") > -1;

			// Need to be able to calculate position if either
			// top or left is auto and position is either absolute or fixed
			if (calculatePosition) {
				curPosition = curElem.position();
				curTop = curPosition.top;
				curLeft = curPosition.left;
			} else {
				curTop = parseFloat(curCSSTop) || 0;
				curLeft = parseFloat(curCSSLeft) || 0;
			}

			if (isFunction(options)) {

				// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
				options = options.call(elem, i, jQuery.extend({}, curOffset));
			}

			if (options.top != null) {
				props.top = options.top - curOffset.top + curTop;
			}
			if (options.left != null) {
				props.left = options.left - curOffset.left + curLeft;
			}

			if ("using" in options) {
				options.using.call(elem, props);
			} else {
				curElem.css(props);
			}
		}
	};

	jQuery.fn.extend({

		// offset() relates an element's border box to the document origin
		offset: function offset(options) {

			// Preserve chaining for setter
			if (arguments.length) {
				return options === undefined ? this : this.each(function (i) {
					jQuery.offset.setOffset(this, options, i);
				});
			}

			var rect,
			    win,
			    elem = this[0];

			if (!elem) {
				return;
			}

			// Return zeros for disconnected and hidden (display: none) elements (gh-2310)
			// Support: IE <=11 only
			// Running getBoundingClientRect on a
			// disconnected node in IE throws an error
			if (!elem.getClientRects().length) {
				return { top: 0, left: 0 };
			}

			// Get document-relative position by adding viewport scroll to viewport-relative gBCR
			rect = elem.getBoundingClientRect();
			win = elem.ownerDocument.defaultView;
			return {
				top: rect.top + win.pageYOffset,
				left: rect.left + win.pageXOffset
			};
		},

		// position() relates an element's margin box to its offset parent's padding box
		// This corresponds to the behavior of CSS absolute positioning
		position: function position() {
			if (!this[0]) {
				return;
			}

			var offsetParent,
			    offset,
			    doc,
			    elem = this[0],
			    parentOffset = { top: 0, left: 0 };

			// position:fixed elements are offset from the viewport, which itself always has zero offset
			if (jQuery.css(elem, "position") === "fixed") {

				// Assume position:fixed implies availability of getBoundingClientRect
				offset = elem.getBoundingClientRect();
			} else {
				offset = this.offset();

				// Account for the *real* offset parent, which can be the document or its root element
				// when a statically positioned element is identified
				doc = elem.ownerDocument;
				offsetParent = elem.offsetParent || doc.documentElement;
				while (offsetParent && (offsetParent === doc.body || offsetParent === doc.documentElement) && jQuery.css(offsetParent, "position") === "static") {

					offsetParent = offsetParent.parentNode;
				}
				if (offsetParent && offsetParent !== elem && offsetParent.nodeType === 1) {

					// Incorporate borders into its offset, since they are outside its content origin
					parentOffset = jQuery(offsetParent).offset();
					parentOffset.top += jQuery.css(offsetParent, "borderTopWidth", true);
					parentOffset.left += jQuery.css(offsetParent, "borderLeftWidth", true);
				}
			}

			// Subtract parent offsets and element margins
			return {
				top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", true),
				left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", true)
			};
		},

		// This method will return documentElement in the following cases:
		// 1) For the element inside the iframe without offsetParent, this method will return
		//    documentElement of the parent window
		// 2) For the hidden or detached element
		// 3) For body or html element, i.e. in case of the html node - it will return itself
		//
		// but those exceptions were never presented as a real life use-cases
		// and might be considered as more preferable results.
		//
		// This logic, however, is not guaranteed and can change at any point in the future
		offsetParent: function offsetParent() {
			return this.map(function () {
				var offsetParent = this.offsetParent;

				while (offsetParent && jQuery.css(offsetParent, "position") === "static") {
					offsetParent = offsetParent.offsetParent;
				}

				return offsetParent || documentElement;
			});
		}
	});

	// Create scrollLeft and scrollTop methods
	jQuery.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function (method, prop) {
		var top = "pageYOffset" === prop;

		jQuery.fn[method] = function (val) {
			return access(this, function (elem, method, val) {

				// Coalesce documents and windows
				var win;
				if (isWindow(elem)) {
					win = elem;
				} else if (elem.nodeType === 9) {
					win = elem.defaultView;
				}

				if (val === undefined) {
					return win ? win[prop] : elem[method];
				}

				if (win) {
					win.scrollTo(!top ? val : win.pageXOffset, top ? val : win.pageYOffset);
				} else {
					elem[method] = val;
				}
			}, method, val, arguments.length);
		};
	});

	// Support: Safari <=7 - 9.1, Chrome <=37 - 49
	// Add the top/left cssHooks using jQuery.fn.position
	// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
	// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
	// getComputedStyle returns percent when specified for top/left/bottom/right;
	// rather than make the css module depend on the offset module, just check for it here
	jQuery.each(["top", "left"], function (i, prop) {
		jQuery.cssHooks[prop] = addGetHookIf(support.pixelPosition, function (elem, computed) {
			if (computed) {
				computed = curCSS(elem, prop);

				// If curCSS returns percentage, fallback to offset
				return rnumnonpx.test(computed) ? jQuery(elem).position()[prop] + "px" : computed;
			}
		});
	});

	// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
	jQuery.each({ Height: "height", Width: "width" }, function (name, type) {
		jQuery.each({ padding: "inner" + name, content: type, "": "outer" + name }, function (defaultExtra, funcName) {

			// Margin is only for outerHeight, outerWidth
			jQuery.fn[funcName] = function (margin, value) {
				var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"),
				    extra = defaultExtra || (margin === true || value === true ? "margin" : "border");

				return access(this, function (elem, type, value) {
					var doc;

					if (isWindow(elem)) {

						// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
						return funcName.indexOf("outer") === 0 ? elem["inner" + name] : elem.document.documentElement["client" + name];
					}

					// Get document width or height
					if (elem.nodeType === 9) {
						doc = elem.documentElement;

						// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
						// whichever is greatest
						return Math.max(elem.body["scroll" + name], doc["scroll" + name], elem.body["offset" + name], doc["offset" + name], doc["client" + name]);
					}

					return value === undefined ?

					// Get width or height on the element, requesting but not forcing parseFloat
					jQuery.css(elem, type, extra) :

					// Set width or height on the element
					jQuery.style(elem, type, value, extra);
				}, type, chainable ? margin : undefined, chainable);
			};
		});
	});

	jQuery.each(("blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu").split(" "), function (i, name) {

		// Handle event binding
		jQuery.fn[name] = function (data, fn) {
			return arguments.length > 0 ? this.on(name, null, data, fn) : this.trigger(name);
		};
	});

	jQuery.fn.extend({
		hover: function hover(fnOver, fnOut) {
			return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
		}
	});

	jQuery.fn.extend({

		bind: function bind(types, data, fn) {
			return this.on(types, null, data, fn);
		},
		unbind: function unbind(types, fn) {
			return this.off(types, null, fn);
		},

		delegate: function delegate(selector, types, data, fn) {
			return this.on(types, selector, data, fn);
		},
		undelegate: function undelegate(selector, types, fn) {

			// ( namespace ) or ( selector, types [, fn] )
			return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn);
		}
	});

	// Bind a function to a context, optionally partially applying any
	// arguments.
	// jQuery.proxy is deprecated to promote standards (specifically Function#bind)
	// However, it is not slated for removal any time soon
	jQuery.proxy = function (fn, context) {
		var tmp, args, proxy;

		if (typeof context === "string") {
			tmp = fn[context];
			context = fn;
			fn = tmp;
		}

		// Quick check to determine if target is callable, in the spec
		// this throws a TypeError, but we will just return undefined.
		if (!isFunction(fn)) {
			return undefined;
		}

		// Simulated bind
		args = _slice.call(arguments, 2);
		proxy = function proxy() {
			return fn.apply(context || this, args.concat(_slice.call(arguments)));
		};

		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || jQuery.guid++;

		return proxy;
	};

	jQuery.holdReady = function (hold) {
		if (hold) {
			jQuery.readyWait++;
		} else {
			jQuery.ready(true);
		}
	};
	jQuery.isArray = Array.isArray;
	jQuery.parseJSON = JSON.parse;
	jQuery.nodeName = nodeName;
	jQuery.isFunction = isFunction;
	jQuery.isWindow = isWindow;
	jQuery.camelCase = camelCase;
	jQuery.type = toType;

	jQuery.now = Date.now;

	jQuery.isNumeric = function (obj) {

		// As of jQuery 3.0, isNumeric is limited to
		// strings and numbers (primitives or objects)
		// that can be coerced to finite numbers (gh-2662)
		var type = jQuery.type(obj);
		return (type === "number" || type === "string") &&

		// parseFloat NaNs numeric-cast false positives ("")
		// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
		// subtraction forces infinities to NaN
		!isNaN(obj - parseFloat(obj));
	};

	// Register as a named AMD module, since jQuery can be concatenated with other
	// files that may use define, but not via a proper concatenation script that
	// understands anonymous AMD modules. A named AMD is safest and most robust
	// way to register. Lowercase jquery is used because AMD module names are
	// derived from file names, and jQuery is normally delivered in a lowercase
	// file name. Do this after creating the global so that if an AMD module wants
	// to call noConflict to hide this version of jQuery, it will work.

	// Note that for maximum portability, libraries that are not jQuery should
	// declare themselves as anonymous modules, and avoid setting a global if an
	// AMD loader is present. jQuery is a special case. For more information, see
	// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon

	if (true) {
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
			return jQuery;
		}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	}

	var

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,


	// Map over the $ in case of overwrite
	_$ = window.$;

	jQuery.noConflict = function (deep) {
		if (window.$ === jQuery) {
			window.$ = _$;
		}

		if (deep && window.jQuery === jQuery) {
			window.jQuery = _jQuery;
		}

		return jQuery;
	};

	// Expose jQuery and $ identifiers, even in AMD
	// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
	// and CommonJS for browser emulators (#13566)
	if (!noGlobal) {
		window.jQuery = window.$ = jQuery;
	}

	return jQuery;
});
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module)))

/***/ }),

/***/ "./node_modules/line-i18n/dist/LanguageService.js":
/*!********************************************************!*\
  !*** ./node_modules/line-i18n/dist/LanguageService.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
var LanguageService = /** @class */function () {
    function LanguageService(lsKey, defaultLang) {
        if (defaultLang === void 0) {
            defaultLang = 'pt';
        }
        this.lsKey = lsKey;
        this.defaultLang = defaultLang;
        this.listeners = [];
        this.document = document;
        this.setupListener();
    }
    LanguageService.prototype.setupListener = function () {
        var _this = this;
        if (this.document !== null) {
            this.document.addEventListener("storage", function (event) {
                var e = event;
                if (e.key === _this.lsKey) {
                    _this.listeners.forEach(function (l) {
                        return l();
                    });
                }
            });
        }
    };
    LanguageService.prototype.getLang = function () {
        var lang = localStorage.getItem(this.lsKey);
        if (lang === null || lang === undefined) {
            console.warn("Internal Error: User language information has not been set. Returning default...");
            return this.getDefaultLang();
        }
        return lang;
    };
    LanguageService.prototype.getDefaultLang = function () {
        return this.defaultLang;
    };
    LanguageService.prototype.registerLanguageChangeListener = function (listener) {
        this.listeners.push(listener);
    };
    return LanguageService;
}();
exports.LanguageService = LanguageService;

/***/ }),

/***/ "./node_modules/line-i18n/dist/LanguageServiceNoLS.js":
/*!************************************************************!*\
  !*** ./node_modules/line-i18n/dist/LanguageServiceNoLS.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
var LanguageServiceNoLS = /** @class */function () {
    function LanguageServiceNoLS(lang) {
        this.lang = lang;
        this.listeners = [];
    }
    LanguageServiceNoLS.prototype.setupListener = function () {};
    LanguageServiceNoLS.prototype.notifyChange = function () {
        this.listeners.forEach(function (l) {
            return l();
        });
    };
    LanguageServiceNoLS.prototype.setLang = function (lang) {
        this.lang = lang;
        this.notifyChange();
    };
    LanguageServiceNoLS.prototype.getLang = function () {
        return this.lang;
    };
    LanguageServiceNoLS.prototype.getDefaultLang = function () {
        return this.lang;
    };
    LanguageServiceNoLS.prototype.registerLanguageChangeListener = function (listener) {
        this.listeners.push(listener);
    };
    return LanguageServiceNoLS;
}();
exports.LanguageServiceNoLS = LanguageServiceNoLS;

/***/ }),

/***/ "./node_modules/line-i18n/dist/LocalizedStrings.js":
/*!*********************************************************!*\
  !*** ./node_modules/line-i18n/dist/LocalizedStrings.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.LocalizedStrings = undefined;

var _StringTypes = __webpack_require__(/*! ./StringTypes */ "./node_modules/line-i18n/dist/StringTypes.js");

var LocalizedStrings = /** @class */function () {
    function LocalizedStrings(service, i18nData, listenToChange) {
        if (listenToChange === void 0) {
            listenToChange = false;
        }
        var _this = this;
        this.service = service;
        this.i18nData = i18nData;
        this.listenToChange = listenToChange;
        this.document = document;
        if (this.listenToChange) {
            service.registerLanguageChangeListener(function () {
                _this.updateTagText();
            });
        }
    }
    LocalizedStrings.prototype.getString = function (id, type) {
        var i18nObj = this.i18nData[this.service.getLang()];
        if (!!!i18nObj) {
            console.warn("Internal Error. The language set at ivprog.lang is not valid: " + this.service.getLang());
            i18nObj = this.i18nData[this.service.getDefaultLang()];
        }
        if (!!!i18nObj[type]) {
            return "{MISSING_I18N_TYPE_IDENTIFIER}";
        } else if (!!!i18nObj[type][id]) {
            return "{MISSING_I18N_IDENTIFIER}";
        } else {
            return i18nObj[type][id];
        }
    };
    LocalizedStrings.prototype.getOR = function () {
        return this.getUI('join_or');
    };
    LocalizedStrings.prototype.getError = function (id, context) {
        if (context === void 0) {
            context = [];
        }
        var text = this.getString(id, _StringTypes.StringTypes.ERROR);
        return this.processString(text, context);
    };
    LocalizedStrings.prototype.getMessage = function (id, context) {
        if (context === void 0) {
            context = [];
        }
        var text = this.getString(id, _StringTypes.StringTypes.MESSAGE);
        return this.processString(text, context);
    };
    LocalizedStrings.prototype.getUI = function (id, context) {
        if (context === void 0) {
            context = [];
        }
        var text = this.getString(id, _StringTypes.StringTypes.UI);
        return this.processString(text, context);
    };
    LocalizedStrings.prototype.processString = function (text, context) {
        for (var i = 0; i < context.length; i++) {
            var v = context[i];
            text = text.replace('\$' + i, v);
        }
        return text;
    };
    LocalizedStrings.prototype.updateTagText = function (func) {
        var _this = this;
        if (func === void 0) {
            func = null;
        }
        if (this.document !== null) {
            var list = this.document.querySelectorAll("data.i18n");
            list.forEach(function (node) {
                if (func === null) {
                    node.innerHTML = _this.processTagTex(node.getAttribute("value"));
                } else {
                    node.innerHTML = func(node.getAttribute("value"));
                }
            });
        }
    };
    LocalizedStrings.prototype.processTagTex = function (text) {
        if (text === null) {
            return "<Invalid i18n identifier>";
        }
        var opts = text.split(':');
        var type = opts[0].toLowerCase();
        var id = opts[1];
        if (_StringTypes.StringTypes.ERROR === type) {
            return this.getError(id);
        } else if (_StringTypes.StringTypes.MESSAGE === type) {
            return this.getMessage(id);
        } else if (_StringTypes.StringTypes.UI === type) {
            return this.getUI(id);
        } else {
            console.warn(" A string has been passed to the i18n helper function that was not in the form type:id -> " + text);
            return this.getString(id, type);
        }
    };
    return LocalizedStrings;
}();
exports.LocalizedStrings = LocalizedStrings;

/***/ }),

/***/ "./node_modules/line-i18n/dist/StringTypes.js":
/*!****************************************************!*\
  !*** ./node_modules/line-i18n/dist/StringTypes.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
var StringTypes = exports.StringTypes = undefined;
(function (StringTypes) {
    StringTypes["ERROR"] = "error";
    StringTypes["MESSAGE"] = "message";
    StringTypes["UI"] = "ui";
})(StringTypes || (exports.StringTypes = StringTypes = {}));

/***/ }),

/***/ "./node_modules/line-i18n/dist/index.js":
/*!**********************************************!*\
  !*** ./node_modules/line-i18n/dist/index.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});

var _LanguageService = __webpack_require__(/*! ./LanguageService */ "./node_modules/line-i18n/dist/LanguageService.js");

var _LocalizedStrings = __webpack_require__(/*! ./LocalizedStrings */ "./node_modules/line-i18n/dist/LocalizedStrings.js");

var _StringTypes = __webpack_require__(/*! ./StringTypes */ "./node_modules/line-i18n/dist/StringTypes.js");

var _LanguageServiceNoLS = __webpack_require__(/*! ./LanguageServiceNoLS */ "./node_modules/line-i18n/dist/LanguageServiceNoLS.js");

exports.default = {
    LanguageService: _LanguageService.LanguageService,
    LanguageServiceNoLS: _LanguageServiceNoLS.LanguageServiceNoLS,
    LocalizedStrings: _LocalizedStrings.LocalizedStrings,
    StringTypes: _StringTypes.StringTypes
};

/***/ }),

/***/ "./node_modules/melanke-watchjs/src/watch.js":
/*!***************************************************!*\
  !*** ./node_modules/melanke-watchjs/src/watch.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
 * DEVELOPED BY
 * GIL LOPES BUENO
 * gilbueno.mail@gmail.com
 *
 * WORKS WITH:
 * IE8*, IE 9+, FF 4+, SF 5+, WebKit, CH 7+, OP 12+, BESEN, Rhino 1.7+
 * For IE8 (and other legacy browsers) WatchJS will use dirty checking  
 *
 * FORK:
 * https://github.com/melanke/Watch.JS
 *
 * LICENSE: MIT
 */



var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

(function (factory) {
    if (( false ? undefined : _typeof(exports)) === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like enviroments that support module.exports,
        // like Node.
        module.exports = factory();
    } else if (true) {
        // AMD. Register as an anonymous module.
        !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
				__WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
    } else {}
})(function () {

    var WatchJS = {
        noMore: false, // use WatchJS.suspend(obj) instead
        useDirtyCheck: false, // use only dirty checking to track changes.
        preserveExistingSetters: false
    },
        lengthsubjects = [];

    var dirtyChecklist = [];
    var pendingChanges = []; // used coalesce changes from defineProperty and __defineSetter__

    var supportDefineProperty = false;
    try {
        supportDefineProperty = Object.defineProperty && Object.defineProperty({}, 'x', {});
    } catch (ex) {/* not supported */}

    var isFunction = function isFunction(functionToCheck) {
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) == '[object Function]';
    };

    var isInt = function isInt(x) {
        return x % 1 === 0;
    };

    var isArray = function isArray(obj) {
        return Object.prototype.toString.call(obj) === '[object Array]';
    };

    var isObject = function isObject(obj) {
        return {}.toString.apply(obj) === '[object Object]';
    };

    var getObjDiff = function getObjDiff(a, b) {
        var aplus = [],
            bplus = [];

        if (!(typeof a == "string") && !(typeof b == "string")) {

            if (isArray(a) && b) {
                for (var i = 0; i < a.length; i++) {
                    if (b[i] === undefined) aplus.push(i);
                }
            } else {
                for (var i in a) {
                    if (a.hasOwnProperty(i)) {
                        if (b && !b.hasOwnProperty(i)) {
                            aplus.push(i);
                        }
                    }
                }
            }

            if (isArray(b) && a) {
                for (var j = 0; j < b.length; j++) {
                    if (a[j] === undefined) bplus.push(j);
                }
            } else {
                for (var j in b) {
                    if (b.hasOwnProperty(j)) {
                        if (a && !a.hasOwnProperty(j)) {
                            bplus.push(j);
                        }
                    }
                }
            }
        }

        return {
            added: aplus,
            removed: bplus
        };
    };

    var clone = function clone(obj) {

        if (null == obj || "object" != (typeof obj === 'undefined' ? 'undefined' : _typeof(obj))) {
            return obj;
        }

        var copy = obj.constructor();

        for (var attr in obj) {
            copy[attr] = obj[attr];
        }

        return copy;
    };

    var getExistingSetter = function getExistingSetter(obj, propName) {
        if (WatchJS.preserveExistingSetters) {
            var existing = Object.getOwnPropertyDescriptor(obj, propName);
            return existing.set;
        }

        return undefined;
    };

    var defineGetAndSet = function defineGetAndSet(obj, propName, getter, setter) {
        try {
            var existingSetter = getExistingSetter(obj, propName);
            Object.defineProperty(obj, propName, {
                get: getter,
                set: function set(value) {
                    setter.call(this, value, true); // coalesce changes
                    if (existingSetter) {
                        existingSetter(value);
                    }
                },
                enumerable: true,
                configurable: true
            });
        } catch (e1) {
            try {
                Object.prototype.__defineGetter__.call(obj, propName, getter);
                Object.prototype.__defineSetter__.call(obj, propName, function (value) {
                    setter.call(this, value, true); // coalesce changes
                });
            } catch (e2) {
                observeDirtyChanges(obj, propName, setter);
                //throw new Error("watchJS error: browser not supported :/")
            }
        }
    };

    var defineProp = function defineProp(obj, propName, value) {
        try {
            Object.defineProperty(obj, propName, {
                enumerable: false,
                configurable: true,
                writable: false,
                value: value
            });
        } catch (error) {
            obj[propName] = value;
        }
    };

    var observeDirtyChanges = function observeDirtyChanges(obj, propName, setter) {
        dirtyChecklist[dirtyChecklist.length] = {
            prop: propName,
            object: obj,
            orig: clone(obj[propName]),
            callback: setter
        };
    };

    var watch = function watch() {

        if (isFunction(arguments[1])) {
            watchAll.apply(this, arguments);
        } else if (isArray(arguments[1])) {
            watchMany.apply(this, arguments);
        } else {
            watchOne.apply(this, arguments);
        }
    };

    var watchAll = function watchAll(obj, watcher, level, addNRemove) {

        if (typeof obj == "string" || !(obj instanceof Object) && !isArray(obj)) {
            //accepts only objects and array (not string)
            return;
        }

        if (isArray(obj)) {
            defineWatcher(obj, "__watchall__", watcher, level); // watch all changes on the array
            if (level === undefined || level > 0) {
                for (var prop = 0; prop < obj.length; prop++) {
                    // watch objects in array
                    watchAll(obj[prop], watcher, level, addNRemove);
                }
            }
        } else {
            var prop,
                props = [];
            for (prop in obj) {
                //for each attribute if obj is an object
                if (prop == "$val" || !supportDefineProperty && prop === 'watchers') {
                    continue;
                }

                if (Object.prototype.hasOwnProperty.call(obj, prop)) {
                    props.push(prop); //put in the props
                }
            }
            watchMany(obj, props, watcher, level, addNRemove); //watch all items of the props
        }

        if (addNRemove) {
            pushToLengthSubjects(obj, "$$watchlengthsubjectroot", watcher, level);
        }
    };

    var watchMany = function watchMany(obj, props, watcher, level, addNRemove) {

        if (typeof obj == "string" || !(obj instanceof Object) && !isArray(obj)) {
            //accepts only objects and array (not string)
            return;
        }

        for (var i = 0; i < props.length; i++) {
            //watch each property
            var prop = props[i];
            watchOne(obj, prop, watcher, level, addNRemove);
        }
    };

    var watchOne = function watchOne(obj, prop, watcher, level, addNRemove) {
        if (typeof obj == "string" || !(obj instanceof Object) && !isArray(obj)) {
            //accepts only objects and array (not string)
            return;
        }

        if (isFunction(obj[prop])) {
            //dont watch if it is a function
            return;
        }
        if (obj[prop] != null && (level === undefined || level > 0)) {
            watchAll(obj[prop], watcher, level !== undefined ? level - 1 : level); //recursively watch all attributes of this
        }

        defineWatcher(obj, prop, watcher, level);

        if (addNRemove && (level === undefined || level > 0)) {
            pushToLengthSubjects(obj, prop, watcher, level);
        }
    };

    var unwatch = function unwatch() {

        if (isFunction(arguments[1])) {
            unwatchAll.apply(this, arguments);
        } else if (isArray(arguments[1])) {
            unwatchMany.apply(this, arguments);
        } else {
            unwatchOne.apply(this, arguments);
        }
    };

    var unwatchAll = function unwatchAll(obj, watcher) {

        if (obj instanceof String || !(obj instanceof Object) && !isArray(obj)) {
            //accepts only objects and array (not string)
            return;
        }

        if (isArray(obj)) {
            var props = ['__watchall__'];
            for (var prop = 0; prop < obj.length; prop++) {
                //for each item if obj is an array
                props.push(prop); //put in the props
            }
            unwatchMany(obj, props, watcher); //watch all itens of the props
        } else {
            var unwatchPropsInObject = function unwatchPropsInObject(obj2) {
                var props = [];
                for (var prop2 in obj2) {
                    //for each attribute if obj is an object
                    if (obj2.hasOwnProperty(prop2)) {
                        if (obj2[prop2] instanceof Object) {
                            unwatchPropsInObject(obj2[prop2]); //recurs into object props
                        } else {
                            props.push(prop2); //put in the props
                        }
                    }
                }
                unwatchMany(obj2, props, watcher); //unwatch all of the props
            };
            unwatchPropsInObject(obj);
        }
    };

    var unwatchMany = function unwatchMany(obj, props, watcher) {

        for (var prop2 in props) {
            //watch each attribute of "props" if is an object
            if (props.hasOwnProperty(prop2)) {
                unwatchOne(obj, props[prop2], watcher);
            }
        }
    };

    var timeouts = [],
        timerID = null;
    function clearTimerID() {
        timerID = null;
        for (var i = 0; i < timeouts.length; i++) {
            timeouts[i]();
        }
        timeouts.length = 0;
    }
    var getTimerID = function getTimerID() {
        if (!timerID) {
            timerID = setTimeout(clearTimerID);
        }
        return timerID;
    };
    var registerTimeout = function registerTimeout(fn) {
        // register function to be called on timeout
        if (timerID == null) getTimerID();
        timeouts[timeouts.length] = fn;
    };

    // Track changes made to an array, object or an object's property 
    // and invoke callback with a single change object containing type, value, oldvalue and array splices
    // Syntax: 
    //      trackChange(obj, callback, recursive, addNRemove)
    //      trackChange(obj, prop, callback, recursive, addNRemove)
    var trackChange = function trackChange() {
        var fn = isFunction(arguments[2]) ? trackProperty : trackObject;
        fn.apply(this, arguments);
    };

    // track changes made to an object and invoke callback with a single change object containing type, value and array splices
    var trackObject = function trackObject(obj, callback, recursive, addNRemove) {
        var change = null,
            lastTimerID = -1;
        var isArr = isArray(obj);
        var level,
            fn = function fn(prop, action, newValue, oldValue) {
            var timerID = getTimerID();
            if (lastTimerID !== timerID) {
                // check if timer has changed since last update
                lastTimerID = timerID;
                change = {
                    type: 'update'
                };
                change['value'] = obj;
                change['splices'] = null;
                registerTimeout(function () {
                    callback.call(this, change);
                    change = null;
                });
            }
            // create splices for array changes
            if (isArr && obj === this && change !== null) {
                if (action === 'pop' || action === 'shift') {
                    newValue = [];
                    oldValue = [oldValue];
                } else if (action === 'push' || action === 'unshift') {
                    newValue = [newValue];
                    oldValue = [];
                } else if (action !== 'splice') {
                    return; // return here - for reverse and sort operations we don't need to return splices. a simple update will do
                }
                if (!change.splices) change.splices = [];
                change.splices[change.splices.length] = {
                    index: prop,
                    deleteCount: oldValue ? oldValue.length : 0,
                    addedCount: newValue ? newValue.length : 0,
                    added: newValue,
                    deleted: oldValue
                };
            }
        };
        level = recursive == true ? undefined : 0;
        watchAll(obj, fn, level, addNRemove);
    };

    // track changes made to the property of an object and invoke callback with a single change object containing type, value, oldvalue and splices
    var trackProperty = function trackProperty(obj, prop, callback, recursive, addNRemove) {
        if (obj && prop) {
            watchOne(obj, prop, function (prop, action, newvalue, oldvalue) {
                var change = {
                    type: 'update'
                };
                change['value'] = newvalue;
                change['oldvalue'] = oldvalue;
                if (recursive && isObject(newvalue) || isArray(newvalue)) {
                    trackObject(newvalue, callback, recursive, addNRemove);
                }
                callback.call(this, change);
            }, 0);

            if (recursive && isObject(obj[prop]) || isArray(obj[prop])) {
                trackObject(obj[prop], callback, recursive, addNRemove);
            }
        }
    };

    var defineWatcher = function defineWatcher(obj, prop, watcher, level) {
        var newWatcher = false;
        var isArr = isArray(obj);

        if (!obj.watchers) {
            defineProp(obj, "watchers", {});
            if (isArr) {
                // watch array functions
                watchFunctions(obj, function (index, action, newValue, oldValue) {
                    addPendingChange(obj, index, action, newValue, oldValue);
                    if (level !== 0 && newValue && (isObject(newValue) || isArray(newValue))) {
                        var i,
                            n,
                            ln,
                            wAll,
                            watchList = obj.watchers[prop];
                        if (wAll = obj.watchers['__watchall__']) {
                            watchList = watchList ? watchList.concat(wAll) : wAll;
                        }
                        ln = watchList ? watchList.length : 0;
                        for (i = 0; i < ln; i++) {
                            if (action !== 'splice') {
                                watchAll(newValue, watchList[i], level === undefined ? level : level - 1);
                            } else {
                                // watch spliced values
                                for (n = 0; n < newValue.length; n++) {
                                    watchAll(newValue[n], watchList[i], level === undefined ? level : level - 1);
                                }
                            }
                        }
                    }
                });
            }
        }

        if (!obj.watchers[prop]) {
            obj.watchers[prop] = [];
            if (!isArr) newWatcher = true;
        }

        for (var i = 0; i < obj.watchers[prop].length; i++) {
            if (obj.watchers[prop][i] === watcher) {
                return;
            }
        }

        obj.watchers[prop].push(watcher); //add the new watcher to the watchers array

        if (newWatcher) {
            var val = obj[prop];
            var getter = function getter() {
                return val;
            };

            var setter = function setter(newval, delayWatcher) {
                var oldval = val;
                val = newval;
                if (level !== 0 && obj[prop] && (isObject(obj[prop]) || isArray(obj[prop])) && !obj[prop].watchers) {
                    // watch sub properties
                    var i,
                        ln = obj.watchers[prop].length;
                    for (i = 0; i < ln; i++) {
                        watchAll(obj[prop], obj.watchers[prop][i], level === undefined ? level : level - 1);
                    }
                }

                //watchFunctions(obj, prop);

                if (isSuspended(obj, prop)) {
                    resume(obj, prop);
                    return;
                }

                if (!WatchJS.noMore) {
                    // this does not work with Object.observe
                    //if (JSON.stringify(oldval) !== JSON.stringify(newval)) {
                    if (oldval !== newval) {
                        if (!delayWatcher) {
                            callWatchers(obj, prop, "set", newval, oldval);
                        } else {
                            addPendingChange(obj, prop, "set", newval, oldval);
                        }
                        WatchJS.noMore = false;
                    }
                }
            };

            if (WatchJS.useDirtyCheck) {
                observeDirtyChanges(obj, prop, setter);
            } else {
                defineGetAndSet(obj, prop, getter, setter);
            }
        }
    };

    var callWatchers = function callWatchers(obj, prop, action, newval, oldval) {
        if (prop !== undefined) {
            var ln,
                wl,
                watchList = obj.watchers[prop];
            if (wl = obj.watchers['__watchall__']) {
                watchList = watchList ? watchList.concat(wl) : wl;
            }
            ln = watchList ? watchList.length : 0;
            for (var wr = 0; wr < ln; wr++) {
                watchList[wr].call(obj, prop, action, newval, oldval);
            }
        } else {
            for (var prop in obj) {
                //call all
                if (obj.hasOwnProperty(prop)) {
                    callWatchers(obj, prop, action, newval, oldval);
                }
            }
        }
    };

    var methodNames = ['pop', 'push', 'reverse', 'shift', 'sort', 'slice', 'unshift', 'splice'];
    var defineArrayMethodWatcher = function defineArrayMethodWatcher(obj, original, methodName, callback) {
        defineProp(obj, methodName, function () {
            var index = 0;
            var i, newValue, oldValue, response;
            // get values before splicing array 
            if (methodName === 'splice') {
                var start = arguments[0];
                var end = start + arguments[1];
                oldValue = obj.slice(start, end);
                newValue = [];
                for (i = 2; i < arguments.length; i++) {
                    newValue[i - 2] = arguments[i];
                }
                index = start;
            } else {
                newValue = arguments.length > 0 ? arguments[0] : undefined;
            }

            response = original.apply(obj, arguments);
            if (methodName !== 'slice') {
                if (methodName === 'pop') {
                    oldValue = response;
                    index = obj.length;
                } else if (methodName === 'push') {
                    index = obj.length - 1;
                } else if (methodName === 'shift') {
                    oldValue = response;
                } else if (methodName !== 'unshift' && newValue === undefined) {
                    newValue = response;
                }
                callback.call(obj, index, methodName, newValue, oldValue);
            }
            return response;
        });
    };

    var watchFunctions = function watchFunctions(obj, callback) {

        if (!isFunction(callback) || !obj || obj instanceof String || !isArray(obj)) {
            return;
        }

        for (var i = methodNames.length, methodName; i--;) {
            methodName = methodNames[i];
            defineArrayMethodWatcher(obj, obj[methodName], methodName, callback);
        }
    };

    var unwatchOne = function unwatchOne(obj, prop, watcher) {
        if (prop) {
            if (obj.watchers && obj.watchers[prop]) {
                if (watcher === undefined) {
                    delete obj.watchers[prop]; // remove all property watchers
                } else {
                    for (var i = 0; i < obj.watchers[prop].length; i++) {
                        var w = obj.watchers[prop][i];
                        if (w == watcher) {
                            obj.watchers[prop].splice(i, 1);
                        }
                    }
                }
            }
        } else {
            delete obj.watchers;
        }

        removeFromLengthSubjects(obj, prop, watcher);
        removeFromDirtyChecklist(obj, prop);
    };

    // suspend watchers until next update cycle
    var suspend = function suspend(obj, prop) {
        if (obj.watchers) {
            var name = '__wjs_suspend__' + (prop !== undefined ? prop : '');
            obj.watchers[name] = true;
        }
    };

    var isSuspended = function isSuspended(obj, prop) {
        return obj.watchers && (obj.watchers['__wjs_suspend__'] || obj.watchers['__wjs_suspend__' + prop]);
    };

    // resumes preivously suspended watchers
    var resume = function resume(obj, prop) {
        registerTimeout(function () {
            delete obj.watchers['__wjs_suspend__'];
            delete obj.watchers['__wjs_suspend__' + prop];
        });
    };

    var pendingTimerID = null;
    var addPendingChange = function addPendingChange(obj, prop, mode, newval, oldval) {
        pendingChanges[pendingChanges.length] = {
            obj: obj,
            prop: prop,
            mode: mode,
            newval: newval,
            oldval: oldval
        };
        if (pendingTimerID === null) {
            pendingTimerID = setTimeout(applyPendingChanges);
        }
    };

    var applyPendingChanges = function applyPendingChanges() {
        // apply pending changes
        var change = null;
        pendingTimerID = null;
        for (var i = 0; i < pendingChanges.length; i++) {
            change = pendingChanges[i];
            callWatchers(change.obj, change.prop, change.mode, change.newval, change.oldval);
        }
        if (change) {
            pendingChanges = [];
            change = null;
        }
    };

    var loop = function loop() {

        // check for new or deleted props
        for (var i = 0; i < lengthsubjects.length; i++) {

            var subj = lengthsubjects[i];

            if (subj.prop === "$$watchlengthsubjectroot") {

                var difference = getObjDiff(subj.obj, subj.actual);

                if (difference.added.length || difference.removed.length) {
                    if (difference.added.length) {
                        watchMany(subj.obj, difference.added, subj.watcher, subj.level - 1, true);
                    }

                    subj.watcher.call(subj.obj, "root", "differentattr", difference, subj.actual);
                }
                subj.actual = clone(subj.obj);
            } else {

                var difference = getObjDiff(subj.obj[subj.prop], subj.actual);

                if (difference.added.length || difference.removed.length) {
                    if (difference.added.length) {
                        for (var j = 0; j < subj.obj.watchers[subj.prop].length; j++) {
                            watchMany(subj.obj[subj.prop], difference.added, subj.obj.watchers[subj.prop][j], subj.level - 1, true);
                        }
                    }

                    callWatchers(subj.obj, subj.prop, "differentattr", difference, subj.actual);
                }

                subj.actual = clone(subj.obj[subj.prop]);
            }
        }

        // start dirty check
        var n, value;
        if (dirtyChecklist.length > 0) {
            for (var i = 0; i < dirtyChecklist.length; i++) {
                n = dirtyChecklist[i];
                value = n.object[n.prop];
                if (!compareValues(n.orig, value)) {
                    n.orig = clone(value);
                    n.callback(value);
                }
            }
        }
    };

    var compareValues = function compareValues(a, b) {
        var i,
            state = true;
        if (a !== b) {
            if (isObject(a)) {
                for (i in a) {
                    if (!supportDefineProperty && i === 'watchers') continue;
                    if (a[i] !== b[i]) {
                        state = false;
                        break;
                    };
                }
            } else {
                state = false;
            }
        }
        return state;
    };

    var pushToLengthSubjects = function pushToLengthSubjects(obj, prop, watcher, level) {

        var actual;

        if (prop === "$$watchlengthsubjectroot") {
            actual = clone(obj);
        } else {
            actual = clone(obj[prop]);
        }

        lengthsubjects.push({
            obj: obj,
            prop: prop,
            actual: actual,
            watcher: watcher,
            level: level
        });
    };

    var removeFromLengthSubjects = function removeFromLengthSubjects(obj, prop, watcher) {
        for (var i = 0; i < lengthsubjects.length; i++) {
            var subj = lengthsubjects[i];

            if (subj.obj == obj) {
                if (!prop || subj.prop == prop) {
                    if (!watcher || subj.watcher == watcher) {
                        // if we splice off one item at position i
                        // we need to decrement i as the array is one item shorter
                        // so when we increment i in the loop statement we
                        // will land at the correct index.
                        // if it's not decremented, you won't delete all length subjects
                        lengthsubjects.splice(i--, 1);
                    }
                }
            }
        }
    };

    var removeFromDirtyChecklist = function removeFromDirtyChecklist(obj, prop) {
        var notInUse;
        for (var i = 0; i < dirtyChecklist.length; i++) {
            var n = dirtyChecklist[i];
            var watchers = n.object.watchers;
            notInUse = n.object == obj && (!prop || n.prop == prop) && watchers && (!prop || !watchers[prop] || watchers[prop].length == 0);
            if (notInUse) {
                // we use the same syntax as in removeFromLengthSubjects
                dirtyChecklist.splice(i--, 1);
            }
        }
    };

    setInterval(loop, 50);

    WatchJS.watch = watch;
    WatchJS.unwatch = unwatch;
    WatchJS.callWatchers = callWatchers;
    WatchJS.suspend = suspend; // suspend watchers    
    WatchJS.onChange = trackChange; // track changes made to object or  it's property and return a single change object

    return WatchJS;
});

/***/ }),

/***/ "./node_modules/node-libs-browser/mock/empty.js":
/*!******************************************************!*\
  !*** ./node_modules/node-libs-browser/mock/empty.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/***/ }),

/***/ "./node_modules/webpack/buildin/module.js":
/*!***********************************!*\
  !*** (webpack)/buildin/module.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = function (module) {
	if (!module.webpackPolyfill) {
		module.deprecate = function () {};
		module.paths = [];
		// module.parent = undefined by default
		if (!module.children) module.children = [];
		Object.defineProperty(module, "loaded", {
			enumerable: true,
			get: function get() {
				return module.l;
			}
		});
		Object.defineProperty(module, "id", {
			enumerable: true,
			get: function get() {
				return module.i;
			}
		});
		module.webpackPolyfill = 1;
	}
	return module;
};

/***/ })

/******/ });
});
//# sourceMappingURL=ivprog.bundle.js.map